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 |
|---|---|---|---|---|---|---|---|---|
// -----------------------------------------------------------------------
// <copyright file="AnyRadixConvert.cs" company="OSharp开源团队">
// Copyright (c) 2014 OSharp. All rights reserved.
// </copyright>
// <last-editor>郭明锋</last-editor>
// <last-date>2014-07-18 16:10</last-date>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OSharp.Utility.Extensions;
namespace OSharp.Utility.Data
{
/// <summary>
/// 任意[2,62]进制转换器
/// </summary>
public static class AnyRadixConvert
{
private const string BaseChar = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
/// <summary>
/// 将指定基数的数字的字符串表示形式转换为等效的64位有符号整数
/// </summary>
/// <param name="value">指定基数的数字的字符串表示</param>
/// <param name="fromRadix">字符串的基数,必须为[2,62]范围内</param>
/// <returns>等效于value的数值的64位有符号整数</returns>
public static ulong X2H(string value, int fromRadix)
{
value.CheckNotNullOrEmpty("value");
fromRadix.CheckBetween("fromRadix", 2, 62, true, true);
value = value.Trim();
if (value == string.Empty)
{
return 0L;
}
string baseChar = BaseChar.Substring(0, fromRadix);
ulong result = 0;
for (int i = 0; i < value.Length; i++)
{
char @char = value[i];
if (!baseChar.Contains(@char))
{
throw new ArgumentException(string.Format("参数中的字符\"{0}\"不是 {1} 进制数的有效字符。", @char, fromRadix));
}
try
{
result += (ulong)baseChar.IndexOf(@char) * (ulong)Math.Pow(baseChar.Length, value.Length - i - 1);
}
catch (Exception)
{
throw new OverflowException("运算溢出。");
}
}
return result;
}
/// <summary>
/// 将64位有符号整数形式的数值转换为指定基数的数值的字符串形式
/// </summary>
/// <param name="value">64位有符号整数形式的数值</param>
/// <param name="toRadix">要转换的目标基数,必须为[2,62]范围内</param>
/// <returns>指定基数的数值的字符串形式</returns>
public static string H2X(ulong value, int toRadix)
{
toRadix.CheckBetween("fromRadix", 2, 62, true, true);
string baseChar = BaseChar.Substring(0, toRadix);
string result = string.Empty;
while (value > 0)
{
int index = (int)(value % (ulong)baseChar.Length);
result = baseChar[index] + result;
value = value / (ulong)baseChar.Length;
}
return result;
}
/// <summary>
/// 任意进制转换,将源进制表示的value转换为目标进制,进制的字母顺序为先大写后小写
/// </summary>
/// <param name="value">要转换的数据</param>
/// <param name="fromRadix">源进制数,必须为[2,62]范围内</param>
/// <param name="toRadix">目标进制数,必须为[2,62]范围内</param>
/// <returns></returns>
public static string X2X(string value, int fromRadix, int toRadix)
{
value.CheckNotNullOrEmpty("value");
fromRadix.CheckBetween("fromRadix", 2, 62, true, true);
toRadix.CheckBetween("toRadix", 2, 62, true, true);
ulong num = X2H(value, fromRadix);
return H2X(num, toRadix);
}
/// <summary>
/// 10进制数字转换为16进制字符串
/// </summary>
/// <param name="value">10进制数</param>
/// <returns>16进制数的字符串</returns>
public static string _10To16(int value)
{
string str = X2X(value.ToString(CultureInfo.InvariantCulture), 10, 16);
return str.IsNullOrEmpty() ? "0" : str[0] == '0' ? str : '0' + str;
}
/// <summary>
/// 16进制字符串转换为10进制数字
/// </summary>
public static int _16To10(string value)
{
value = value.ToUpper();
return X2X(value, 16, 10).CastTo<int>();
}
}
}
| 34.918699
| 119
| 0.497788
|
[
"Apache-2.0"
] |
J-W-Chan/osharp
|
src/OSharp.Utility/Data/AnyRadixConvert.cs
| 4,835
|
C#
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
/// Name: Cory Siebler
/// ASUID: 1000832292
/// Email: csiebler@asu.edu
/// Class: ASU CSE 445 (#11845)
namespace HotelBookingSystem
{
/// <summary>
/// The HotelSupplier uses a pricing model to calculate the room price. If the new price is lower than the previous price, it emits a
/// (promotional) event and calls the event handlers in the travel agencies that have subscribed to the event. ⦁The HotelSupplier receives
/// the encoded string from the MultiCellBuffer and sends the string to the Decoder for decoding. The HotelSupplier creates a new thread to
/// process the order.
/// </summary>
public class HotelSupplier
{
private const int P_MAX = 10; // Constant for Maximum Price Cuts
private int p = 1; // Counter for the price cuts
private double currentPrice = 0.0; // Current Unit Price for the rooms
private double previousPrice = 0.0; // Previous Unit Price for the rooms
private static Random random = new Random(); // Random number generator
private ArrayList processingThreads = new ArrayList();
public delegate void PriceCutHandler(PriceCutEventArgs e);
public event PriceCutHandler PriceCut;
/// <summary>
/// Event fired once a PriceCut has occurred.
/// </summary>
private void PriceCutEvent()
{
// Make sure the event is subscribed to
if (PriceCut != null)
{
// Fire the PriceCut event
Console.WriteLine("\nEVENT: Performing Price Cut Event (#{0}) ({1})\n", p, Thread.CurrentThread.Name);
p++;
PriceCut(new PriceCutEventArgs(Thread.CurrentThread.Name, currentPrice));
}
else
{
Console.WriteLine("ERROR: No PriceCut event subscribers");
}
}
/// <summary>
/// Execution thread for the HotelSupplier class. Sets the price from the PricingModel, fires PriceCut events if price is lowered, and
/// processes any orders received from the Multi-Cell buffer.
/// </summary>
public void Run()
{
// Continue until P_MAX price cuts have been sent
while (p <= P_MAX)
{
// Calculate the Unit Price for rooms from the Pricing model
SetPrice();
if (Program.DEBUG)
{
Console.WriteLine("CHECKING: ({0}) Price Comparison ({1} to {2})",
Thread.CurrentThread.Name,
previousPrice.ToString("C"),
currentPrice.ToString("C")
);
}
// Check if the previous price was more than the current price
if (currentPrice < previousPrice)
{
// PriceCut has been made, fire the event
PriceCutEvent();
}
// Initialize the Previous Price to the Current Price
previousPrice = currentPrice;
// Retrieve and Process orders from the Multi-Cell buffer
ProcessOrder(RetrieveOrder());
//Console.WriteLine("WAITING: Hotel Supplier Thread ({0})", Thread.CurrentThread.Name);
//Thread.Sleep(5000);
}
foreach (Thread item in processingThreads)
{
while (item.IsAlive);
}
Console.WriteLine("CLOSING: Hotel Supplier Thread ({0})", Thread.CurrentThread.Name);
}
/// <summary>
/// Calculate the price from the PricingModel.
/// </summary>
private void SetPrice()
{
DateTime today = DateTime.Now;
DateTime future = today.AddDays(random.Next(1,10));
if (Program.DEBUG) Console.WriteLine("PRICING: ({0}) Starting Calculation", Thread.CurrentThread.Name);
previousPrice = currentPrice;
currentPrice = PricingModel.GetRates(random.NextDouble(), today, future);
if (Program.DEBUG)
{
Console.WriteLine("PRICING: ({0}) Price Finalized ({1})",
Thread.CurrentThread.Name,
currentPrice.ToString("C")
);
}
}
/// <summary>
/// Collect orders from the Multi-Cell Buffer
/// </summary>
/// <returns>Order retrieved from the Multi-Cell Buffer</returns>
private OrderClass RetrieveOrder()
{
return Decoder.DecodeOrder(Program.mb.getOneCell());
}
/// <summary>
/// Create a new thread to process the order.
/// </summary>
/// <param name="order">Order from the TravelAgency threads</param>
private void ProcessOrder(OrderClass order)
{
// Make sure the order is for the current HotelSupplier
if (order.ReceiverId == Thread.CurrentThread.Name || order.ReceiverId == null)
{
Console.WriteLine("RECEIVING: Order for Hotel Supplier ({0})", Thread.CurrentThread.Name);
OrderProcessing processor = new OrderProcessing(order, currentPrice);
Thread processingThread = new Thread(new ThreadStart(processor.ProcessOrder));
processingThreads.Add(processingThread);
processingThread.Name = "Processor_" + Thread.CurrentThread.Name;
processingThread.Start();
}
else
{
Console.WriteLine("SKIPPING: Order not for Hotel Supplier ({0})", Thread.CurrentThread.Name);
}
}
}
}
| 38.357143
| 143
| 0.57034
|
[
"MIT"
] |
crsiebler/HotelBookingSystem
|
HotelBookingSystem/HotelSupplier.cs
| 5,911
|
C#
|
using Microsoft.EntityFrameworkCore;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WalkingTec.Mvvm.Core.Test.VM
{
[TestClass]
public class BaseCRUDVMTestWithOtherID
{
private BaseCRUDVM<SchoolWithOtherID> _schoolvm = new BaseCRUDVM<SchoolWithOtherID>();
private BaseCRUDVM<MajorWithOtherID> _majorvm = new BaseCRUDVM<MajorWithOtherID>();
private BaseCRUDVM<Student> _studentvm = new BaseCRUDVM<Student>();
private string _seed;
public BaseCRUDVMTestWithOtherID()
{
_seed = Guid.NewGuid().ToString();
_schoolvm.DC = new DataContext(_seed, DBTypeEnum.Memory);
_majorvm.DC = new DataContext(_seed, DBTypeEnum.Memory);
_studentvm.DC = new DataContext(_seed, DBTypeEnum.Memory);
_schoolvm.Session = new MockSession();
_majorvm.Session = new MockSession();
_studentvm.Session = new MockSession();
_schoolvm.MSD = new MockMSD();
_majorvm.MSD = new MockMSD();
_studentvm.MSD = new MockMSD();
_schoolvm.LoginUserInfo = new LoginUserInfo { ITCode = "schooluser" };
_majorvm.LoginUserInfo = new LoginUserInfo { ITCode = "majoruser" };
_studentvm.LoginUserInfo = new LoginUserInfo { ITCode = "studentuser" };
Mock<IServiceProvider> mockService = new Mock<IServiceProvider>();
mockService.Setup(x => x.GetService(typeof(GlobalData))).Returns(new GlobalData());
mockService.Setup(x => x.GetService(typeof(Configs))).Returns(new Configs());
GlobalServices.SetServiceProvider(mockService.Object);
}
[TestMethod]
[Description("单表添加")]
[DataTestMethod]
[DataRow("111", "test1", SchoolTypeEnum.PRI, "remark1")]
[DataRow("222","test2", SchoolTypeEnum.PUB,"remark2")]
public void SingleTableDoAdd(string code, string name, SchoolTypeEnum schooltype, string remark)
{
SchoolWithOtherID s = new SchoolWithOtherID();
s.SchoolCode = code;
s.SchoolName = name;
s.SchoolType = schooltype;
s.Remark = remark;
_schoolvm.Entity = s;
_schoolvm.DoAdd();
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
var rv = context.Set<SchoolWithOtherID>().ToList();
Assert.AreEqual(1, rv.Count());
Assert.AreEqual(code, rv[0].SchoolCode);
Assert.AreEqual(name, rv[0].SchoolName);
Assert.AreEqual(schooltype, rv[0].SchoolType);
Assert.AreEqual(remark, rv[0].Remark);
}
Assert.IsTrue(_schoolvm.MSD.Count == 0);
}
[TestMethod]
[Description("单表修改全部字段")]
[DataTestMethod]
[DataRow("111", "test1", SchoolTypeEnum.PRI, "remark1")]
[DataRow("222", "test2", SchoolTypeEnum.PUB, "remark2")]
public void SingleTableDoEdit(string code, string name, SchoolTypeEnum schooltype, string remark)
{
SchoolWithOtherID s = new SchoolWithOtherID();
s.SchoolCode = "000";
s.SchoolName = "default";
s.SchoolType = null;
s.Remark = "default";
_schoolvm.Entity = s;
_schoolvm.DoAdd();
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
SchoolWithOtherID s2 = new SchoolWithOtherID();
s2.SchoolCode = code;
s2.SchoolName = name;
s2.SchoolType = schooltype;
s2.Remark = remark;
s2.ID = s.ID;
_schoolvm.DC = context;
_schoolvm.Entity = s2;
_schoolvm.DoEdit(true);
}
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
var rv = context.Set<SchoolWithOtherID>().ToList();
Assert.AreEqual(1, rv.Count());
Assert.AreEqual(code, rv[0].SchoolCode);
Assert.AreEqual(name, rv[0].SchoolName);
Assert.AreEqual(schooltype, rv[0].SchoolType);
Assert.AreEqual(remark, rv[0].Remark);
}
}
[TestMethod]
[Description("单表修改指定字段")]
[DataTestMethod]
[DataRow("111", "test1", SchoolTypeEnum.PRI, "remark1")]
[DataRow("222", "test2", SchoolTypeEnum.PUB, "remark2")]
public void SingleTableDoEditFields(string code, string name, SchoolTypeEnum schooltype, string remark)
{
SchoolWithOtherID s = new SchoolWithOtherID();
s.SchoolCode = "000";
s.SchoolName = "default";
s.SchoolType = null;
s.Remark = "default";
_schoolvm.Entity = s;
_schoolvm.DoAdd();
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
SchoolWithOtherID s2 = new SchoolWithOtherID();
s2.SchoolCode = code;
s2.SchoolName = name;
s2.SchoolType = schooltype;
s2.Remark = remark;
s2.ID = s.ID;
_schoolvm.DC = context;
_schoolvm.Entity = s2;
_schoolvm.FC.Add("Entity.SchoolName", name);
_schoolvm.DoEdit();
}
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
var rv = context.Set<SchoolWithOtherID>().ToList();
Assert.AreEqual(1, rv.Count());
Assert.AreEqual("000", rv[0].SchoolCode);
Assert.AreEqual(name, rv[0].SchoolName);
Assert.AreEqual(null, rv[0].SchoolType);
Assert.AreEqual("default", rv[0].Remark);
}
}
[TestMethod]
[Description("单表删除")]
public void SingleTableDelete()
{
SchoolWithOtherID s = new SchoolWithOtherID();
s.SchoolCode = "000";
s.SchoolName = "default";
s.SchoolType = null;
s.Remark = "default";
_schoolvm.Entity = s;
_schoolvm.DoAdd();
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
Assert.AreEqual(1, context.Set<SchoolWithOtherID>().Count());
_schoolvm.DC = context;
_schoolvm.Entity = new SchoolWithOtherID { ID = s.ID };
_schoolvm.DoDelete();
}
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
Assert.AreEqual(0, context.Set<SchoolWithOtherID>().Count());
}
}
[TestMethod]
[Description("一对多主表删除")]
public void One2ManyTableDelete()
{
One2ManyDoAdd();
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
var id = context.Set<SchoolWithOtherID>().AsNoTracking().First().ID;
_schoolvm.DC = context;
_schoolvm.Entity = new SchoolWithOtherID { ID = id };
_schoolvm.DoDelete();
}
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
Assert.AreEqual(0, context.Set<SchoolWithOtherID>().Count());
}
}
[TestMethod]
[Description("多对多主表删除")]
public void Many2ManyTableDelete()
{
Many2ManyDoAdd();
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
var id = context.Set<Student>().AsNoTracking().First().ID;
_studentvm.DC = context;
_studentvm.Entity = new Student { ID = id };
_studentvm.DoRealDelete();
}
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
Assert.AreEqual(1, context.Set<Student>().Count(), "主表是否正确删除");
//Assert.AreEqual(1, context.Set<StudentMajor>().Count(), "子表是否正确删除");
}
}
[TestMethod]
[Description("一对多添加")]
public void One2ManyDoAdd()
{
SchoolWithOtherID s = new SchoolWithOtherID();
s.SchoolCode = "000";
s.SchoolName = "school";
s.SchoolType = SchoolTypeEnum.PRI;
s.Majors = new List<MajorWithOtherID>();
s.Majors.Add(new MajorWithOtherID
{
ID = "id1",
MajorCode = "111",
MajorName = "major1",
MajorType = MajorTypeEnum.Optional
});
s.Majors.Add(new MajorWithOtherID
{
ID = "id2",
MajorCode = "222",
MajorName = "major2",
MajorType = MajorTypeEnum.Required
});
_schoolvm.Entity = s;
_schoolvm.DoAdd();
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
Assert.AreEqual(1, context.Set<SchoolWithOtherID>().Count());
Assert.AreEqual(2, context.Set<MajorWithOtherID>().Count());
var rv = context.Set<MajorWithOtherID>().ToList();
Assert.AreEqual("id1", rv[0].ID);
Assert.AreEqual("111", rv[0].MajorCode);
Assert.AreEqual("major1", rv[0].MajorName);
Assert.AreEqual(MajorTypeEnum.Optional, rv[0].MajorType);
Assert.AreEqual("id2", rv[1].ID);
Assert.AreEqual("222", rv[1].MajorCode);
Assert.AreEqual("major2", rv[1].MajorName);
Assert.AreEqual(MajorTypeEnum.Required, rv[1].MajorType);
Assert.AreEqual("schooluser", rv[0].CreateBy);
Assert.IsTrue(DateTime.Now.Subtract(rv[0].CreateTime.Value).Seconds < 10);
Assert.AreEqual("schooluser", rv[1].CreateBy);
Assert.IsTrue(DateTime.Now.Subtract(rv[1].CreateTime.Value).Seconds < 10);
}
}
[TestMethod]
[Description("多对多添加")]
public void Many2ManyDoAdd()
{
MajorWithOtherID m1 = new MajorWithOtherID
{
ID = "id1",
MajorCode = "111",
MajorName = "major1",
MajorType = MajorTypeEnum.Optional
};
MajorWithOtherID m2 = new MajorWithOtherID
{
ID = "id2",
MajorCode = "222",
MajorName = "major2",
MajorType = MajorTypeEnum.Required
};
Student s1 = new Student
{
LoginName = "s1",
Password = "aaa",
Name = "student1"
};
Student s2 = new Student
{
LoginName = "s2",
Password = "bbb",
Name = "student2"
};
_majorvm.Entity = m1;
_majorvm.DoAdd();
_majorvm.Entity = m2;
_majorvm.DoAdd();
s1.StudentMajorWithOtherID = new List<StudentMajorWithOtherID>();
s1.StudentMajorWithOtherID.Add(new StudentMajorWithOtherID { MajorId = m1.ID });
s2.StudentMajorWithOtherID = new List<StudentMajorWithOtherID>();
s2.StudentMajorWithOtherID.Add(new StudentMajorWithOtherID { MajorId = m2.ID });
_studentvm.Entity = s1;
_studentvm.DoAdd();
_studentvm.Entity = s2;
_studentvm.DoAdd();
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
Assert.AreEqual(2, context.Set<MajorWithOtherID>().Count());
Assert.AreEqual(2, context.Set<Student>().Count());
Assert.AreEqual(2, context.Set<StudentMajorWithOtherID>().Count());
var rv = context.Set<StudentMajorWithOtherID>().ToList();
Assert.AreEqual(s1.ID, rv[0].StudentId);
Assert.AreEqual(m1.ID, rv[0].MajorId);
Assert.AreEqual(s2.ID, rv[1].StudentId);
Assert.AreEqual(m2.ID, rv[1].MajorId);
}
}
[TestMethod]
[Description("一对多修改")]
public void One2ManyDoEdit()
{
One2ManyDoAdd();
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
var id = context.Set<SchoolWithOtherID>().Select(x=>x.ID).First();
var mid = context.Set<MajorWithOtherID>().Select(x => x.ID).First();
SchoolWithOtherID s = new SchoolWithOtherID { ID = id };
s.Majors = new List<MajorWithOtherID>();
s.Majors.Add(new MajorWithOtherID
{
ID = "id3",
MajorCode = "333",
MajorName = "major3",
MajorType = MajorTypeEnum.Optional
});
s.Majors.Add(new MajorWithOtherID { ID = mid, MajorCode = "111update" });
_schoolvm.Entity = s;
_schoolvm.DC = context;
_schoolvm.DoEdit(true);
}
using(var context = new DataContext(_seed, DBTypeEnum.Memory))
{
var id = context.Set<SchoolWithOtherID>().Select(x => x.ID).First();
Assert.AreEqual(1, context.Set<SchoolWithOtherID>().Count());
Assert.AreEqual(2, context.Set<MajorWithOtherID>().Where(x=>x.SchoolId == id).Count());
var rv1 = context.Set<MajorWithOtherID>().Where(x=>x.MajorCode == "111update").SingleOrDefault();
Assert.AreEqual("111update", rv1.MajorCode);
Assert.AreEqual(null, rv1.MajorName);
Assert.AreEqual(null, rv1.MajorType);
var rv2 = context.Set<MajorWithOtherID>().Where(x => x.MajorCode == "333").SingleOrDefault();
Assert.AreEqual("333", rv2.MajorCode);
Assert.AreEqual("major3", rv2.MajorName);
Assert.AreEqual(MajorTypeEnum.Optional, rv2.MajorType);
Assert.AreEqual("schooluser", rv1.UpdateBy);
Assert.IsTrue(DateTime.Now.Subtract(rv1.UpdateTime.Value).Seconds < 10);
Assert.AreEqual("schooluser", rv2.CreateBy);
Assert.IsTrue(DateTime.Now.Subtract(rv2.CreateTime.Value).Seconds < 10);
}
}
[TestMethod]
[Description("一对多修改指定字段")]
public void One2ManyDoEditFields()
{
One2ManyDoAdd();
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
var id = context.Set<SchoolWithOtherID>().Select(x => x.ID).First();
var mid = context.Set<MajorWithOtherID>().Select(x => x.ID).First();
SchoolWithOtherID s = new SchoolWithOtherID { ID = id };
s.Majors = new List<MajorWithOtherID>();
s.Majors.Add(new MajorWithOtherID
{
ID = "id3",
MajorCode = "333",
MajorName = "major3",
MajorType = MajorTypeEnum.Optional
});
s.Majors.Add(new MajorWithOtherID { ID = mid, MajorCode = "111update" });
_schoolvm.Entity = s;
_schoolvm.DC = context;
_schoolvm.FC = new Dictionary<string, object>();
_schoolvm.FC.Add("Entity.Majors[0].MajorCode",null);
_schoolvm.DoEdit();
}
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
var id = context.Set<SchoolWithOtherID>().Select(x => x.ID).First();
Assert.AreEqual(1, context.Set<SchoolWithOtherID>().Count());
Assert.AreEqual(2, context.Set<MajorWithOtherID>().Where(x => x.SchoolId == id).Count());
var rv1 = context.Set<MajorWithOtherID>().Where(x => x.MajorCode == "111update").SingleOrDefault();
Assert.AreEqual("111update", rv1.MajorCode);
Assert.AreEqual("major1", rv1.MajorName);
Assert.AreEqual( MajorTypeEnum.Optional, rv1.MajorType);
var rv2 = context.Set<MajorWithOtherID>().Where(x => x.MajorCode == "333").SingleOrDefault();
Assert.AreEqual("333", rv2.MajorCode);
Assert.AreEqual("major3", rv2.MajorName);
Assert.AreEqual(MajorTypeEnum.Optional, rv2.MajorType);
Assert.AreEqual("schooluser", rv1.UpdateBy);
Assert.IsTrue(DateTime.Now.Subtract(rv1.UpdateTime.Value).Seconds < 10);
Assert.AreEqual("schooluser", rv2.CreateBy);
Assert.IsTrue(DateTime.Now.Subtract(rv2.CreateTime.Value).Seconds < 10);
}
}
[TestMethod]
[Description("多对多修改")]
public void Many2ManyDoEdit()
{
MajorWithOtherID m1 = new MajorWithOtherID
{
ID = "id1",
MajorCode = "111",
MajorName = "major1",
MajorType = MajorTypeEnum.Optional
};
MajorWithOtherID m2 = new MajorWithOtherID
{
ID = "id2",
MajorCode = "222",
MajorName = "major2",
MajorType = MajorTypeEnum.Required
};
MajorWithOtherID m3 = new MajorWithOtherID
{
ID = "id3",
MajorCode = "333",
MajorName = "major3",
MajorType = MajorTypeEnum.Required
};
Student s1 = new Student
{
LoginName = "s1",
Password = "aaa",
Name = "student1"
};
_majorvm.Entity = m1;
_majorvm.DoAdd();
_majorvm.Entity = m2;
_majorvm.DoAdd();
_majorvm.Entity = m3;
_majorvm.DoAdd();
s1.StudentMajorWithOtherID = new List<StudentMajorWithOtherID>();
s1.StudentMajorWithOtherID.Add(new StudentMajorWithOtherID { MajorId = m1.ID });
s1.StudentMajorWithOtherID.Add(new StudentMajorWithOtherID { MajorId = m2.ID });
_studentvm.Entity = s1;
_studentvm.DoAdd();
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
s1.StudentMajorWithOtherID.RemoveAt(0);
s1.StudentMajorWithOtherID.Add(new StudentMajorWithOtherID { MajorId = m3.ID });
_studentvm.DC = context;
_studentvm.Entity = s1;
_studentvm.DoEdit();
}
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
Assert.AreEqual(3, context.Set<MajorWithOtherID>().Count());
Assert.AreEqual(1, context.Set<Student>().Count());
Assert.AreEqual(2, context.Set<StudentMajorWithOtherID>().Count());
var rv1 = context.Set<StudentMajorWithOtherID>().Where(x => x.MajorId == m2.ID).SingleOrDefault();
var rv2 = context.Set<StudentMajorWithOtherID>().Where(x => x.MajorId == m3.ID).SingleOrDefault();
Assert.AreEqual(s1.ID, rv1.StudentId);
Assert.AreEqual(m2.ID, rv1.MajorId);
Assert.AreEqual(s1.ID, rv2.StudentId);
Assert.AreEqual(m3.ID, rv2.MajorId);
}
}
[TestMethod]
[Description("多对多修改清除关联")]
public void Many2ManyDoEditClearRelation()
{
MajorWithOtherID m1 = new MajorWithOtherID
{
ID = "id1",
MajorCode = "111",
MajorName = "major1",
MajorType = MajorTypeEnum.Optional
};
MajorWithOtherID m2 = new MajorWithOtherID
{
ID = "id2",
MajorCode = "222",
MajorName = "major2",
MajorType = MajorTypeEnum.Required
};
MajorWithOtherID m3 = new MajorWithOtherID
{
ID = "id3",
MajorCode = "333",
MajorName = "major3",
MajorType = MajorTypeEnum.Required
};
Student s1 = new Student
{
LoginName = "s1",
Password = "aaa",
Name = "student1"
};
_majorvm.Entity = m1;
_majorvm.DoAdd();
_majorvm.Entity = m2;
_majorvm.DoAdd();
_majorvm.Entity = m3;
_majorvm.DoAdd();
s1.StudentMajorWithOtherID = new List<StudentMajorWithOtherID>();
s1.StudentMajorWithOtherID.Add(new StudentMajorWithOtherID { MajorId = m1.ID });
s1.StudentMajorWithOtherID.Add(new StudentMajorWithOtherID { MajorId = m2.ID });
s1.StudentMajorWithOtherID.Add(new StudentMajorWithOtherID { MajorId = m3.ID });
_studentvm.Entity = s1;
_studentvm.DoAdd();
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
s1.StudentMajor = null;
_studentvm.DC = context;
_studentvm.Entity = s1;
_studentvm.DoEdit();
}
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
Assert.AreEqual(3, context.Set<StudentMajorWithOtherID>().Count());
}
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
s1.StudentMajorWithOtherID = new List<StudentMajorWithOtherID>();
_studentvm.DC = context;
_studentvm.Entity = s1;
_studentvm.DoEdit();
}
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
Assert.AreEqual(0, context.Set<StudentMajorWithOtherID>().Count());
}
}
[TestMethod]
[Description("根据ID读取")]
public void GetTest()
{
One2ManyDoAdd();
_majorvm.SetInclude(x => x.School);
string id;
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
id = context.Set<MajorWithOtherID>().Select(x => x.ID).FirstOrDefault();
}
_majorvm.SetEntityById(id);
Assert.IsTrue(_majorvm.Entity.School.ID != 0);
}
[TestMethod]
[Description("设置单一不可重复字段")]
public void DuplicateTest()
{
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
context.Set<MajorWithOtherID>().Add(new MajorWithOtherID { ID="id1", MajorCode = "111", MajorName = "222", MajorType = MajorTypeEnum.Optional });
context.SaveChanges();
}
_majorvm = new MajorVM1WithOtherID();
_majorvm.DC = new DataContext(_seed, DBTypeEnum.Memory);
_majorvm.MSD = new MockMSD();
_majorvm.Entity = new MajorWithOtherID {ID="id2", MajorCode = "111", MajorName = "not222", MajorType = MajorTypeEnum.Required };
_majorvm.Validate();
Assert.IsTrue(_majorvm.MSD["Entity.MajorCode"].Count > 0);
}
[TestMethod]
[Description("设置多个不可重复字段")]
public void DuplicateTest2()
{
using (var context = new DataContext(_seed, DBTypeEnum.Memory))
{
context.Set<MajorWithOtherID>().Add(new MajorWithOtherID {ID="id1", MajorCode = "111", MajorName = "222", MajorType = MajorTypeEnum.Optional });
context.SaveChanges();
}
_majorvm = new MajorVM2WithOtherID();
_majorvm.DC = new DataContext(_seed, DBTypeEnum.Memory);
_majorvm.MSD = new MockMSD();
_majorvm.Entity = new MajorWithOtherID {ID="id2", MajorCode = "111", MajorName = "222", MajorType = MajorTypeEnum.Required };
_majorvm.Validate();
Assert.IsTrue(_majorvm.MSD["Entity.MajorCode"].Count > 0);
Assert.IsTrue(_majorvm.MSD["Entity.MajorName"].Count > 0);
}
class MajorVM1 : BaseCRUDVM<Major>
{
public override DuplicatedInfo<Major> SetDuplicatedCheck()
{
return CreateFieldsInfo(SimpleField(x => x.MajorCode));
}
}
class MajorVM2 : BaseCRUDVM<Major>
{
public override DuplicatedInfo<Major> SetDuplicatedCheck()
{
return CreateFieldsInfo(SimpleField(x => x.MajorCode)).AddGroup(SimpleField(x=>x.MajorName));
}
}
class MajorVM3 : BaseCRUDVM<OptMajor>
{
public override DuplicatedInfo<OptMajor> SetDuplicatedCheck()
{
return CreateFieldsInfo(SimpleField(x => x.MajorCode),SimpleField(x => x.SchoolId));
}
}
class MajorVM1WithOtherID : BaseCRUDVM<MajorWithOtherID>
{
public override DuplicatedInfo<MajorWithOtherID> SetDuplicatedCheck()
{
return CreateFieldsInfo(SimpleField(x => x.MajorCode));
}
}
class MajorVM2WithOtherID : BaseCRUDVM<MajorWithOtherID>
{
public override DuplicatedInfo<MajorWithOtherID> SetDuplicatedCheck()
{
return CreateFieldsInfo(SimpleField(x => x.MajorCode)).AddGroup(SimpleField(x => x.MajorName));
}
}
}
}
| 39.367223
| 161
| 0.532282
|
[
"MIT"
] |
331378731/WTM
|
test/WalkingTec.Mvvm.Core.Test/VM/BaseCRUDVMTestWithOtherID.cs
| 26,175
|
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TopMostMagic")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Automatl")]
[assembly: AssemblyProduct("TopMostMagic")]
[assembly: AssemblyCopyright("Copyright © Automatl 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("26a59bcb-44b7-45f4-ae88-a2052105bd51")]
// 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("0.8.*")]
//[assembly: AssemblyVersion("1.0.0.0")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.189189
| 85
| 0.728966
|
[
"BSD-2-Clause"
] |
automatl/TopMostMagic
|
TopMostMagic/Properties/AssemblyInfo.cs
| 1,453
|
C#
|
using Furion.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
namespace Furion.DatabaseAccessor
{
/// <summary>
/// 非泛型EF Core仓储实现
/// </summary>
[SkipScan]
public partial class EFCoreRepository : IRepository
{
/// <summary>
/// 服务提供器
/// </summary>
private readonly IServiceProvider _serviceProvider;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="scoped">服务提供器</param>
public EFCoreRepository(
IServiceProvider scoped)
{
_serviceProvider = scoped;
}
/// <summary>
/// 切换仓储
/// </summary>
/// <typeparam name="TEntity">实体类型</typeparam>
/// <returns>仓储</returns>
public virtual IRepository<TEntity> Change<TEntity>()
where TEntity : class, IPrivateEntity, new()
{
return _serviceProvider.GetService<IRepository<TEntity>>();
}
/// <summary>
/// 切换多数据库上下文仓储
/// </summary>
/// <typeparam name="TEntity">实体类型</typeparam>
/// <typeparam name="TDbContextLocator">数据库上下文定位器</typeparam>
/// <returns>仓储</returns>
public virtual IRepository<TEntity, TDbContextLocator> Change<TEntity, TDbContextLocator>()
where TEntity : class, IPrivateEntity, new()
where TDbContextLocator : class, IDbContextLocator
{
return _serviceProvider.GetService<IRepository<TEntity, TDbContextLocator>>();
}
/// <summary>
/// 重新构建并切换仓储
/// </summary>
/// <typeparam name="TEntity">实体类型</typeparam>
/// <returns>仓储</returns>
public virtual IRepository<TEntity> BuildChange<TEntity>()
where TEntity : class, IPrivateEntity, new()
{
return _serviceProvider.CreateScope().ServiceProvider.GetService<IRepository<TEntity>>();
}
/// <summary>
/// 重新构建并切换多数据库上下文仓储
/// </summary>
/// <typeparam name="TEntity">实体类型</typeparam>
/// <typeparam name="TDbContextLocator">数据库上下文定位器</typeparam>
/// <returns>仓储</returns>
public virtual IRepository<TEntity, TDbContextLocator> BuildChange<TEntity, TDbContextLocator>()
where TEntity : class, IPrivateEntity, new()
where TDbContextLocator : class, IDbContextLocator
{
return _serviceProvider.CreateScope().ServiceProvider.GetService<IRepository<TEntity, TDbContextLocator>>();
}
/// <summary>
/// 获取 Sql 操作仓储
/// </summary>
/// <returns>ISqlRepository</returns>
public virtual ISqlRepository Sql()
{
return _serviceProvider.GetService<ISqlRepository>();
}
/// <summary>
/// 获取多数据库上下文 Sql 操作仓储
/// </summary>
/// <returns>ISqlRepository{TDbContextLocator}</returns>
public virtual ISqlRepository<TDbContextLocator> Sql<TDbContextLocator>()
where TDbContextLocator : class, IDbContextLocator
{
return _serviceProvider.GetService<ISqlRepository<TDbContextLocator>>();
}
/// <summary>
/// 解析服务
/// </summary>
/// <typeparam name="TService"></typeparam>
/// <returns></returns>
public virtual TService GetService<TService>()
{
return _serviceProvider.GetService<TService>();
}
/// <summary>
/// 解析服务
/// </summary>
/// <typeparam name="TService"></typeparam>
/// <returns></returns>
public virtual TService GetRequiredService<TService>()
{
return _serviceProvider.GetRequiredService<TService>();
}
}
/// <summary>
/// EF Core仓储实现
/// </summary>
/// <typeparam name="TEntity">实体类型</typeparam>
[SkipScan]
public partial class EFCoreRepository<TEntity> : EFCoreRepository<TEntity, MasterDbContextLocator>
, IRepository<TEntity>
where TEntity : class, IPrivateEntity, new()
{
/// <summary>
/// 构造函数
/// </summary>
/// <param name="scoped">服务提供器</param>
public EFCoreRepository(IServiceProvider scoped) : base(scoped)
{
}
}
/// <summary>
/// 多数据库上下文仓储
/// </summary>
[SkipScan]
public partial class EFCoreRepository<TEntity, TDbContextLocator> : PrivateRepository<TEntity>
, IRepository<TEntity, TDbContextLocator>
where TEntity : class, IPrivateEntity, new()
where TDbContextLocator : class, IDbContextLocator
{
/// <summary>
/// 构造函数
/// </summary>
/// <param name="scoped">服务提供器</param>
public EFCoreRepository(IServiceProvider scoped) : base(typeof(TDbContextLocator), scoped)
{
}
}
/// <summary>
/// 私有仓储
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public partial class PrivateRepository<TEntity> : PrivateSqlRepository, IPrivateRepository<TEntity>
where TEntity : class, IPrivateEntity, new()
{
/// <summary>
/// 非泛型仓储
/// </summary>
private readonly IRepository _repository;
/// <summary>
/// 数据库上下文池
/// </summary>
private readonly IDbContextPool _dbContextPool;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="dbContextLocator"></param>
/// <param name="scoped">服务提供器</param>
public PrivateRepository(Type dbContextLocator, IServiceProvider scoped) : base(dbContextLocator, scoped)
{
// 初始化服务提供器
ServiceProvider = scoped;
DbConnection = Database.GetDbConnection();
ChangeTracker = Context.ChangeTracker;
Model = Context.Model;
// 内置多租户
Tenant = DynamicContext.Tenant;
// 设置提供器名称
ProviderName = Database.ProviderName;
//初始化实体
Entities = Context.Set<TEntity>();
DetachedEntities = Entities.AsNoTracking();
EntityType = Model.FindEntityType(typeof(TEntity));
// 初始化数据上下文池
_dbContextPool = scoped.GetService<IDbContextPool>();
// 非泛型仓储
_repository = scoped.GetService<IRepository>();
}
/// <summary>
/// 实体集合
/// </summary>
public virtual DbSet<TEntity> Entities { get; }
/// <summary>
/// 不跟踪的(脱轨)实体
/// </summary>
public virtual IQueryable<TEntity> DetachedEntities { get; }
/// <summary>
/// 查看实体类型
/// </summary>
public virtual IEntityType EntityType { get; }
/// <summary>
/// 数据库连接对象
/// </summary>
public virtual DbConnection DbConnection { get; }
/// <summary>
/// 实体追综器
/// </summary>
public virtual ChangeTracker ChangeTracker { get; }
/// <summary>
/// 实体模型
/// </summary>
public virtual IModel Model { get; }
/// <summary>
/// 租户信息
/// </summary>
public virtual Tenant Tenant { get; }
/// <summary>
/// 数据库提供器名
/// </summary>
public virtual string ProviderName { get; }
/// <summary>
/// 服务提供器
/// </summary>
public virtual IServiceProvider ServiceProvider { get; }
/// <summary>
/// 租户Id
/// </summary>
public virtual Guid? TenantId { get; }
/// <summary>
/// 判断上下文是否更改
/// </summary>
/// <returns>bool</returns>
public virtual bool HasChanges()
{
return ChangeTracker.HasChanges();
}
/// <summary>
/// 将实体加入数据上下文托管
/// </summary>
/// <param name="entity">实体</param>
/// <returns>EntityEntry</returns>
public virtual EntityEntry Entry(object entity)
{
return Context.Entry(entity);
}
/// <summary>
/// 将实体加入数据上下文托管
/// </summary>
/// <param name="entity">实体</param>
/// <returns></returns>
public virtual EntityEntry<TEntity> Entry(TEntity entity)
{
return Context.Entry(entity);
}
/// <summary>
/// 获取实体状态
/// </summary>
/// <param name="entity">实体</param>
/// <returns></returns>
public virtual EntityState EntityEntryState(object entity)
{
return Entry(entity).State;
}
/// <summary>
/// 获取实体状态
/// </summary>
/// <param name="entity">实体</param>
/// <returns>EntityState</returns>
public virtual EntityState EntityEntryState(TEntity entity)
{
return Entry(entity).State;
}
/// <summary>
/// 将实体属性加入托管
/// </summary>
/// <param name="entity">实体</param>
/// <param name="propertyName">属性名</param>
/// <returns>PropertyEntry</returns>
public virtual PropertyEntry EntityPropertyEntry(object entity, string propertyName)
{
return Entry(entity).Property(propertyName);
}
/// <summary>
/// 将实体属性加入托管
/// </summary>
/// <param name="entity">实体</param>
/// <param name="propertyName">属性名</param>
/// <returns>PropertyEntry</returns>
public virtual PropertyEntry EntityPropertyEntry(TEntity entity, string propertyName)
{
return Entry(entity).Property(propertyName);
}
/// <summary>
/// 将实体属性加入托管
/// </summary>
/// <typeparam name="TProperty">属性类型</typeparam>
/// <param name="entity">实体</param>
/// <param name="propertyPredicate">属性表达式</param>
/// <returns>PropertyEntry</returns>
public virtual PropertyEntry<TEntity, TProperty> EntityPropertyEntry<TProperty>(TEntity entity, Expression<Func<TEntity, TProperty>> propertyPredicate)
{
return Entry(entity).Property(propertyPredicate);
}
/// <summary>
/// 改变实体状态
/// </summary>
/// <param name="entity">实体</param>
/// <param name="entityState">实体状态</param>
/// <returns>EntityEntry</returns>
public virtual EntityEntry ChangeEntityState(object entity, EntityState entityState)
{
var entityEntry = Entry(entity);
entityEntry.State = entityState;
return entityEntry;
}
/// <summary>
/// 改变实体状态
/// </summary>
/// <param name="entity">实体</param>
/// <param name="entityState">实体状态</param>
/// <returns>EntityEntry{TEntity}</returns>
public virtual EntityEntry<TEntity> ChangeEntityState(TEntity entity, EntityState entityState)
{
var entityEntry = Entry(entity);
entityEntry.State = entityState;
return entityEntry;
}
/// <summary>
/// 改变实体状态
/// </summary>
/// <param name="entityEntry">实体条目</param>
/// <param name="entityState">实体状态</param>
/// <returns>EntityEntry</returns>
public virtual EntityEntry ChangeEntityState(EntityEntry entityEntry, EntityState entityState)
{
entityEntry.State = entityState;
return entityEntry;
}
/// <summary>
/// 改变实体状态
/// </summary>
/// <param name="entityEntry">实体条目</param>
/// <param name="entityState">实体状态</param>
/// <returns>EntityEntry{TEntity}</returns>
public virtual EntityEntry<TEntity> ChangeEntityState(EntityEntry<TEntity> entityEntry, EntityState entityState)
{
entityEntry.State = entityState;
return entityEntry;
}
/// <summary>
/// 判断是否被附加
/// </summary>
/// <param name="entity">实体</param>
/// <returns>bool</returns>
public virtual bool IsAttached(object entity)
{
return EntityEntryState(entity) != EntityState.Detached;
}
/// <summary>
/// 判断是否被附加
/// </summary>
/// <param name="entity">实体</param>
/// <returns>bool</returns>
public virtual bool IsAttached(TEntity entity)
{
return EntityEntryState(entity) != EntityState.Detached;
}
/// <summary>
/// 附加实体
/// </summary>
/// <param name="entity">实体</param>
/// <returns>EntityEntry</returns>
public virtual EntityEntry Attach(object entity)
{
return Context.Attach(entity);
}
/// <summary>
/// 附加实体
/// </summary>
/// <param name="entity">实体</param>
/// <returns>EntityEntry</returns>
public virtual EntityEntry<TEntity> Attach(TEntity entity)
{
return Context.Attach(entity);
}
/// <summary>
/// 附加多个实体
/// </summary>
/// <param name="entities">多个实体</param>
public virtual void AttachRange(params object[] entities)
{
Context.AttachRange(entities);
}
/// <summary>
/// 附加多个实体
/// </summary>
/// <param name="entities">多个实体</param>
public virtual void AttachRange(IEnumerable<TEntity> entities)
{
Context.AttachRange(entities);
}
/// <summary>
/// 取消附加实体
/// </summary>
/// <param name="entity">实体</param>
public virtual void Detach(object entity)
{
ChangeEntityState(entity, EntityState.Detached);
}
/// <summary>
/// 取消附加实体
/// </summary>
/// <param name="entity">实体</param>
public virtual void Detach(TEntity entity)
{
ChangeEntityState(entity, EntityState.Detached);
}
/// <summary>
/// 取消附加实体
/// </summary>
/// <param name="entityEntry">实体条目</param>
public virtual void Detach(EntityEntry entityEntry)
{
ChangeEntityState(entityEntry, EntityState.Detached);
}
/// <summary>
/// 取消附加实体
/// </summary>
/// <param name="entityEntry">实体条目</param>
public virtual void Detach(EntityEntry<TEntity> entityEntry)
{
ChangeEntityState(entityEntry, EntityState.Detached);
}
/// <summary>
/// 获取所有数据库上下文
/// </summary>
/// <returns>ConcurrentBag{DbContext}</returns>
public ConcurrentBag<DbContext> GetDbContexts()
{
return _dbContextPool.GetDbContexts();
}
/// <summary>
/// 判断实体是否设置了主键
/// </summary>
/// <param name="entity">实体</param>
/// <returns>bool</returns>
public virtual bool IsKeySet(TEntity entity)
{
return Entry(entity).IsKeySet;
}
/// <summary>
/// 删除数据库
/// </summary>
public virtual void EnsureDeleted()
{
Context.Database.EnsureDeleted();
}
/// <summary>
/// 删除数据库
/// </summary>
public virtual Task EnsureDeletedAsync(CancellationToken cancellationToken = default)
{
return Context.Database.EnsureDeletedAsync(cancellationToken);
}
/// <summary>
/// 创建数据库
/// </summary>
public virtual void EnsureCreated()
{
Context.Database.EnsureCreated();
}
/// <summary>
/// 创建数据库
/// </summary>
public virtual Task EnsureCreatedAsync(CancellationToken cancellationToken = default)
{
return Context.Database.EnsureCreatedAsync(cancellationToken);
}
/// <summary>
/// 动态改变表名
/// </summary>
/// <param name="tableName">表名</param>
[Obsolete("该方法已过时,请调用 BuildChange<TEntity> 方法代替。")]
public virtual void ChangeTable(string tableName)
{
if (EntityType is IConventionEntityType convention)
{
convention.SetTableName(tableName);
}
}
/// <summary>
/// 动态改变数据库
/// </summary>
/// <param name="connectionString">连接字符串</param>
public virtual void ChangeDatabase(string connectionString)
{
if (DbConnection.State == ConnectionState.Open) DbConnection.ChangeDatabase(connectionString);
else DbConnection.ConnectionString = connectionString;
}
/// <summary>
/// 动态改变数据库
/// </summary>
/// <param name="connectionString">连接字符串</param>
/// <param name="cancellationToken">异步取消令牌</param>
public virtual async Task ChangeDatabaseAsync(string connectionString, CancellationToken cancellationToken = default)
{
if (DbConnection.State == ConnectionState.Open)
{
await DbConnection.ChangeDatabaseAsync(connectionString, cancellationToken);
}
else
{
DbConnection.ConnectionString = connectionString;
}
}
/// <summary>
/// 判断是否是 SqlServer 数据库
/// </summary>
/// <returns>bool</returns>
public virtual bool IsSqlServer()
{
return DbProvider.IsDatabaseFor(ProviderName, DbProvider.SqlServer);
}
/// <summary>
/// 判断是否是 Sqlite 数据库
/// </summary>
/// <returns>bool</returns>
public virtual bool IsSqlite()
{
return DbProvider.IsDatabaseFor(ProviderName, DbProvider.Sqlite);
}
/// <summary>
/// 判断是否是 Cosmos 数据库
/// </summary>
/// <returns>bool</returns>
public virtual bool IsCosmos()
{
return DbProvider.IsDatabaseFor(ProviderName, DbProvider.Cosmos);
}
/// <summary>
/// 判断是否是 内存中 数据库
/// </summary>
/// <returns>bool</returns>
public virtual bool InMemoryDatabase()
{
return DbProvider.IsDatabaseFor(ProviderName, DbProvider.InMemoryDatabase);
}
/// <summary>
/// 判断是否是 MySql 数据库
/// </summary>
/// <returns>bool</returns>
public virtual bool IsMySql()
{
return DbProvider.IsDatabaseFor(ProviderName, DbProvider.MySql);
}
/// <summary>
/// 判断是否是 MySql 数据库 官方包(更新不及时,只支持 8.0.23+ 版本, 所以单独弄一个分类)
/// </summary>
/// <returns>bool</returns>
public virtual bool IsMySqlOfficial()
{
return DbProvider.IsDatabaseFor(ProviderName, DbProvider.MySqlOfficial);
}
/// <summary>
/// 判断是否是 PostgreSQL 数据库
/// </summary>
/// <returns>bool</returns>
public virtual bool IsNpgsql()
{
return DbProvider.IsDatabaseFor(ProviderName, DbProvider.Npgsql);
}
/// <summary>
/// 判断是否是 Oracle 数据库
/// </summary>
/// <returns>bool</returns>
public virtual bool IsOracle()
{
return DbProvider.IsDatabaseFor(ProviderName, DbProvider.Oracle);
}
/// <summary>
/// 判断是否是 Firebird 数据库
/// </summary>
/// <returns>bool</returns>
public virtual bool IsFirebird()
{
return DbProvider.IsDatabaseFor(ProviderName, DbProvider.Firebird);
}
/// <summary>
/// 判断是否是 Dm 数据库
/// </summary>
/// <returns>bool</returns>
public virtual bool IsDm()
{
return DbProvider.IsDatabaseFor(ProviderName, DbProvider.Dm);
}
/// <summary>
/// 判断是否是关系型数据库
/// </summary>
/// <returns>bool</returns>
public virtual bool IsRelational()
{
return Database.IsRelational();
}
/// <summary>
/// 切换仓储
/// </summary>
/// <typeparam name="TChangeEntity">实体类型</typeparam>
/// <returns>仓储</returns>
public virtual new IRepository<TChangeEntity> Change<TChangeEntity>()
where TChangeEntity : class, IPrivateEntity, new()
{
return _repository.Change<TChangeEntity>();
}
/// <summary>
/// 切换多数据库上下文仓储
/// </summary>
/// <typeparam name="TChangeEntity">实体类型</typeparam>
/// <typeparam name="TChangeDbContextLocator">数据库上下文定位器</typeparam>
/// <returns>仓储</returns>
public virtual IRepository<TChangeEntity, TChangeDbContextLocator> Change<TChangeEntity, TChangeDbContextLocator>()
where TChangeEntity : class, IPrivateEntity, new()
where TChangeDbContextLocator : class, IDbContextLocator
{
return _repository.Change<TChangeEntity, TChangeDbContextLocator>();
}
/// <summary>
/// 重新构建并切换仓储
/// </summary>
/// <typeparam name="TChangeEntity">实体类型</typeparam>
/// <returns>仓储</returns>
public virtual IRepository<TChangeEntity> BuildChange<TChangeEntity>()
where TChangeEntity : class, IPrivateEntity, new()
{
return _repository.BuildChange<TChangeEntity>();
}
/// <summary>
/// 重新构建并切换多数据库上下文仓储
/// </summary>
/// <typeparam name="TChangeEntity">实体类型</typeparam>
/// <typeparam name="TChangeDbContextLocator">数据库上下文定位器</typeparam>
/// <returns>仓储</returns>
public virtual IRepository<TChangeEntity, TChangeDbContextLocator> BuildChange<TChangeEntity, TChangeDbContextLocator>()
where TChangeEntity : class, IPrivateEntity, new()
where TChangeDbContextLocator : class, IDbContextLocator
{
return _repository.BuildChange<TChangeEntity, TChangeDbContextLocator>();
}
}
}
| 30.839286
| 159
| 0.554808
|
[
"Apache-2.0"
] |
DarrenYangsimida/Furion
|
framework/Furion/DatabaseAccessor/Repositories/EFCoreRepository.cs
| 24,091
|
C#
|
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text.RegularExpressions;
using Microsoft.Recognizers.Text.DateTime.Utilities;
using Microsoft.Recognizers.Definitions.English;
namespace Microsoft.Recognizers.Text.DateTime.English
{
public class EnglishDateParserConfiguration : BaseOptionsConfiguration, IDateParserConfiguration
{
public string DateTokenPrefix { get; }
public IExtractor IntegerExtractor { get; }
public IExtractor OrdinalExtractor { get; }
public IExtractor CardinalExtractor { get; }
public IParser NumberParser { get; }
public IDateTimeExtractor DurationExtractor { get; }
public IDateExtractor DateExtractor { get; }
public IDateTimeParser DurationParser { get; }
public IEnumerable<Regex> DateRegexes { get; }
public IImmutableDictionary<string, string> UnitMap { get; }
public Regex OnRegex { get; }
public Regex SpecialDayRegex { get; }
public Regex SpecialDayWithNumRegex { get; }
public Regex NextRegex { get; }
public Regex ThisRegex { get; }
public Regex LastRegex { get; }
public Regex UnitRegex { get; }
public Regex WeekDayRegex { get; }
public Regex MonthRegex { get; }
public Regex WeekDayOfMonthRegex { get; }
public Regex ForTheRegex { get; }
public Regex WeekDayAndDayOfMothRegex { get; }
public Regex RelativeMonthRegex { get; }
public Regex YearSuffix { get; }
public Regex RelativeWeekDayRegex { get; }
public Regex RelativeDayRegex { get; }
public Regex NextPrefixRegex { get; }
public Regex PastPrefixRegex { get; }
public IImmutableDictionary<string, int> DayOfMonth { get; }
public IImmutableDictionary<string, int> DayOfWeek { get; }
public IImmutableDictionary<string, int> MonthOfYear { get; }
public IImmutableDictionary<string, int> CardinalMap { get; }
public IImmutableList<string> SameDayTerms { get; }
public IImmutableList<string> PlusOneDayTerms { get; }
public IImmutableList<string> MinusOneDayTerms { get; }
public IImmutableList<string> PlusTwoDayTerms { get; }
public IImmutableList<string> MinusTwoDayTerms { get; }
public IDateTimeUtilityConfiguration UtilityConfiguration { get; }
public EnglishDateParserConfiguration(ICommonDateTimeParserConfiguration config) : base(config)
{
DateTokenPrefix = DateTimeDefinitions.DateTokenPrefix;
IntegerExtractor = config.IntegerExtractor;
OrdinalExtractor = config.OrdinalExtractor;
CardinalExtractor = config.CardinalExtractor;
NumberParser = config.NumberParser;
DurationExtractor = config.DurationExtractor;
DateExtractor = config.DateExtractor;
DurationParser = config.DurationParser;
DateRegexes = new EnglishDateExtractorConfiguration(this).DateRegexList;
OnRegex = EnglishDateExtractorConfiguration.OnRegex;
SpecialDayRegex = EnglishDateExtractorConfiguration.SpecialDayRegex;
SpecialDayWithNumRegex = EnglishDateExtractorConfiguration.SpecialDayWithNumRegex;
NextRegex = EnglishDateExtractorConfiguration.NextDateRegex;
ThisRegex = EnglishDateExtractorConfiguration.ThisRegex;
LastRegex = EnglishDateExtractorConfiguration.LastDateRegex;
UnitRegex = EnglishDateExtractorConfiguration.DateUnitRegex;
WeekDayRegex = EnglishDateExtractorConfiguration.WeekDayRegex;
MonthRegex = EnglishDateExtractorConfiguration.MonthRegex;
WeekDayOfMonthRegex = EnglishDateExtractorConfiguration.WeekDayOfMonthRegex;
ForTheRegex = EnglishDateExtractorConfiguration.ForTheRegex;
WeekDayAndDayOfMothRegex = EnglishDateExtractorConfiguration.WeekDayAndDayOfMothRegex;
RelativeMonthRegex = EnglishDateExtractorConfiguration.RelativeMonthRegex;
YearSuffix = EnglishDateExtractorConfiguration.YearSuffix;
RelativeWeekDayRegex = EnglishDateExtractorConfiguration.RelativeWeekDayRegex;
RelativeDayRegex = new Regex(DateTimeDefinitions.RelativeDayRegex, RegexOptions.Singleline);
NextPrefixRegex = new Regex(DateTimeDefinitions.NextPrefixRegex, RegexOptions.Singleline);
PastPrefixRegex = new Regex(DateTimeDefinitions.PastPrefixRegex, RegexOptions.Singleline);
DayOfMonth = config.DayOfMonth;
DayOfWeek = config.DayOfWeek;
MonthOfYear = config.MonthOfYear;
CardinalMap = config.CardinalMap;
UnitMap = config.UnitMap;
UtilityConfiguration = config.UtilityConfiguration;
SameDayTerms = DateTimeDefinitions.SameDayTerms.ToImmutableList();
PlusOneDayTerms = DateTimeDefinitions.PlusOneDayTerms.ToImmutableList();
PlusTwoDayTerms = DateTimeDefinitions.PlusTwoDayTerms.ToImmutableList();
MinusOneDayTerms = DateTimeDefinitions.MinusOneDayTerms.ToImmutableList();
MinusTwoDayTerms = DateTimeDefinitions.MinusTwoDayTerms.ToImmutableList();
}
public int GetSwiftMonth(string text)
{
var trimmedText = text.Trim().ToLowerInvariant();
var swift = 0;
if (NextPrefixRegex.IsMatch(trimmedText))
{
swift = 1;
}
if (PastPrefixRegex.IsMatch(trimmedText))
{
swift = -1;
}
return swift;
}
public bool IsCardinalLast(string text)
{
var trimmedText = text.Trim().ToLowerInvariant();
return trimmedText.Equals("last");
}
public string Normalize(string text)
{
return text;
}
}
}
| 37.275
| 104
| 0.681422
|
[
"MIT"
] |
Irrelevances/Recognizers-Text
|
.NET/Microsoft.Recognizers.Text.DateTime/English/Parsers/EnglishDateParserConfiguration.cs
| 5,966
|
C#
|
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
using Windows.UI.Xaml;
namespace WinRTXamlToolkit.Controls.DataVisualization.Charting
{
/// <summary>
/// Represents a data point used for an area series.
/// </summary>
/// <QualityBand>Preview</QualityBand>
[TemplateVisualState(Name = DataPoint.StateCommonNormal, GroupName = DataPoint.GroupCommonStates)]
[TemplateVisualState(Name = DataPoint.StateCommonMouseOver, GroupName = DataPoint.GroupCommonStates)]
[TemplateVisualState(Name = DataPoint.StateSelectionUnselected, GroupName = DataPoint.GroupSelectionStates)]
[TemplateVisualState(Name = DataPoint.StateSelectionSelected, GroupName = DataPoint.GroupSelectionStates)]
[TemplateVisualState(Name = DataPoint.StateRevealShown, GroupName = DataPoint.GroupRevealStates)]
[TemplateVisualState(Name = DataPoint.StateRevealHidden, GroupName = DataPoint.GroupRevealStates)]
public partial class AreaDataPoint : DataPoint
{
/// <summary>
/// Initializes a new instance of the AreaDataPoint class.
/// </summary>
public AreaDataPoint()
{
this.DefaultStyleKey = typeof(AreaDataPoint);
}
}
}
| 47.862069
| 113
| 0.717579
|
[
"MIT"
] |
JUV-Studios/WinRTXamlToolk
|
WinRTXamlToolkit.Controls.DataVisualization/Charting/DataPoint/AreaDataPoint.cs
| 1,390
|
C#
|
/*----------------------------------------------------------------
Copyright (C) 2019 Senparc
文件名:SystemTime.cs
文件功能描述:用于从 DateTimeOffset 进行扩展,方便进行单元测试
创建标识:Senparc - 20181113
修改标识:Senparc - 20181226
修改描述:1、将 DateTime 改为 DateTimeOffset
2、添加 Today 属性
修改标识:Senparc - 20190427
修改描述:v0.6.1 添加 NowTicks 属性
修改标识:Senparc - 20190507
修改描述:v0.7.1 添加 NowDiff 属性
----------------------------------------------------------------*/
namespace System
{
/// <summary>
/// 时间扩展类
/// </summary>
public static class SystemTime
{
///// <summary>
///// 返回 Now 方法
///// </summary>
//public static Func<DateTime> GetNow = () => SystemTime.Now;
/// <summary>
/// 当前时间
/// </summary>
public static DateTimeOffset Now => DateTimeOffset.Now;
/// <summary>
/// 当天零点时间,从 SystemTime.Now.Date 获得
/// </summary>
public static DateTime Today => Now.Date;
/// <summary>
/// 获取当前时间的 Ticks
/// </summary>
public static long NowTicks => Now.Ticks;
//TODO:添加更多实用方法
/// <summary>
/// 获取 TimeSpan
/// </summary>
/// <param name="compareTime">当前时间 - compareTime</param>
/// <returns></returns>
public static TimeSpan NowDiff(DateTimeOffset compareTime)
{
return Now - compareTime;
}
/// <summary>
/// 获取 TimeSpan
/// </summary>
/// <param name="compareTime">当前时间 - compareTime</param>
/// <returns></returns>
public static TimeSpan NowDiff(DateTime compareTime)
{
return Now.DateTime - compareTime;
}
}
}
| 23
| 69
| 0.491419
|
[
"Apache-2.0"
] |
JayDenZ09/Senparc.CO2NET
|
src/Senparc.CO2NET/ExtensionEntities/SystemTime.cs
| 2,010
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Task3
{
static class Program
{
/// <summary>
/// Главная точка входа для приложения.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 21.652174
| 65
| 0.606426
|
[
"MIT"
] |
hse-programming-CSharp2020-2021/CSharp2020-2021
|
02 module/9-10Seminar/Task3/Program.cs
| 530
|
C#
|
using System;
using System.Windows.Input;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using DotNetify;
using Newtonsoft.Json;
namespace SPA
{
public class SimpleListVM : BaseVM
{
private readonly IEmployeeRepository _repository;
public class EmployeeInfo
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public IEnumerable<EmployeeInfo> Employees => _repository
.GetAll(10)
.Select(i => new EmployeeInfo { Id = i.Id, FirstName = i.FirstName, LastName = i.LastName });
// If you use CRUD methods on a list, you must set the item key prop name of that list
// by defining a string property that starts with that list's prop name, followed by "_itemKey".
public string Employees_itemKey => nameof(Employee.Id);
public Action<string> Add => fullName =>
{
var names = fullName.Split(new char[] { ' ' }, 2);
var employee = new Employee
{
FirstName = names.First(),
LastName = names.Length > 1 ? names.Last() : ""
};
// Use CRUD base method to add the list item on the client.
this.AddList("Employees", new EmployeeInfo
{
Id = _repository.Add(employee),
FirstName = employee.FirstName,
LastName = employee.LastName
});
};
public Action<EmployeeInfo> Update => employeeInfo =>
{
var employee = _repository.Get(employeeInfo.Id);
if (employee != null)
{
employee.FirstName = employeeInfo.FirstName ?? employee.FirstName;
employee.LastName = employeeInfo.LastName ?? employee.LastName;
_repository.Update(employee);
}
};
public Action<int> Remove => id =>
{
_repository.Remove(id);
// Use CRUD base method to remove the list item on the client.
this.RemoveList(nameof(Employees), id);
};
public SimpleListVM(IEmployeeRepository repository)
{
_repository = repository;
}
}
}
| 32.136986
| 104
| 0.569906
|
[
"Apache-2.0"
] |
BajakiGabesz/dotNetify
|
Demo/Knockout/SPA/server/ViewModels/SimpleList.cs
| 2,346
|
C#
|
using System;
using System.Collections;
using System.Collections.Generic;
#if !SILVERLIGHT
using System.Data;
#endif
using System.Globalization;
using System.IO;
using System.Text;
using System.Collections.Specialized;
namespace fastJSON
{
internal sealed class JSONSerializer
{
private StringBuilder _output = new StringBuilder();
//private StringBuilder _before = new StringBuilder();
private int _before;
private int _MAX_DEPTH = 20;
int _current_depth = 0;
private Dictionary<string, int> _globalTypes = new Dictionary<string, int>();
private Dictionary<object, int> _cirobj = new Dictionary<object, int>();
private JSONParameters _params;
private bool _useEscapedUnicode = false;
internal JSONSerializer(JSONParameters param)
{
_params = param;
_useEscapedUnicode = _params.UseEscapedUnicode;
_MAX_DEPTH = _params.SerializerMaxDepth;
}
internal string ConvertToJSON(object obj)
{
WriteValue(obj);
if (_params.UsingGlobalTypes && _globalTypes != null && _globalTypes.Count > 0)
{
var sb = new StringBuilder();
sb.Append("\"$types\":{");
var pendingSeparator = false;
foreach (var kv in _globalTypes)
{
if (pendingSeparator) sb.Append(',');
pendingSeparator = true;
sb.Append('\"');
sb.Append(kv.Key);
sb.Append("\":\"");
sb.Append(kv.Value);
sb.Append('\"');
}
sb.Append("},");
_output.Insert(_before, sb.ToString());
}
return _output.ToString();
}
private void WriteValue(object obj)
{
if (obj == null || obj is DBNull)
_output.Append("null");
else if (obj is string || obj is char)
WriteString(obj.ToString());
else if (obj is Guid)
WriteGuid((Guid)obj);
else if (obj is bool)
_output.Append(((bool)obj) ? "true" : "false"); // conform to standard
else if (
obj is int || obj is long ||
obj is decimal ||
obj is byte || obj is short ||
obj is sbyte || obj is ushort ||
obj is uint || obj is ulong
)
_output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo));
else if (obj is double || obj is Double)
{
double d = (double)obj;
if (double.IsNaN(d))
_output.Append("\"NaN\"");
else if (double.IsInfinity(d))
{
_output.Append("\"");
_output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo));
_output.Append("\"");
}
else
_output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo));
}
else if (obj is float || obj is Single)
{
float d = (float)obj;
if (float.IsNaN(d))
_output.Append("\"NaN\"");
else if (float.IsInfinity(d))
{
_output.Append("\"");
_output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo));
_output.Append("\"");
}
else
_output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo));
}
else if (obj is DateTime)
WriteDateTime((DateTime)obj);
else if (obj is DateTimeOffset)
WriteDateTimeOffset((DateTimeOffset)obj);
else if (obj is TimeSpan)
_output.Append(((TimeSpan)obj).Ticks);
#if NET4
else if (_params.KVStyleStringDictionary == false &&
obj is IEnumerable<KeyValuePair<string, object>>)
WriteStringDictionary((IEnumerable<KeyValuePair<string, object>>)obj);
#endif
else if (_params.KVStyleStringDictionary == false && obj is IDictionary &&
obj.GetType().IsGenericType && Reflection.Instance.GetGenericArguments(obj.GetType())[0] == typeof(string))
WriteStringDictionary((IDictionary)obj);
else if (obj is IDictionary)
WriteDictionary((IDictionary)obj);
#if !SILVERLIGHT
else if (obj is DataSet)
WriteDataset((DataSet)obj);
else if (obj is DataTable)
this.WriteDataTable((DataTable)obj);
#endif
else if (obj is byte[])
WriteBytes((byte[])obj);
else if (obj is StringDictionary)
WriteSD((StringDictionary)obj);
else if (obj is NameValueCollection)
WriteNV((NameValueCollection)obj);
else if (obj is IEnumerable)
WriteArray((IEnumerable)obj);
else if (obj is Enum)
WriteEnum((Enum)obj);
else if (Reflection.Instance.IsTypeRegistered(obj.GetType()))
WriteCustom(obj);
else
WriteObject(obj);
}
private void WriteDateTimeOffset(DateTimeOffset d)
{
DateTime dt = _params.UseUTCDateTime ? d.UtcDateTime : d.DateTime;
write_date_value(dt);
var ticks = dt.Ticks % TimeSpan.TicksPerSecond;
_output.Append('.');
_output.Append(ticks.ToString("0000000", NumberFormatInfo.InvariantInfo));
if (_params.UseUTCDateTime)
_output.Append('Z');
else
{
if (d.Offset.Hours > 0)
_output.Append("+");
else
_output.Append("-");
_output.Append(d.Offset.Hours.ToString("00", NumberFormatInfo.InvariantInfo));
_output.Append(":");
_output.Append(d.Offset.Minutes.ToString("00", NumberFormatInfo.InvariantInfo));
}
_output.Append('\"');
}
private void WriteNV(NameValueCollection nameValueCollection)
{
_output.Append('{');
bool pendingSeparator = false;
foreach (string key in nameValueCollection)
{
if (_params.SerializeNullValues == false && (nameValueCollection[key] == null))
{
}
else
{
if (pendingSeparator) _output.Append(',');
if (_params.SerializeToLowerCaseNames)
WritePair(key.ToLowerInvariant(), nameValueCollection[key]);
else
WritePair(key, nameValueCollection[key]);
pendingSeparator = true;
}
}
_output.Append('}');
}
private void WriteSD(StringDictionary stringDictionary)
{
_output.Append('{');
bool pendingSeparator = false;
foreach (DictionaryEntry entry in stringDictionary)
{
if (_params.SerializeNullValues == false && (entry.Value == null))
{
}
else
{
if (pendingSeparator) _output.Append(',');
string k = (string)entry.Key;
if (_params.SerializeToLowerCaseNames)
WritePair(k.ToLowerInvariant(), entry.Value);
else
WritePair(k, entry.Value);
pendingSeparator = true;
}
}
_output.Append('}');
}
private void WriteCustom(object obj)
{
Reflection.Serialize s;
Reflection.Instance._customSerializer.TryGetValue(obj.GetType(), out s);
WriteStringFast(s(obj));
}
private void WriteEnum(Enum e)
{
// FEATURE : optimize enum write
if (_params.UseValuesOfEnums)
WriteValue(Convert.ToInt32(e));
else
WriteStringFast(e.ToString());
}
private void WriteGuid(Guid g)
{
if (_params.UseFastGuid == false)
WriteStringFast(g.ToString());
else
WriteBytes(g.ToByteArray());
}
private void WriteBytes(byte[] bytes)
{
#if !SILVERLIGHT
WriteStringFast(Convert.ToBase64String(bytes, 0, bytes.Length, Base64FormattingOptions.None));
#else
WriteStringFast(Convert.ToBase64String(bytes, 0, bytes.Length));
#endif
}
private void WriteDateTime(DateTime dateTime)
{
// datetime format standard : yyyy-MM-dd HH:mm:ss
DateTime dt = dateTime;
if (_params.UseUTCDateTime)
dt = dateTime.ToUniversalTime();
write_date_value(dt);
if (_params.DateTimeMilliseconds)
{
_output.Append('.');
_output.Append(dt.Millisecond.ToString("000", NumberFormatInfo.InvariantInfo));
}
if (_params.UseUTCDateTime)
_output.Append('Z');
_output.Append('\"');
}
private void write_date_value(DateTime dt)
{
_output.Append('\"');
_output.Append(dt.Year.ToString("0000", NumberFormatInfo.InvariantInfo));
_output.Append('-');
_output.Append(dt.Month.ToString("00", NumberFormatInfo.InvariantInfo));
_output.Append('-');
_output.Append(dt.Day.ToString("00", NumberFormatInfo.InvariantInfo));
_output.Append('T'); // strict ISO date compliance
_output.Append(dt.Hour.ToString("00", NumberFormatInfo.InvariantInfo));
_output.Append(':');
_output.Append(dt.Minute.ToString("00", NumberFormatInfo.InvariantInfo));
_output.Append(':');
_output.Append(dt.Second.ToString("00", NumberFormatInfo.InvariantInfo));
}
#if !SILVERLIGHT
private DatasetSchema GetSchema(DataTable ds)
{
if (ds == null) return null;
DatasetSchema m = new DatasetSchema();
m.Info = new List<string>();
m.Name = ds.TableName;
foreach (DataColumn c in ds.Columns)
{
m.Info.Add(ds.TableName);
m.Info.Add(c.ColumnName);
m.Info.Add(c.DataType.ToString());
}
// FEATURE : serialize relations and constraints here
return m;
}
private DatasetSchema GetSchema(DataSet ds)
{
if (ds == null) return null;
DatasetSchema m = new DatasetSchema();
m.Info = new List<string>();
m.Name = ds.DataSetName;
foreach (DataTable t in ds.Tables)
{
foreach (DataColumn c in t.Columns)
{
m.Info.Add(t.TableName);
m.Info.Add(c.ColumnName);
m.Info.Add(c.DataType.ToString());
}
}
// FEATURE : serialize relations and constraints here
return m;
}
private string GetXmlSchema(DataTable dt)
{
using (var writer = new StringWriter())
{
dt.WriteXmlSchema(writer);
return dt.ToString();
}
}
private void WriteDataset(DataSet ds)
{
_output.Append('{');
if (_params.UseExtensions)
{
WritePair("$schema", _params.UseOptimizedDatasetSchema ? (object)GetSchema(ds) : ds.GetXmlSchema());
_output.Append(',');
}
bool tablesep = false;
foreach (DataTable table in ds.Tables)
{
if (tablesep) _output.Append(',');
tablesep = true;
WriteDataTableData(table);
}
// end dataset
_output.Append('}');
}
private void WriteDataTableData(DataTable table)
{
_output.Append('\"');
_output.Append(table.TableName);
_output.Append("\":[");
DataColumnCollection cols = table.Columns;
bool rowseparator = false;
foreach (DataRow row in table.Rows)
{
if (rowseparator) _output.Append(',');
rowseparator = true;
_output.Append('[');
bool pendingSeperator = false;
foreach (DataColumn column in cols)
{
if (pendingSeperator) _output.Append(',');
WriteValue(row[column]);
pendingSeperator = true;
}
_output.Append(']');
}
_output.Append(']');
}
void WriteDataTable(DataTable dt)
{
this._output.Append('{');
if (_params.UseExtensions)
{
this.WritePair("$schema", _params.UseOptimizedDatasetSchema ? (object)this.GetSchema(dt) : this.GetXmlSchema(dt));
this._output.Append(',');
}
WriteDataTableData(dt);
// end datatable
this._output.Append('}');
}
#endif
bool _TypesWritten = false;
private void WriteObject(object obj)
{
int i = 0;
if (_cirobj.TryGetValue(obj, out i) == false)
_cirobj.Add(obj, _cirobj.Count + 1);
else
{
if (_current_depth > 0 && _params.InlineCircularReferences == false)
{
//_circular = true;
_output.Append("{\"$i\":");
_output.Append(i.ToString());
_output.Append("}");
return;
}
}
if (_params.UsingGlobalTypes == false)
_output.Append('{');
else
{
if (_TypesWritten == false)
{
_output.Append('{');
_before = _output.Length;
//_output = new StringBuilder();
}
else
_output.Append('{');
}
_TypesWritten = true;
_current_depth++;
if (_current_depth > _MAX_DEPTH)
throw new Exception("Serializer encountered maximum depth of " + _MAX_DEPTH);
Dictionary<string, string> map = new Dictionary<string, string>();
Type t = obj.GetType();
bool append = false;
if (_params.UseExtensions)
{
if (_params.UsingGlobalTypes == false)
WritePairFast("$type", Reflection.Instance.GetTypeAssemblyName(t));
else
{
int dt = 0;
string ct = Reflection.Instance.GetTypeAssemblyName(t);
if (_globalTypes.TryGetValue(ct, out dt) == false)
{
dt = _globalTypes.Count + 1;
_globalTypes.Add(ct, dt);
}
WritePairFast("$type", dt.ToString());
}
append = true;
}
Getters[] g = Reflection.Instance.GetGetters(t, _params.ShowReadOnlyProperties, _params.IgnoreAttributes);
int c = g.Length;
for (int ii = 0; ii < c; ii++)
{
var p = g[ii];
object o = p.Getter(obj);
if (_params.SerializeNullValues == false && (o == null || o is DBNull))
{
//append = false;
}
else
{
if (append)
_output.Append(',');
if (p.memberName != null)
WritePair(p.memberName, o);
else if (_params.SerializeToLowerCaseNames)
WritePair(p.lcName, o);
else
WritePair(p.Name, o);
if (o != null && _params.UseExtensions)
{
Type tt = o.GetType();
if (tt == typeof(System.Object))
map.Add(p.Name, tt.ToString());
}
append = true;
}
}
if (map.Count > 0 && _params.UseExtensions)
{
_output.Append(",\"$map\":");
WriteStringDictionary(map);
}
_output.Append('}');
_current_depth--;
}
private void WritePairFast(string name, string value)
{
WriteStringFast(name);
_output.Append(':');
WriteStringFast(value);
}
private void WritePair(string name, object value)
{
WriteString(name);
_output.Append(':');
WriteValue(value);
}
private void WriteArray(IEnumerable array)
{
_output.Append('[');
bool pendingSeperator = false;
foreach (object obj in array)
{
if (pendingSeperator) _output.Append(',');
WriteValue(obj);
pendingSeperator = true;
}
_output.Append(']');
}
private void WriteStringDictionary(IDictionary dic)
{
_output.Append('{');
bool pendingSeparator = false;
foreach (DictionaryEntry entry in dic)
{
if (_params.SerializeNullValues == false && (entry.Value == null))
{
}
else
{
if (pendingSeparator) _output.Append(',');
string k = (string)entry.Key;
if (_params.SerializeToLowerCaseNames)
WritePair(k.ToLowerInvariant(), entry.Value);
else
WritePair(k, entry.Value);
pendingSeparator = true;
}
}
_output.Append('}');
}
private void WriteStringDictionary(IEnumerable<KeyValuePair<string, object>> dic)
{
_output.Append('{');
bool pendingSeparator = false;
foreach (KeyValuePair<string, object> entry in dic)
{
if (_params.SerializeNullValues == false && (entry.Value == null))
{
}
else
{
if (pendingSeparator) _output.Append(',');
string k = entry.Key;
if (_params.SerializeToLowerCaseNames)
WritePair(k.ToLowerInvariant(), entry.Value);
else
WritePair(k, entry.Value);
pendingSeparator = true;
}
}
_output.Append('}');
}
private void WriteDictionary(IDictionary dic)
{
_output.Append('[');
bool pendingSeparator = false;
foreach (DictionaryEntry entry in dic)
{
if (pendingSeparator) _output.Append(',');
_output.Append('{');
WritePair("k", entry.Key);
_output.Append(",");
WritePair("v", entry.Value);
_output.Append('}');
pendingSeparator = true;
}
_output.Append(']');
}
private void WriteStringFast(string s)
{
_output.Append('\"');
_output.Append(s);
_output.Append('\"');
}
private void WriteString(string s)
{
_output.Append('\"');
int runIndex = -1;
int l = s.Length;
for (var index = 0; index < l; ++index)
{
var c = s[index];
if (_useEscapedUnicode)
{
if (c >= ' ' && c < 128 && c != '\"' && c != '\\')
{
if (runIndex == -1)
runIndex = index;
continue;
}
}
else
{
if (c != '\t' && c != '\n' && c != '\r' && c != '\"' && c != '\\' && c!='\0')// && c != ':' && c!=',')
{
if (runIndex == -1)
runIndex = index;
continue;
}
}
if (runIndex != -1)
{
_output.Append(s, runIndex, index - runIndex);
runIndex = -1;
}
switch (c)
{
case '\t': _output.Append("\\t"); break;
case '\r': _output.Append("\\r"); break;
case '\n': _output.Append("\\n"); break;
case '"':
case '\\': _output.Append('\\'); _output.Append(c); break;
case '\0': _output.Append("\\u0000"); break;
default:
if (_useEscapedUnicode)
{
_output.Append("\\u");
_output.Append(((int)c).ToString("X4", NumberFormatInfo.InvariantInfo));
}
else
_output.Append(c);
break;
}
}
if (runIndex != -1)
_output.Append(s, runIndex, s.Length - runIndex);
_output.Append('\"');
}
}
}
| 32.568741
| 130
| 0.460031
|
[
"MIT"
] |
utech626/Hoot.Standard
|
Hoot.Standard/fastJSON/JsonSerializer.cs
| 22,507
|
C#
|
// <copyright file="DraftNotification.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Apps.CompanyCommunicator.Models
{
using System.Collections.Generic;
/// <summary>
/// Draft notification model class.
/// </summary>
public class DraftNotification : BaseNotification
{
/// <summary>
/// Gets or sets Teams audience id collection.
/// </summary>
public IEnumerable<string> Teams { get; set; }
/// <summary>
/// Gets or sets Rosters audience id collection.
/// </summary>
public IEnumerable<string> Rosters { get; set; }
/// <summary>
/// Gets or sets a value indicating whether a notification should be sent to all the users.
/// </summary>
public bool AllUsers { get; set; }
public string FromEmail { get; internal set; }
public string ToEmail { get; set; }
}
}
| 29.636364
| 99
| 0.611452
|
[
"MIT"
] |
AtWorkRio/microsoft-teams-company-communicator-app
|
Source/Microsoft.Teams.Apps.CompanyCommunicator/Models/DraftNotification.cs
| 980
|
C#
|
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using UnityEngine;
namespace Guu.Language.Patchs
{
[HarmonyPatch(typeof (ResourceBundle))]
[HarmonyPatch("LoadFromText")]
internal static class LanguagePatch
{
[HarmonyPriority(Priority.Last)]
private static void Postfix(string path, Dictionary<string, string> __result, string text)
{
LanguageController.ResetTranslations(GameContext.Instance.MessageDirector);
if (!LanguageController.TRANSLATIONS.ContainsKey(path))
{
Debug.Log("Missing bundle in translations: " + path);
return;
}
foreach (KeyValuePair<string, string> keyValuePair in LanguageController.TRANSLATIONS[path])
{
if (__result.ContainsKey(keyValuePair.Key))
__result[keyValuePair.Key] = keyValuePair.Value;
else
__result.Add(keyValuePair.Key, keyValuePair.Value);
}
}
}
}
| 33.21875
| 104
| 0.614299
|
[
"MIT"
] |
RicardoTheCoder/ViktorsDiskoveries
|
Project/Guu.Common/Language/Patchs/LanguagePatch.cs
| 1,065
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using DxLibDLL;
using hsb.Extensions;
namespace dxw
{
#region 【StringSize】
/// <summary>
/// 文字列描画サイズ
/// </summary>
public struct StringSize
{
/// <summary>
/// 幅
/// </summary>
public int Width { get; set; }
/// <summary>
/// 高さ
/// </summary>
public int Height { get; set; }
/// <summary>
/// 行数
/// </summary>
public int LineCount { get; set; }
}
#endregion
#region 【JoyPadState】
/// <summary>
/// ジョイパッド状態
/// </summary>
public struct JoyPadState
{
/// <summary>
/// 各ボタン状態
/// </summary>
public byte[] Buttons;
/// <summary>
/// 右トリガ
/// </summary>
public byte RightTrigger;
/// <summary>
/// 左トリガ
/// </summary>
public byte LeftTrigger;
/// <summary>
/// 左スティックY軸
/// </summary>
public short ThumbLY;
/// <summary>
/// 左スティックX軸
/// </summary>
public short ThumbLX;
/// <summary>
/// 右スティックX軸
/// </summary>
public short ThumbRX;
/// <summary>
/// 右スティックY軸
/// </summary>
public short ThumbRY;
/// <summary>
/// ボタンが押下されている?
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
private bool IsDownButton(int n) => (Buttons?[n] ?? 0) == 1;
/// <summary>
/// デジタル方向キー上
/// </summary>
public bool DPadUp => IsDownButton(DX.XINPUT_BUTTON_DPAD_UP);
/// <summary>
/// デジタル方向キー下
/// </summary>
public bool DPadDown => IsDownButton(DX.XINPUT_BUTTON_DPAD_DOWN);
/// <summary>
/// デジタル方向キー左
/// </summary>
public bool DPadLeft => IsDownButton(DX.XINPUT_BUTTON_DPAD_LEFT);
/// <summary>
/// デジタル方向キー右
/// </summary>
public bool DPadRight => IsDownButton(DX.XINPUT_BUTTON_DPAD_RIGHT);
/// <summary>
/// スタートボタン
/// </summary>
public bool Start => IsDownButton(DX.XINPUT_BUTTON_START);
/// <summary>
/// バックボタン
/// </summary>
public bool Back => IsDownButton(DX.XINPUT_BUTTON_BACK);
/// <summary>
/// 左スティック
/// </summary>
public bool LeftThumb => IsDownButton(DX.XINPUT_BUTTON_LEFT_THUMB);
/// <summary>
/// 右スティック
/// </summary>
public bool RightThumb => IsDownButton(DX.XINPUT_BUTTON_RIGHT_THUMB);
/// <summary>
/// 左肩ボタン
/// </summary>
public bool LeftShoulder => IsDownButton(DX.XINPUT_BUTTON_LEFT_SHOULDER);
/// <summary>
/// 右肩ボタン
/// </summary>
public bool RightShoulder => IsDownButton(DX.XINPUT_BUTTON_RIGHT_SHOULDER);
/// <summary>
/// A ボタン
/// </summary>
public bool A => IsDownButton(DX.XINPUT_BUTTON_A);
/// <summary>
/// Bボタン
/// </summary>
public bool B => IsDownButton(DX.XINPUT_BUTTON_B);
/// <summary>
/// Xボタン
/// </summary>
public bool X => IsDownButton(DX.XINPUT_BUTTON_X);
/// <summary>
/// Yボタン
/// </summary>
public bool Y => IsDownButton(DX.XINPUT_BUTTON_Y);
}
#endregion
#region 【RGB】
/// <summary>
/// RGB構造体
/// </summary>
public readonly struct RGB
{
/// <summary>
/// 赤
/// </summary>
public readonly byte Red;
/// <summary>
/// 緑
/// </summary>
public readonly byte Green;
/// <summary>
/// 青
/// </summary>
public readonly byte Blue;
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="red"></param>
/// <param name="green"></param>
/// <param name="blue"></param>
public RGB(byte red, byte green, byte blue)
=> (Red, Green, Blue) = (red, green, blue);
/// <summary>
/// 色コードを返す
/// </summary>
/// <returns>色コード</returns>
public uint Color() => DX.GetColor(Red, Green, Blue);
}
#endregion
#region 【Static Class : Helper】
/// <summary>
/// ヘルパーメソッド
/// </summary>
public static class Helper
{
#region ■ Members
/// <summary>
/// マウスカーソルが表示されているか?
/// </summary>
private static bool _visibleMousrCursor = true;
/// <summary>
/// 描画領域
/// </summary>
private static Rectangle _drawingWindow = null;
/// <summary>
/// KeyCode → Char ルックアップテーブル
/// </summary>
private static readonly char[] KeyCode2CharTable = new char[]
{
(char)0 // (0)
,(char)0 // KEY_ESCAPE(1)
,'1' // KEY_1(2)
,'2' // KEY_2(3)
,'3' // KEY_3(4)
,'4' // KEY_4(5)
,'5' // KEY_5(6)
,'6' // KEY_6(7)
,'7' // KEY_7(8)
,'8' // KEY_8(9)
,'9' // KEY_9(10)
,'0' // KEY_0(11)
,'-' // KEY_MINUS(12)
,(char)0 // (13)
,(char)0 // KEY_BACK(14)
,(char)0 // KEY_TAB(15)
,'Q' // KEY_Q(16)
,'W' // KEY_W(17)
,'E' // KEY_E(18)
,'R' // KEY_R(19)
,'T' // KEY_T(20)
,'Y' // KEY_Y(21)
,'U' // KEY_U(22)
,'I' // KEY_I(23)
,'O' // KEY_O(24)
,'P' // KEY_P(25)
,'[' // KEY_LBRACKET(26)
,']' // KEY_RBRACKET(27)
,(char)0 // KEY_RETURN(28)
,(char)0 // KEY_LCONTROL(29)
,'A' // KEY_A(30)
,'S' // KEY_S(31)
,'D' // KEY_D(32)
,'F' // KEY_F(33)
,'G' // KEY_G(34)
,'H' // KEY_H(35)
,'J' // KEY_J(36)
,'K' // KEY_K(37)
,'L' // KEY_L(38)
,';' // KEY_SEMICOLON(39)
,(char)0 // (40)
,(char)0 // (41)
,(char)0 // KEY_LSHIFT(42)
,'\\' // KEY_BACKSLASH(43)
,'Z' // KEY_Z(44)
,'X' // KEY_X(45)
,'C' // KEY_C(46)
,'V' // KEY_V(47)
,'B' // KEY_B(48)
,'N' // KEY_N(49)
,'M' // KEY_M(50)
,',' // KEY_COMMA(51)
,'.' // KEY_PERIOD(52)
,'/' // KEY_SLASH(53)
,(char)0 // KEY_RSHIFT(54)
,'*' // KEY_MULTIPLY(55)
,(char)0 // KEY_LALT(56)
,' ' // KEY_SPACE(57)
,(char)0 // KEY_CAPSLOCK(58)
,(char)0 // KEY_F1(59)
,(char)0 // KEY_F2(60)
,(char)0 // KEY_F3(61)
,(Char)0 // KEY_F4(62)
,(char)0 // KEY_F5(63)
,(char)0 // KEY_F6(64)
,(char)0 // KEY_F7(65)
,(char)0 // KEY_F8(66)
,(char)0 // KEY_F9(67)
,(char)0 // KEY_F10(68)
,(char)0 // KEY_NUMLOCK(69)
,(char)0 // KEY_SCROLL(70)
,'7' // KEY_NUMPAD7(71)
,'8' // KEY_NUMPAD8(72)
,'9' // KEY_NUMPAD9(73)
,'-' // KEY_SUBTRACT(74)
,'4' // KEY_NUMPAD4(75)
,'5' // KEY_NUMPAD5(76)
,'6' // KEY_NUMPAD6(77)
,'+' // KEY_ADD(78)
,'1' // KEY_NUMPAD1(79)
,'2' // KEY_NUMPAD2(80)
,'3' // KEY_NUMPAD3(81)
,'0' // KEY_NUMPAD0(82)
,'.' // KEY_DECIMAL(83)
,(char)0 // (84)
,(char)0 // (85)
,(char)0 // (86)
,(char)0 // KEY_F11(87)
,(char)0 // KEY_F12(88)
,(char)0 // (89)
,(char)0 // (90)
,(char)0 // (91)
,(char)0 // (92)
,(char)0 // (93)
,(char)0 // (94)
,(char)0 // (95)
,(char)0 // (96)
,(char)0 // (97)
,(char)0 // (98)
,(char)0 // (99)
,(char)0 // (100)
,(char)0 // (101)
,(char)0 // (102)
,(char)0 // (103)
,(char)0 // (104)
,(char)0 // (105)
,(char)0 // (106)
,(char)0 // (107)
,(char)0 // (108)
,(char)0 // (109)
,(char)0 // (110)
,(char)0 // (111)
,(char)0 // KEY_KANA(112)
,(char)0 // (113)
,(char)0 // (114)
,(char)0 // (115)
,(char)0 // (116)
,(char)0 // (117)
,(char)0 // (118)
,(char)0 // (119)
,(char)0 // (120)
,(char)0 // KEY_CONVERT(121)
,(char)0 // (122)
,(char)0 // KEY_NOCONVERT(123)
,(char)0 // (124)
,'\\' // KEY_YEN(125)
,(char)0 // (126)
,(char)0 // (127)
,(char)0 // (128)
,(char)0 // (129)
,(char)0 // (130)
,(char)0 // (131)
,(char)0 // (132)
,(char)0 // (133)
,(char)0 // (134)
,(char)0 // (135)
,(char)0 // (136)
,(char)0 // (137)
,(char)0 // (138)
,(char)0 // (139)
,(char)0 // (140)
,(char)0 // (141)
,(char)0 // (142)
,(char)0 // (143)
,(char)0 // KEY_PREVTRACK(144)
,'@' // KEY_AT(146)
,':' // KEY_COLON(147)
,(char)0 // KEY_KANJI(148)
,(char)0 // (149)
,(char)0 // (150)
,(char)0 // (151)
,(char)0 // (152)
,(char)0 // (153)
,(char)0 // (154)
,(char)0 // (155)
,(char)0 // KEY_NUMPADENTER(156)
,(char)0 // KEY_RCONTROL(157)
,(char)0 // (158)
,(char)0 // (159)
,(char)0 // (160)
,(char)0 // (161)
,(char)0 // (162)
,(char)0 // (163)
,(char)0 // (164)
,(char)0 // (165)
,(char)0 // (166)
,(char)0 // (167)
,(char)0 // (168)
,(char)0 // (169)
,(char)0 // (170)
,(char)0 // (171)
,(char)0 // (172)
,(char)0 // (173)
,(char)0 // (174)
,(char)0 // (175)
,(char)0 // (176)
,(char)0 // (177)
,(char)0 // (178)
,(char)0 // (179)
,(char)0 // (180)
,'/' // KEY_DIVIDE(181)
,(char)0 // (182)
,(char)0 // KEY_SYSRQ(183)
,(char)0 // KEY_RALT(184)
,(char)0 // (185)
,(char)0 // (186)
,(char)0 // (187)
,(char)0 // (188)
,(char)0 // (189)
,(char)0 // (190)
,(char)0 // (191)
,(char)0 // (192)
,(char)0 // (193)
,(char)0 // (194)
,(char)0 // (195)
,(char)0 // (196)
,(char)0 // KEY_PAUSE(197)
,(char)0 // (198)
,(char)0 // KEY_HOME(199)
,(char)0 // KEY_UP(200)
,(char)0 // KEY_PGUP(201)
,(char)0 // (202)
,(char)0 // KEY_LEFT(203)
,(char)0 // (204)
,(char)0 // KEY_RIGHT(205)
,(char)0 // (206)
,(char)0 // KEY_END(207)
,(char)0 // KEY_DOWN(208)
,(char)0 // KEY_PGDN(209)
,(char)0 // KEY_INSERT(210)
,(char)0 // KEY_DELETE(211)
,(char)0 // (212)
,(char)0 // (213)
,(char)0 // (214)
,(char)0 // (215)
,(char)0 // (216)
,(char)0 // (217)
,(char)0 // (218)
,(char)0 // KEY_LWIN(219)
,(char)0 // KEY_RWIN(220)
,(char)0 // KEY_APPS(221)
};
#endregion
#region ■ Properties
#region - NumKeyCodes : 数字キーのKeyCode
/// <summary>
/// 数字キーのKeyCode
/// </summary>
public static KeyCode[] NumKeyCodes { get; private set; } = new KeyCode[]
{
KeyCode.KEY_0, KeyCode.KEY_1, KeyCode.KEY_2, KeyCode.KEY_3, KeyCode.KEY_4,
KeyCode.KEY_5, KeyCode.KEY_6, KeyCode.KEY_7, KeyCode.KEY_8, KeyCode.KEY_9,
KeyCode.KEY_NUMPAD0, KeyCode.KEY_NUMPAD1, KeyCode.KEY_NUMPAD2, KeyCode.KEY_NUMPAD3, KeyCode.KEY_NUMPAD4,
KeyCode.KEY_NUMPAD5, KeyCode.KEY_NUMPAD6, KeyCode.KEY_NUMPAD7, KeyCode.KEY_NUMPAD8, KeyCode.KEY_NUMPAD9
};
#endregion
#endregion
#region ■ Private Methods
#region - DXBool : DXライブラリの真偽値に変換する
/// <summary>
/// DXライブラリの真偽値に変換する
/// </summary>
/// <param name="sw">真偽値</param>
/// <returns>1:真 / 0:偽</returns>
private static int DXBool(bool sw) => sw ? DX.TRUE : DX.FALSE;
#endregion
#region - NormarizeVolume : 音量の正規化
/// <summary>
/// 音量の正規化 (0~250の範囲に収める)
/// </summary>
/// <param name="volume">音量</param>
/// <returns>正規化された音量</returns>
private static int NormarizeVolume(int volume)
{
if (volume < 0)
return 0;
if (volume > 250)
return 250;
return volume;
}
#endregion
#endregion
#region ■ Public Methods
#region - LoadFile : ファイルをバイト配列に読み込む
/// <summary>
/// ファイルをバイト配列に読み込む
/// </summary>
/// <param name="path">ファイルパス</param>
/// <returns>バイト配列</returns>
public static unsafe byte[] LoadFile(string path)
{
// ファイルサイズを取得
var fileSize = DX.FileRead_size(path);
if (fileSize > 0)
{
// 必要な領域を確保
var buff = new byte[fileSize];
// ファイルのOPEN
var fileHandle = DX.FileRead_open(path);
try
{
fixed (byte *p = buff)
{
DX.FileRead_read(new IntPtr(p), (int)fileSize, fileHandle);
}
}
finally
{
DX.FileRead_close(fileHandle);
}
return buff;
}
return null;
}
#endregion
#region ☆ システム関連
#region - InitializeDxLibrary : DXライブラリの初期化
/// <summary>
/// DXライブラリの初期化
/// </summary>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool InitializeDxLibrary()
=> DX.DxLib_Init() == 0;
#endregion
#region - TerminateDxLibrary : DXライブラリの終了処理
/// <summary>
/// DXライブラリの終了処理
/// </summary>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool TerminateDxLibrary()
=> DX.DxLib_End() == 0;
#endregion
#region - ProcessMessage : ウインドウのメッセージを処理する
/// <summary>
/// ウインドウのメッセージを処理する
/// </summary>
/// <returns>true: 成功 / False: 失敗</returns>
public static bool ProcessMessage()
=> DX.ProcessMessage() == 0;
#endregion
#region - GetRand : 整数の乱数を取得する
/// <summary>
/// 整数の乱数を取得する
/// </summary>
/// <param name="max">最大値</param>
/// <returns>乱数値</returns>
public static int GetRand(int max)
=> DX.GetRand(max);
/// <summary>
/// 整数の乱数を取得する
/// </summary>
/// <param name="min">最小値</param>
/// <param name="max">最大値</param>
/// <returns>乱数値</returns>
public static int GetRand(int min, int max)
=> min + DX.GetRand(max - min);
#endregion
#region - SetAlwaysRun : ウィンドウがアクティブでないときでも処理を継続させるか?
/// <summary>
/// ウィンドウがアクティブでないときでも処理を継続させるか?
/// </summary>
/// <param name="flg">True : 継続させる / False : 継続させない</param>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool SetAlwaysRun(bool flg)
=> DX.SetAlwaysRunFlag(DXBool(flg)) == 0;
#endregion
#endregion
#region ☆ ウィンドウモード関連関数
#region - SetMainWindowText : ウインドウのタイトルを変更する
/// <summary>
/// ウインドウのタイトルを変更する
/// </summary>
/// <param name="s">タイトル文字列</param>
public static void SetMainWindowText(string s)
=> DX.SetMainWindowText(s);
#endregion
#region - ChangeWindowMode : ウインドウモード・フルスクリーンモードの変更を行う
/// <summary>
/// ウインドウモード・フルスクリーンモードの変更を行う
/// </summary>
/// <param name="windowMode">ウィンドウモード</param>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool ChangeWindowMode(WindowMode windowMode)
{
_visibleMousrCursor = (windowMode == WindowMode.Window);
return DX.ChangeWindowMode((int)windowMode) == DX.DX_CHANGESCREEN_OK;
}
#endregion
#endregion
#region ☆ グラフィックデータ制御関数
#region - CreateDrawableGraph : 描画可能なグラフィックを生成する。
/// <summary>
/// 描画可能なグラフィックを生成する。
/// </summary>
/// <param name="width">幅(PX)</param>
/// <param name="height">高さ(PX)</param>
/// <param name="useAlphaChannel">アルファチャネルの有効化</param>
/// <returns>グラフィックハンドル</returns>
public static int CreateDrawableGraph(float width, float height, bool useAlphaChannel = false)
=> DX.MakeScreen(Convert.ToInt32(Math.Floor(width)), Convert.ToInt32(Math.Floor(height)), DXBool(useAlphaChannel));
#endregion
#region - CreateDrawableGraph : 描画可能なグラフィックを生成する。
/// <summary>
/// 描画可能なグラフィックを生成する。
/// </summary>
/// <param name="size">サイズ</param>
/// <param name="useAlphaChannel">アルファチャネルの有効化</param>
/// <returns>グラフィックハンドル</returns>
public static int CreateDrawableGraph(RectangleSize size, bool useAlphaChannel = false)
=> DX.MakeScreen(size.IWidth, size.IHeight, DXBool(useAlphaChannel));
#endregion
#region - CreateDrawableGraph : 描画可能なグラフィックを生成する。
/// <summary>
/// 描画可能なグラフィックを生成する。
/// </summary>
/// <param name="width">幅(px)</param>
/// <param name="height">高さ(px)</param>
/// <param name="useAlphaChannel">アルファチャネルの有効化</param>
/// <param name="callback">コールバック</param>
/// <returns>グラフィックハンドル</returns>
public static int CreateDrawableGraph(float width, float height, bool useAlphaChannel, Action callback)
{
var graph = CreateDrawableGraph(width, height, useAlphaChannel);
if (graph >= 0)
{
if (callback != null)
{
DX.SetDrawScreen(graph);
try
{
callback();
}
catch
{
DX.DeleteGraph(graph);
throw;
}
finally
{
DX.SetDrawScreen(DX.DX_SCREEN_BACK);
}
}
}
return graph;
}
#endregion
#region - CreateDrawableGraph : 描画可能なグラフィックを生成する。
/// <summary>
/// 描画可能なグラフィックを生成する。
/// </summary>
/// <param name="size">サイズ</param>
/// <param name="useAlphaChannel">アルファチャネルの有効化</param>
/// <param name="callback">コールバック</param>
/// <returns>グラフィックハンドル</returns>
public static int CreateDrawableGraph(RectangleSize size, bool useAlphaChannel, Action callback)
=> CreateDrawableGraph(size.Width, size.Height, useAlphaChannel, callback);
#endregion
#region - DeleteGraph : グラフィックをメモリから削除する。
/// <summary>
/// グラフィックをメモリから削除する。
/// </summary>
/// <param name="handle">グラフィックハンドル</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool DeleteGraph(int handle)
=> DX.DeleteGraph(handle) == 0;
#endregion
#region - DrawGraph : メモリに読み込んだグラフィックの描画
/// <summary>
/// メモリに読み込んだグラフィックの描画
/// </summary>
/// <param name="x">X座標(px)</param>
/// <param name="y">Y座標(px)</param>
/// <param name="handle">グラフィックハンドル</param>
/// <param name="enableTranslate">透過を有効にする</param>
/// <returns>True : 成功 . False : 失敗</returns>
public static bool DrawGraph(float x, float y, int handle, bool enableTranslate = false)
{
if (handle == 0)
return false;
var _x = (_drawingWindow?.X ?? 0f) + x;
var _y = (_drawingWindow?.Y ?? 0f) + y;
return DX.DrawGraph(Convert.ToInt32(Math.Floor(_x)), Convert.ToInt32(Math.Floor(_y)), handle, DXBool(enableTranslate)) == 0;
}
#endregion
#region - DrawGraph : メモリに読み込んだグラフィックの描画
/// <summary>
/// メモリに読み込んだグラフィックの描画
/// </summary>
/// <param name="pt">座標</param>
/// <param name="handle">グラフィックハンドル</param>
/// <param name="enableTranslate">透過を有効にする</param>
/// <returns>True : 成功 . False : 失敗</returns>
public static bool DrawGraph(Point pt, int handle, bool enableTranslate = false)
=> DrawGraph(pt.X, pt.Y, handle, enableTranslate);
#endregion
#region - DrawRectGraph : グラフィックの指定矩形部分のみを描画
/// <summary>
/// グラフィックの指定矩形部分のみを描画
/// </summary>
/// <param name="x">X座標</param>
/// <param name="y">Y座標</param>
/// <param name="srcX">描画するグラフィック範囲のX座標</param>
/// <param name="srcY">描画するグラフィック範囲のY座標</param>
/// <param name="widht">描画するグラフィック範囲の幅</param>
/// <param name="height">描画するぐらふぃく範囲の高さ</param>
/// <param name="handle">グラフィックハンドル</param>
/// <param name="enableTranslate">透過を有効にする</param>
/// <param name="enableVeritcalTurn">画像の垂直方向反転を有効にする</param>
/// <param name="enableHorizontalTurn">画像の水平方向反転を有効にする</param>
/// <returns>True : 成功 . False : 失敗</returns>
public static bool DrawRectGraph(float x, float y, float srcX, float srcY, float widht, float height,
int handle, bool enableTranslate = false, bool enableVeritcalTurn = false, bool enableHorizontalTurn = false)
{
if (handle == 0)
return false;
var _x = (_drawingWindow?.X ?? 0f) + x;
var _y = (_drawingWindow?.Y ?? 0f) + y;
return DX.DrawRectGraph(
Convert.ToInt32(Math.Floor(_x)), Convert.ToInt32(Math.Floor(_y)),
Convert.ToInt32(Math.Floor(srcX)), Convert.ToInt32(Math.Floor(srcY)),
Convert.ToInt32(Math.Floor(widht)), Convert.ToInt32(Math.Floor(height)),
handle, DXBool(enableTranslate), DXBool(enableVeritcalTurn), DXBool(enableHorizontalTurn)) == 0;
}
#endregion
#region - DrawRectGraph :
/// <summary>
/// グラフィックの指定矩形部分のみを描画
/// </summary>
/// <param name="pt">座標</param>
/// <param name="srcRect">描画するグラフィックの範囲</param>
/// <param name="handle">グラフィックハンドル</param>
/// <param name="enableTranslate">透過を有効にする</param>
/// <param name="enableVeritcalTurn">画像の反転を有効にする</param>
/// <param name="enableHorizontalTurn">画像の水平方向反転を有効にする</param>
/// <returns>True : 成功 . False : 失敗</returns>
public static bool DrawRectGraph(Point pt, Rectangle srcRect, int handle, bool enableTranslate = false,
bool enableVeritcalTurn = false, bool enableHorizontalTurn = false)
=> DrawRectGraph(pt.X, pt.Y, srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, handle,
enableTranslate, enableVeritcalTurn, enableHorizontalTurn);
#endregion
#region - DrawExtendGraph : メモリに読みこんだグラフィックの拡大縮小描画
/// <summary>
/// メモリに読みこんだグラフィックの拡大縮小描画
/// </summary>
/// <param name="x1">左上座標X軸(px)</param>
/// <param name="y1">左上座標Y軸(px)</param>
/// <param name="x2">右下座標X軸(px)</param>
/// <param name="y2">右下座標Y軸(px)</param>
/// <param name="handle">グラフィックハンドル</param>
/// <param name="enableTranslate">透過を有効にする</param>
/// <returns>True : 成功 . False : 失敗</returns>
public static bool DrawExtendGraph(float x1, float y1, float x2, float y2, int handle, bool enableTranslate = false)
{
var _x1 = (_drawingWindow?.X ?? 0f) + x1;
var _y1 = (_drawingWindow?.Y ?? 0f) + y1;
var _x2 = (_drawingWindow?.X ?? 0f) + x2;
var _y2 = (_drawingWindow?.Y ?? 0f) + y2;
return DX.DrawExtendGraph(
Convert.ToInt32(Math.Floor(_x1)), Convert.ToInt32(Math.Floor(_y1)),
Convert.ToInt32(Math.Floor(_x2)), Convert.ToInt32(Math.Floor(_y2)), handle, DXBool(enableTranslate)) == 0;
}
#endregion
#region - DrawRotaGraph : メモリに読みこんだグラフィックの回転描画
/// <summary>
/// メモリに読みこんだグラフィックの回転描画
/// </summary>
/// <param name="x1">中心座標X軸(px)</param>
/// <param name="y1">中心座標Y軸(px)</param>
/// <param name="rate">拡大率</param>
/// <param name="angle">角度</param>
/// <param name="handle"></param>
/// <param name="enableTranslate"></param>
/// <param name="handle">グラフィックハンドル</param>
/// <param name="enableTranslate">透過を有効にする</param>
/// <returns>True : 成功 . False : 失敗</returns>
public static bool DrawRotaGraph(float x, float y, double rate, double angle, int handle, bool enableTranslate = false)
{
if (handle == 0)
return false;
var _x = (_drawingWindow?.X ?? 0f) + x;
var _y = (_drawingWindow?.Y ?? 0f) + y;
return DX.DrawRotaGraph(Convert.ToInt32(Math.Floor(_x)), Convert.ToInt32(Math.Floor(_y)), rate, angle, handle, DXBool(enableTranslate)) == 0;
}
#endregion
#region - DrawRotaGraph : メモリに読みこんだグラフィックの回転描画
/// <summary>
/// メモリに読みこんだグラフィックの回転描画
/// </summary>
/// <param name="pt">中央座標</param>
/// <param name="rate">拡大率</param>
/// <param name="angle">角度</param>
/// <param name="handle"></param>
/// <param name="enableTranslate"></param>
/// <param name="handle">グラフィックハンドル</param>
/// <param name="enableTranslate">透過を有効にする</param>
/// <returns>True : 成功 . False : 失敗</returns>
public static bool DrawRotaGraph(Point pt, double rate, double angle, int handle, bool enableTranslate = false)
=> DrawRotaGraph(pt.X, pt.Y, rate, angle, handle, enableTranslate);
#endregion
#region - LoadGraph : 画像ファイルのメモリへの読みこみ
/// <summary>
/// 画像ファイルのメモリへの読みこみ
/// </summary>
/// <param name="fileName">ファイル名</param>
/// <returns>グラフィックハンドル</returns>
public static int LoadGraph(string fileName)
=> DX.LoadGraph(fileName);
#endregion
#region - LoadDivGraph : 画像ファイルを分割して複数イメージとしてメモリへ読み込む
/// <summary>
/// 画像ファイルを分割して複数イメージとしてメモリへ読み込む
/// </summary>
/// <param name="fileName">ファイル名</param>
/// <param name="allNum">総数</param>
/// <param name="column">列数</param>
/// <param name="row">行数</param>
/// <param name="width">幅</param>
/// <param name="heigth">高さ</param>
/// <returns>グラフィックハンドルのリスト</returns>
public static int[] LoadDivGraph(string fileName, int allNum, int column, int row, int width, int heigth)
{
var buff = new int[allNum];
if (DX.LoadDivGraph(fileName, allNum, column, row, width, heigth, buff) == 0)
return buff;
return null;
}
#endregion
#region - GetGraphSize : グラフィックのサイズを取得する
/// <summary>
/// グラフィックのサイズを取得する
/// </summary>
/// <param name="handle">グラフィックハンドル</param>
/// <returns>サイズ</returns>
public static RectangleSize? GetGraphSize(int handle)
{
if (handle != 0 && DX.GetGraphSize(handle, out var width, out var height) == 0)
{
return new RectangleSize(width, height);
}
return null;
}
#endregion
#region - SetDrawBrendMode : 描画の際のブレンドモードをセットする
/// <summary>
/// 描画の際のブレンドモードをセットする
/// </summary>
/// <param name="brendMode">ブレンドモード</param>
/// <param name="blendParam">パラメーター値</param>
/// <returns>true: 成功 / False: 失敗</returns>
public static bool SetDrawBrendMode(BrendMode brendMode, int blendParam)
=> DX.SetDrawBlendMode((int)brendMode, blendParam) == 0;
#endregion
#region - DrawBrend : 指定したブレンドモードで描画を実行する
/// <summary>
/// 指定したブレンドモードで描画を実行する
/// </summary>
/// <param name="brendMode">ブレンドモード</param>
/// <param name="blendParam">パラメーター値</param>
/// <param name="acttion">描画アクション</param>
public static void DrawBrend(BrendMode brendMode, int blendParam, Action acttion)
{
DX.SetDrawBlendMode((int)brendMode, blendParam);
try
{
acttion?.Invoke();
}
finally
{
DX.SetDrawBlendMode((int)BrendMode.NoBrend, 255);
}
}
#endregion
#region - SetDrawBright : 描画輝度をセット
/// <summary>
/// 描画輝度をセット
/// </summary>
/// <param name="redBright">赤描画輝度(0-255)</param>
/// <param name="greenBright">緑描画輝度(0-255)</param>
/// <param name="blueBright">青描画輝度(0-255)</param>
/// <returns>true: 成功 / False: 失敗</returns>
public static bool SetDrawBright(int redBright, int greenBright, int blueBright)
=> DX.SetDrawBright(redBright, greenBright, blueBright) == 0;
#endregion
#region - SetDrawArea : 描画領域を指定する
/// <summary>
/// 描画領域を指定する
/// </summary>
/// <param name="x1">X1座標</param>
/// <param name="y1">Y1座標</param>
/// <param name="x2">X2座標</param>
/// <param name="y2">Y2座標</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool SetDrawArea(float x1, float y1, float x2, float y2)
=> DX.SetDrawArea(
Convert.ToInt32(Math.Floor(x1)), Convert.ToInt32(Math.Floor(y1)),
Convert.ToInt32(Math.Floor(x2)), Convert.ToInt32(Math.Floor(y2))) == 0;
#endregion
#region - SetDrawArea : 描画領域を指定する
/// <summary>
/// 描画領域を指定する
/// </summary>
/// <param name="r">描画領域とする矩形</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool SetDrawArea(Rectangle r)
=> DX.SetDrawArea(r.IX, r.IY, r.IX2, r.IY2) == 0;
#endregion
#region - ClearDrawArea : 指定した描画領域を解除する
/// <summary>
/// 指定した描画領域を解除する
/// </summary>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool ClearDrawArea()
=> DX.SetDrawAreaFull() == 0;
#endregion
#region - SetDrawingWindow : 描画領域を指定する
/// <summary>
/// 描画領域を指定する
/// </summary>
/// <param name="r">描画領域</param>
/// <param name="enableClipping">クリッピングを有効にする</param>
public static Rectangle SetDrawingWindow(Rectangle r, bool enableClipping= true)
{
var prevWindow = _drawingWindow;
if (enableClipping)
{
if (r != null)
SetDrawArea(r);
else
ClearDrawArea();
}
_drawingWindow = r;
return prevWindow;
}
#endregion
#region - SetDrawingWindow : 描画領域を指定する
/// <summary>
/// 描画領域を指定する
/// </summary>
/// <param name="r">描画領域</param>
/// <param name="enableClipping">クリッピングを有効にする</param>
/// <param name="act">コールバック</param>
public static void SetDrawingWindow(Rectangle r, bool enableClipping, Action act)
{
var prevRect = SetDrawingWindow(r, enableClipping);
try
{
act();
}
finally
{
SetDrawingWindow(prevRect);
}
}
#endregion
#region - ClearDrawingWindow: 描画領域をクリアする
/// <summary>
/// 描画領域をクリアする
/// </summary>
public static void ClearDrawingWindow()
{
ClearDrawArea();
}
#endregion
#region - GraphInvert : グラフィックを反転させる
/// <summary>
/// グラフィックを反転させる
/// </summary>
/// <param name="handle">グラフィックハンドル</param>
/// <returns>True : 成功 . False : 失敗</returns>
public static bool GraphInvert(int handle)
=> DX.GraphFilter(handle, DX.DX_GRAPH_FILTER_INVERT) == 0;
#endregion
#endregion
#region ☆ 図形描画関数
#region - DrawLine : 直線を描画する
/// <summary>
/// 直線を描画する
/// </summary>
/// <param name="x1">起点X座標(px)</param>
/// <param name="y1">起点Y座標(px)</param>
/// <param name="x2">終点X座標(px)</param>
/// <param name="y2">終点Y座標(px)</param>
/// <param name="color">色</param>
/// <param name="thickness">線の太さ</param>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool DrawLine(float x1, float y1, float x2, float y2, uint color, int thickness = 1)
{
var _x1 = (_drawingWindow?.X ?? 0f) + x1;
var _y1 = (_drawingWindow?.Y ?? 0f) + y1;
var _x2 = (_drawingWindow?.X ?? 0f) + x2;
var _y2 = (_drawingWindow?.Y ?? 0f) + y2;
return DX.DrawLine(
Convert.ToInt32(Math.Floor(_x1)), Convert.ToInt32(Math.Floor(_y1)),
Convert.ToInt32(Math.Floor(_x2)), Convert.ToInt32(Math.Floor(_y2)), color, thickness) == 0;
}
#endregion
#region - DrawLine : 直線を描画する
/// <summary>
/// 直線を描画する
/// </summary>
/// <param name="pt1">起点座標(px)</param>
/// <param name="pt2">終点座標(px)</param>
/// <param name="color">色</param>
/// <param name="thickness">線の太さ</param>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool DrawLine(Point pt1, Point pt2, uint color, int thickness = 1)
{
var _x1 = (_drawingWindow?.X ?? 0f) + pt1.X;
var _y1 = (_drawingWindow?.Y ?? 0f) + pt1.Y;
var _x2 = (_drawingWindow?.X ?? 0f) + pt2.X;
var _y2 = (_drawingWindow?.Y ?? 0f) + pt2.Y;
return DX.DrawLine(
Convert.ToInt32(Math.Floor(_x1)), Convert.ToInt32(Math.Floor(_y1)),
Convert.ToInt32(Math.Floor(_x2)), Convert.ToInt32(Math.Floor(_y2)), color, thickness) == 0;
}
#endregion
#region - DrawAntiAliasingLine : 直線を描画する(アンチエリアス適用)
/// <summary>
/// 直線を描画する(アンチエリアス適用)
/// </summary>
/// <param name="x1">起点X座標(px)</param>
/// <param name="y1">起点Y座用(px)</param>
/// <param name="x2">終点X座標(px)</param>
/// <param name="y2">終点Y座標(px)</param>
/// <param name="color">色</param>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool DrawAntiAliasingLine(float x1, float y1, float x2, float y2, uint color, float thickness = 1.0f)
{
var _x1 = (_drawingWindow?.X ?? 0f) + x1;
var _y1 = (_drawingWindow?.Y ?? 0f) + y1;
var _x2 = (_drawingWindow?.X ?? 0f) + x2;
var _y2 = (_drawingWindow?.Y ?? 0f) + y2;
return DX.DrawLineAA(_x1, _y1, _x2, _y2, color, thickness) == 0;
}
#endregion
#region - DrawAntiAliasingLine : 直線を描画する(アンチエリアス適用)
/// <summary>
/// 直線を描画する(アンチエリアス適用)
/// </summary>
/// <param name="x1">起点X座標(px)</param>
/// <param name="y1">起点Y座用(px)</param>
/// <param name="x2">終点X座標(px)</param>
/// <param name="y2">終点Y座標(px)</param>
/// <param name="color">色</param>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool DrawAntiAliasingLine(Point pt1, Point pt2, uint color, float thickness = 1.0f)
{
var _x1 = (_drawingWindow?.X ?? 0f) + pt1.X;
var _y1 = (_drawingWindow?.Y ?? 0f) + pt1.Y;
var _x2 = (_drawingWindow?.X ?? 0f) + pt2.X;
var _y2 = (_drawingWindow?.Y ?? 0f) + pt2.Y;
return DX.DrawLineAA(_x1, _y1, _x2, _y2, color, thickness) == 0;
}
#endregion
#region - DrawRectangle : 矩形を描画する
/// <summary>
/// 矩形を描画する
/// </summary>
/// <param name="x">X軸(px)</param>
/// <param name="y">Y軸(px)</param>
/// <param name="width">幅(px)</param>
/// <param name="height">高さ(px)</param>
/// <param name="color">色</param>
/// <param name="isFill">塗りつぶす?</param>
public static bool DrawRectangle(float x, float y, float width, float height, uint color, bool isFill = false)
{
var _x = (_drawingWindow?.X ?? 0f) + x;
var _y = (_drawingWindow?.Y ?? 0f) + y;
return DX.DrawBox(
Convert.ToInt32(Math.Floor(_x)), Convert.ToInt32(Math.Floor(_y)),
Convert.ToInt32(Math.Floor(_x + width)), Convert.ToInt32(Math.Floor(_y + height)),
color, DXBool(isFill)) == 0;
}
#endregion
#region - DrawRectangle : 矩形を描画する
/// <summary>
/// 矩形を描画する
/// </summary>
/// <param name="rect">矩形</param>
/// <param name="color">色</param>
/// <param name="isFill">塗りつぶす?</param>
public static bool DrawRectangle(Rectangle rect, uint color, bool isFill = false)
=> DrawRectangle(rect.X, rect.Y, rect.Width, rect.Height, color, isFill);
#endregion
#region - DrawRectangle : 矩形を描画する
/// <summary>
/// 矩形を描画する
/// </summary>
/// <param name="pt">座標</param>
/// <param name="size">サイズ</param>
/// <param name="color">色</param>
/// <param name="isFill">塗りつぶす?</param>
public static bool DrawRectangle(Point pt, RectangleSize size, uint color, bool isFill = false)
=> DrawRectangle(pt.X, pt.Y, size.Width, size.Height, color, isFill);
#endregion
#region - DrawRectangle : 矩形を描画する
/// <summary>
/// 矩形を描画する
/// </summary>
/// <param name="leftTop">左上座標</param>
/// <param name="rightBottom">右下座標</param>
/// <param name="color">色</param>
/// <param name="isFill">塗りつぶす?</param>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool DrawRectangle(Point leftTop, Point rightBottom, uint color, bool isFill = false)
=> DrawRectangle(new Rectangle(leftTop, rightBottom), color, isFill);
#endregion
#region - DrawRoundRectangle : 角丸矩形を描画する
/// <summary>
/// 角丸矩形を描画する
/// </summary>
/// <param name="x">X軸(px)</param>
/// <param name="y">Y軸(px)</param>
/// <param name="width">幅(px)</param>
/// <param name="height">高さ(px)</param>
/// <param name="r">角丸半径</param>
/// <param name="color">色</param>
/// <param name="isFill">塗りつぶす?</param>
public static bool DrawRoundRectangle(float x, float y, float width, float height, float r, uint color, bool isFill = false)
{
var _x = (_drawingWindow?.IX ?? 0) + x;
var _y = (_drawingWindow?.IY ?? 0) + y;
return DX.DrawRoundRect(
Convert.ToInt32(Math.Floor(_x)), Convert.ToInt32(Math.Floor(_y)),
Convert.ToInt32(Math.Floor(_x + width)), Convert.ToInt32(Math.Floor(_y + height)),
Convert.ToInt32(Math.Floor(r)), Convert.ToInt32(Math.Floor(r)), color, DXBool(isFill)) == 0;
}
#endregion
#region - DrawRoundRectangle : 角丸矩形を描画する
/// <summary>
/// 角丸矩形を描画する
/// </summary>
/// <param name="rect">矩形</param>
/// <param name="r">角丸半径</param>
/// <param name="color">色</param>
/// <param name="isFill">塗りつぶす?</param>
public static bool DrawRoundRectangle(Rectangle rect, float r, uint color, bool isFill = false)
=> DrawRoundRectangle(rect.X, rect.Y, rect.Width, rect.Height, r, color, isFill);
#endregion
#region - DrawRoundRectangle : 角丸矩形を描画する
/// <summary>
/// 角丸矩形を描画する
/// </summary>
/// <param name="pt">座標</param>
/// <param name="size">サイズ</param>
/// <param name="r">角丸半径</param>
/// <param name="color">色</param>
/// <param name="isFill">塗りつぶす?</param>
public static bool DrawRoundRectangle(Point pt, RectangleSize size, float r, uint color, bool isFill = false)
=> DrawRoundRectangle(pt.X, pt.Y, size.Width, size.Height, r, color, isFill);
#endregion
#region - DrawRoundRectangle : 角丸矩形を描画する
/// <summary>
/// 角丸矩形を描画する
/// </summary>
/// <param name="leftTop">左上座標</param>
/// <param name="rightBottom">右下座標</param>
/// <param name="r">角丸半径</param>
/// <param name="color">色</param>
/// <param name="isFill">塗りつぶす?</param>
public static bool DrawRoundRectangle(Point leftTop, Point rightBottom, float r, uint color, bool isFill = false)
=> DrawRoundRectangle(new Rectangle(leftTop, rightBottom), r, color, isFill);
#endregion
#region - DrawCircle : 円を描画する
/// <summary>
/// 円を描画する
/// </summary>
/// <param name="x">円の中心X座標(px)</param>
/// <param name="y">円の中心Y座標(px)</param>
/// <param name="r">円の半径(px)</param>
/// <param name="color">色</param>
/// <param name="isFill">塗りつぶす?</param>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool DrawCircle(float x, float y, float r, uint color, bool isFill = false)
{
var _x = (_drawingWindow?.X ?? 0f) + x;
var _y = (_drawingWindow?.Y ?? 0f) + y;
return DX.DrawCircle(Convert.ToInt32(Math.Floor(_x)), Convert.ToInt32(Math.Floor(_y)),
Convert.ToInt32(Math.Floor(r)), color, DXBool(isFill)) == 0;
}
#endregion
#region - DrawCircle : 円を描画する
/// <summary>
/// 円を描画する
/// </summary>
/// <param name="pt">円の中心座標(Point)</param>
/// <param name="r">円の半径(px)</param>
/// <param name="color">色</param>
/// <param name="isFill">塗りつぶす?</param>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool DrawCircle(Point pt, float r, uint color, bool isFill = false)
=> DrawCircle(pt.X, pt.Y, r, color, isFill);
#endregion
#region - DrawAntiAliasingBox : 矩形を描画する
/// <summary>
/// 矩形を描画する
/// </summary>
/// <param name="x">X座上(px)</param>
/// <param name="y">Y座h上(px)</param>
/// <param name="width">幅(px)</param>
/// <param name="height">高さ(px)</param>
/// <param name="color">色</param>
/// <param name="isFill">塗りつぶす?</param>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool DrawAntiAliasingBox(float x, float y, float width, float height, uint color, bool isFill = false)
{
var _x = (_drawingWindow?.X ?? 0f) + x;
var _y = (_drawingWindow?.Y ?? 0f) + y;
return DX.DrawBoxAA(_x, _y, _x + width, _y + height, color, DXBool(isFill)) == 0;
}
#endregion
#region - DrawPolygon : ポリゴンを描画する
/// <summary>
/// ポリゴンを描画する
/// </summary>
/// <param name="vertexs">VERTEX2D</param>
/// <param name="polygonNum"></param>
/// <param name="h"></param>
/// <param name="flag"></param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool DrawPolygon(DX.VERTEX2D[] vertexs, int polygonNum, int h, int flag)
=> DX.DrawPolygon2D(vertexs, polygonNum, h, flag) == 0;
#endregion
#region - DrawGradationBox : グラデーション背景の矩形を描く
/// <summary>
/// グラデーション背景の矩形を描く
/// </summary>
/// <param name="x">X座標(px)</param>
/// <param name="y">Y座標(px)</param>
/// <param name="widht">幅(px)</param>
/// <param name="height">高さ(px)</param>
/// <param name="fromColor">開始色(RGB)</param>
/// <param name="toColor">終了色(RGB)</param>
/// <param name="orientation">方向</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool DrawGradationBox(float x, float y, float widht, float height, RGB fromColor, RGB toColor, Orientation orientation)
{
var _x = (_drawingWindow?.X ?? 0f) + x;
var _y = (_drawingWindow?.Y ?? 0f) + y;
DX.VERTEX2D CreateVertex(float px, float py, RGB rgb)
{
return new DX.VERTEX2D
{
pos = new DX.VECTOR { x = px, y = py, z = 0.0f },
rhw = 1.0f,
dif = new DX.COLOR_U8 { r = rgb.Red, g = rgb.Green, b = rgb.Blue, a = 255 },
u = 0.0f,
v = 0.0f
};
}
var vertex = new DX.VERTEX2D[]
{
// 第1ポリゴンの頂点1(左上)
CreateVertex(_x, _y, fromColor),
// 第1ポリゴンの頂点2(右上)
CreateVertex(_x + widht, _y, orientation.IsHorizontal() ? toColor : fromColor),
// 第1ポリゴンの頂点3(左下)
CreateVertex(_x, _y + height, orientation.IsVertical() ? toColor : fromColor),
// 第2ポリゴンの頂点1(右下)
CreateVertex(_x + widht, _y + height, toColor),
// 第2ポリゴンの頂点2(左下)
CreateVertex(_x, _y + height,orientation.IsVertical() ? toColor : fromColor),
// 第2ポリゴンの頂点3(右上)
CreateVertex(_x + widht, _y, orientation.IsHorizontal() ? toColor : fromColor),
};
return DrawPolygon(vertex, 2, DX.DX_NONE_GRAPH, 0);
}
#endregion
#region - DrawGradationBox : グラデーション背景の矩形を描く
/// <summary>
/// グラデーション背景の矩形を描く
/// </summary>
/// <param name="rect">矩形</param>
/// <param name="fromColor">開始色(RGB)</param>
/// <param name="toColor">終了色(RGB)</param>
/// <param name="orientation">方向</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool DrawGradationBox(Rectangle rect, RGB fromColor, RGB toColor, Orientation orientation)
=> DrawGradationBox(rect.X, rect.Y, rect.Width, rect.Height, fromColor, toColor, orientation);
#endregion
#region - DrawGradationBox : グラデーション背景の矩形を描く
/// <summary>
/// グラデーション背景の矩形を描く
/// </summary>
/// <param name="pt">座標</param>
/// <param name="size">サイズ</param>
/// <param name="fromColor">開始色(RGB)</param>
/// <param name="toColor">終了色(RGB)</param>
/// <param name="orientation">方向</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool DrawGradationBox(Point pt, RectangleSize size, RGB fromColor, RGB toColor, Orientation orientation)
=> DrawGradationBox(pt.X, pt.Y, size.Width, size.Height, fromColor, toColor, orientation);
#endregion
#region - DrawGradationBox : グラデーション背景の矩形を描く
/// <summary>
/// グラデーション背景の矩形を描く
/// </summary>
/// <param name="leftTop">左上座標</param>
/// <param name="rightBottom">右下座標</param>
/// <param name="fromColor">開始色(RGB)</param>
/// <param name="toColor">終了色(RGB)</param>
/// <param name="orientation">方向</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool DrawGradationBox(Point leftTop, Point rightBottom, RGB fromColor, RGB toColor, Orientation orientation)
=> DrawGradationBox(new Rectangle(leftTop, rightBottom), fromColor, toColor, orientation);
#endregion
#endregion
#region ☆ 文字描画関係関数
#region - DrawString : 文字列を描画する
/// <summary>
/// 文字列を描画する
/// </summary>
/// <param name="x">X座標(px)</param>
/// <param name="y">Y座標(px)</param>
/// <param name="s">描画文字列</param>
/// <param name="color">色</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool DrawString(float x, float y, string s, uint color)
{
var _x = (_drawingWindow?.X ?? 0f) + x;
var _y = (_drawingWindow?.Y ?? 0f) + y;
return DX.DrawString(Convert.ToInt32(Math.Floor(_x)), Convert.ToInt32(Math.Floor(_y)), s, color) == 0;
}
#endregion
#region - DrawString : 文字列を描画する
/// <summary>
/// 文字列を描画する
/// </summary>
/// <param name="pt">座標</param>
/// <param name="s">描画文字列</param>
/// <param name="color">色</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool DrawString(Point pt, string s, uint color)
=> DrawString(pt.X, pt.Y, s, color);
#endregion
#region - DrawString : 文字列を描画する
/// <summary>
/// 文字列を描画する
/// </summary>
/// <param name="x">X座標(px)</param>
/// <param name="y">Y座標(px)</param>
/// <param name="s">描画文字列</param>
/// <param name="color">色</param>
/// <param name="font">フォントハンドル</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool DrawString(float x, float y, string s, uint color, int font)
{
var _x = (_drawingWindow?.X ?? 0f) + x;
var _y = (_drawingWindow?.Y ?? 0f) + y;
return DX.DrawStringToHandle(Convert.ToInt32(Math.Floor(_x)), Convert.ToInt32(Math.Floor(_y)), s, color, font) == 0;
}
#endregion
#region - DrawString : 文字列を描画する
/// <summary>
/// 文字列を描画する
/// </summary>
/// <param name="pt">座標</param>
/// <param name="s">描画文字列</param>
/// <param name="color">色</param>
/// <param name="font">フォントハンドル</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool DrawString(Point pt, string s, uint color, int font)
=> DrawString(pt.X, pt.Y, s, color, font);
#endregion
#region - DrawString : 文字列を描画する
/// <summary>
/// 文字列を描画する
/// </summary>
/// <param name="x">X座標(px)</param>
/// <param name="y">Y座標(px)</param>
/// <param name="width">幅</param>
/// <param name="textAlign">テキストアラインメント</param>
/// <param name="s">描画文字列</param>
/// <param name="color">色</param>
/// <param name="font">フォントハンドル</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool DrawString(float x, float y, float width, HAlignment textAlign, string s, uint color, int font)
{
var stringWidth = GetDrawStringWidth(s, font);
var offset = 0f;
if (textAlign == HAlignment.Center)
offset = (width - stringWidth) / 2f;
else if (textAlign == HAlignment.Right)
offset = (width - stringWidth);
return DrawString(x + offset, y, s, color, font);
}
#endregion
#region - DrawString : 文字列を描画する
/// <summary>
/// 文字列を描画する
/// </summary>
/// <param name="rect">描画領域(px)</param>
/// <param name="hAlign">水平アライメント</param>
/// <param name="vAlign">垂直アライメント</param>
/// <param name="s">描画文字列</param>
/// <param name="color">色</param>
/// <param name="font">フォントハンドル</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool DrawString(Rectangle rect, HAlignment hAlign, VAlignment vAlign, string s, uint color, int font)
{
var size = GetDrawStringSize(s, font);
var hOffset = 0f;
if (hAlign == HAlignment.Center)
hOffset = (rect.Width - size.Width) / 2f;
else if (hAlign == HAlignment.Right)
hOffset = (rect.Width - size.Width);
var vOffset = 0f;
if (vAlign == VAlignment.Middle)
vOffset = (rect.Height - size.Height) / 2f;
else if (vAlign == VAlignment.Bottom)
vOffset = (rect.Height - size.Height);
return DrawString(rect.X + hOffset, rect.Y + vOffset, s, color, font);
}
#endregion
#region - GetDrawStringWidth 文字列を描画したさいの幅を取得する
/// <summary>
/// 文字列を描画したさいの幅を取得する
/// </summary>
/// <param name="s">文字列</param>
/// <param name="font">フォントハンドル</param>
/// <returns>描画幅(px)</returns>
public static int GetDrawStringWidth(string s, int font = 0)
{
var byteLength = Encoding.GetEncoding("shift_jis").GetByteCount(s);
if (font != 0)
return DX.GetDrawStringWidthToHandle(s, byteLength, font);
else
return DX.GetDrawStringWidth(s, byteLength);
}
#endregion
#region - GetDrawStringSize : 文字列を描画したさいのサイズを取得する
/// <summary>
/// 文字列を描画したさいのサイズを取得する
/// </summary>
/// <param name="s">文字列</param>
/// <param name="font">フォントハンドル</param>
/// <returns>描画サイズ</returns>
public static StringSize GetDrawStringSize(string s, int font = 0)
{
int width, height, lineCount;
var byteLength = Encoding.GetEncoding("shift_jis").GetByteCount(s);
if (font != 0)
DX.GetDrawStringSizeToHandle(out width, out height, out lineCount, s, byteLength, font);
else
DX.GetDrawStringSize(out width, out height, out lineCount, s, byteLength);
return new StringSize { Width = width, Height = height, LineCount = lineCount };
}
#endregion
#region - DrawStringVertical : 文字列を縦書きで表示する
/// <summary>
/// 文字列を縦書きで表示する
/// </summary>
/// <param name="x">X座標(px) 文字の中央/param>
/// <param name="y">Y座標(px)</param>
/// <param name="s">描画文字列</param>
/// <param name="color">色</param>
/// <param name="font">フォントハンドル</param>
public static bool DrawStringVertical(float x, float y, string s, uint color, int font = 0)
{
var _x = (_drawingWindow?.X ?? 0f) + x;
var _y = (_drawingWindow?.Y ?? 0f) + y;
if (font == 0)
return DX.DrawVString(Convert.ToInt32(Math.Floor(_x)), Convert.ToInt32(Math.Floor(_y)), s, color) == 0;
else
return DX.DrawVStringToHandle(Convert.ToInt32(Math.Floor(_x)), Convert.ToInt32(Math.Floor(_y)), s, color, font) == 0;
}
#endregion
#region - DrawStringVertical : 文字列を縦書きで表示する
/// <summary>
/// 文字列を縦書きで表示する
/// </summary>
/// <param name="pt">座標</param>
/// <param name="s">描画文字列</param>
/// <param name="color">色</param>
/// <param name="font">フォントハンドル</param>
public static bool DrawStringVertical(Point pt, string s, uint color, int font = 0)
=> DrawStringVertical(pt.X, pt.Y, s, color, font);
#endregion
#region - CreateFont : フォントを作製する
/// <summary>
/// フォントを作製する
/// </summary>
/// <param name="fontName">フォント名(null: default)</param>
/// <param name="size">サイズ(px -1:default)</param>
/// <param name="thick">太さ(0-9 -1:default)</param>
/// <param name="fontType">フォント種別</param>
/// <returns>フォントハンドル</returns>
public static int CreateFont(string fontName, int size, int thick, FontType fontType)
=> DX.CreateFontToHandle(fontName, size, thick, (int)fontType);
#endregion
#region - DeleteFont : フォントを破棄する
/// <summary>
/// フォントハンドルを破棄する
/// </summary>
/// <param name="font">フォントハンドル</param>
/// <returns>TRUE : 成功 / FALSE : 失敗</returns>
public static bool DeleteFont(int font)
=> DX.DeleteFontToHandle(font) == 0;
#endregion
#endregion
#region ☆ その他画面操作系関数
#region - SetGraphMode : 画面モードの変更
/// <summary>
/// 画面モードの変更
/// </summary>
/// <param name="screenWidth">画面幅(px)</param>
/// <param name="screenHeight">画面高さ(px)</param>
/// <param name="colorBitDepth">色深度(bit)</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool SetGraphMode(int screenWidth, int screenHeight, ColorBitDepth colorBitDepth)
=> DX.SetGraphMode(screenWidth, screenHeight, (int)colorBitDepth) == DX.DX_CHANGESCREEN_OK;
#endregion
#region - SetGraphMode : 画面モードの変更
/// <summary>
/// 画面モードの変更
/// </summary>
/// <param name="screenSize">画面サイズ</param>
/// <param name="colorBitDepth">色深度(bit)</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool SetGraphMode(RectangleSize screenSize, ColorBitDepth colorBitDepth)
=> SetGraphMode(screenSize.IWidth, screenSize.IHeight, colorBitDepth);
#endregion
#region - GetColor : 色コードを取得する
/// <summary>
/// 色コードを取得する
/// </summary>
/// <param name="red">赤</param>
/// <param name="green">緑</param>
/// <param name="blue">青</param>
/// <returns>色コード</returns>
public static uint GetColor(int red, int green, int blue)
=> DX.GetColor(red, green, blue);
#endregion
#region - GetColor : 色コードを取得する
/// <summary>
/// 色コードを取得する
/// </summary>
/// <param name="rgb">RGB構造体</param>
/// <returns>色コード</returns>
public static uint GetColor(RGB rgb)
=> DX.GetColor(rgb.Red, rgb.Green, rgb.Blue);
#endregion
#region - GetGradationColor : 中間色を取得する
/// <summary>
/// 中間色を取得する
/// </summary>
/// <param name="rgb1">色1</param>
/// <param name="rgb2">色2</param>
/// <param name="rate">率(0:色1~1:色2</param>
/// <returns>中間色</returns>
public static RGB GetGradationColor(RGB rgb1, RGB rgb2, float rate)
{
byte Round(int n) => (byte)(n < 0 ? 0 : (n > 255 ? 255 : n));
return new RGB(
Round(Convert.ToInt32((rgb2.Red - rgb1.Red) * rate) + rgb1.Red),
Round(Convert.ToInt32((rgb2.Green - rgb1.Green) * rate) + rgb1.Green),
Round(Convert.ToInt32((rgb2.Blue - rgb1.Blue) * rate) + rgb1.Blue));
}
#endregion
#region - ClearDrawScreen : 画面に描かれたものを消去する
/// <summary>
/// 画面に描かれたものを消去する
/// </summary>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool ClearDrawScreen()
=> DX.ClearDrawScreen() == 0;
#endregion
#region - ScreenFlip : 裏画面を表画面に転送する
/// <summary>
/// 裏画面を表画面に転送する
/// </summary>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool ScreenFlip()
=> DX.ScreenFlip() == 0;
#endregion
#region - SetDrawScreen : 描画先グラフィック領域の指定
/// <summary>
/// 描画先グラフィック領域の指定
/// </summary>
/// <param name="screen">描画スクリーン</param>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool SetDrawScreen(DrawScreen screen)
=> DX.SetDrawScreen((int)screen) == 0;
#endregion
#region - SetDrawScreen : 描画先グラフィック領域の指定
/// <summary>
/// 描画先グラフィック領域の指定
/// </summary>
/// <param name="screenHandle">描画先グラフィックハンドル</param>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool SetDrawScreen(int screenHandle)
=> DX.SetDrawScreen(screenHandle) == 0;
#endregion
#region - SetDrawScreen : 描画先グラフィック領域の指定
/// <summary>
/// 描画先グラフィック領域の指定
/// </summary>
/// <param name="screenHandle">描画先グラフィックハンドル</param>
/// <param name="callback">コールバック</param>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool SetDrawScreen(int screenHandle, Action callback)
{
if (DX.SetDrawScreen(screenHandle) == 0)
{
try
{
callback();
return true;
}
finally
{
DX.SetDrawScreen(DX.DX_SCREEN_BACK);
}
}
return false;
}
#endregion
#endregion
#region ☆ キーボード入力関連関数
#region - GetHitKeyStateAll : キーボードのすべてのキーの押下状態を取得する
/// <summary>
/// キーボードのすべてのキーの押下状態を取得する
/// </summary>
/// <param name="keyStateBuf"></param>
/// <returns>キーの押下状態を保持したバイト配列</returns>
public static bool GetHitKeyStateAll(byte[] keyStateBuf)
=> DX.GetHitKeyStateAll(keyStateBuf) == 0;
#endregion
#region - EnableDirectInput : 直接入力を有効にする
/// <summary>
/// 直接入力を有効にする
/// </summary>
/// <param name="flag">True : 有効 / False : 無効</param>
public static void EnableDirectInput(bool flag)
=> DX.SetUseDirectInputFlag(DXBool(flag));
#endregion
#endregion
#region ☆ タッチパネル入力関連関数
#region - GetTouchInputNum : タッチされている箇所の数を取得する
/// <summary>
/// タッチされている箇所の数を取得する
/// </summary>
/// <returns>タッチされている箇所の数</returns>
public static int GetTouchInputNum()
=> DX.GetTouchInputNum();
#endregion
#region - GetTouchInput : タッチされている箇所の情報を取得する
/// <summary>
/// タッチされている箇所の情報を取得する
/// </summary>
/// <param name="inputNo">タッチされている箇所の番号</param>
/// <returns>入力情報</returns>
public static InputInfo GetTouchInput(int inputNo)
{
if (DX.GetTouchInput(inputNo, out var x, out var y, out var id, out var device) == 0)
{
return new InputInfo(DeviceType.Touch, device, id, x, y, (int)MouseInput.Left);
}
return null;
}
#endregion
#region - GetTouchInputs : すべてのタッチされている情報を取得する
/// <summary>
/// すべてのタッチされている情報を取得する
/// </summary>
/// <returns>入力情報の列挙</returns>
public static IEnumerable<InputInfo> GetTouchInputs()
=> Enumerable.Range(0, GetTouchInputNum())
.Select(n => GetTouchInput(n))
.Where(info => info != null);
#endregion
#endregion
#region ☆ マウス入力関連関数
#region - GetMousePoint : マウスカーソルの位置を取得する
/// <summary>
/// マウスカーソルの位置を取得する
/// </summary>
/// <returns>マウスカーソル座標</returns>
public static Point? GetMousePoint()
{
if (DX.GetMousePoint(out var x, out var y) == 0)
return new Point(x, y);
return null;
}
#endregion
#region - GetMouseInput : マウスの入力情報を取得する
/// <summary>
/// マウスの入力情報を取得する
/// </summary>
/// <returns>入力情報</returns>
public static InputInfo GetMouseInput()
{
var buttons = DX.GetMouseInput();
if (buttons != 0)
{
if (DX.GetMousePoint(out var x, out var y) == 0)
return new InputInfo(DeviceType.Mouse, 0, 0, x, y, buttons);
}
return null;
}
#endregion
#region - SetMouseDispFlag : マウスカーソルの表示設定フラグのセット
/// <summary>
/// マウスカーソルの表示設定フラグのセット
/// </summary>
/// <param name="isShow"></param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool SetMouseDispFlag(bool isShow)
{
_visibleMousrCursor = isShow;
return DX.SetMouseDispFlag(DXBool(isShow)) == 0;
}
#endregion
#region - ShowMouseCursor : マウスカーソルを表示する
/// <summary>
/// マウスカーソルを表示する
/// </summary>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool ShowMouseCursor() => SetMouseDispFlag(true);
#endregion
#region - HideMouseCursor : マウスカーソルを非表示にする
/// <summary>
/// マウスカーソルを非表示にする
/// </summary>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool HideMouseCursor() => SetMouseDispFlag(false);
#endregion
#region - IsMouseCursorVisible : マウスカーソルが表示されている?
/// <summary>
/// マウスカーソルが表示されている?
/// </summary>
public static bool IsMouseCursorVisible
{
get { return _visibleMousrCursor; }
}
#endregion
#endregion
#region ☆ 音利用関数
#region - PlaySound : 音声を再生する
/// <summary>
/// 音声を再生する
/// </summary>
/// <param name="handle">リソースハンドル</param>
/// <param name="playType">再生形式</param>
/// <param name="volume">音量</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool PlaySound(int handle, PlayType playType, int volume)
{
DX.ChangeNextPlayVolumeSoundMem(NormarizeVolume(volume), handle);
return DX.PlaySoundMem(handle, (int)playType, DX.TRUE) == 0;
}
#endregion
#region - PlaySound : 音声を再生する
/// <summary>
/// 音声を再生する(バックグラウンド)
/// </summary>
/// <param name="handle">リソースハンドル</param>
/// <param name="volume">音量</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool PlaySound(int handle, int volume)
=> PlaySound(handle, PlayType.Back, volume);
#endregion
#region - PlaySoundLoop : 音声をループ再生する
/// <summary>
/// 音声をループ再生する
/// </summary>
/// <param name="handle">リソースハンドル</param>
/// <param name="volume">音量</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool PlaySoundLoop(int handle, int volume)
=> PlaySound(handle, PlayType.Loop, volume);
#endregion
#region - ChangeSoundVolume : 音量を変更する
/// <summary>
/// 音量を変更する
/// </summary>
/// <param name="handle">リソースハンドル</param>
/// <param name="newVolume">音量</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool ChangeSoundVolume(int handle, int newVolume)
{
if (DX.CheckSoundMem(handle) == DX.TRUE)
return DX.ChangeVolumeSoundMem(NormarizeVolume(newVolume), handle) == 0;
return false;
}
#endregion
#region - StopSound : 音声を停止する
/// <summary>
/// 音声を停止する
/// </summary>
/// <param name="handles">リソースハンドル</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static void StopSound(params int[] handles)
{
foreach (var h in handles)
{
if (DX.CheckSoundMem(h) == DX.TRUE)
DX.StopSoundMem(h);
}
}
#endregion
#region - IsPlayingSound : 音声が再生中?
/// <summary>
/// 音声が再生中?
/// </summary>
/// <param name="handle">リソースハンドル</param>
/// <returns>Trye : 再生中 / False : 再生中でない</returns>
public static bool IsPlayingSound(int handle)
=> DX.CheckSoundMem(handle) == DX.TRUE;
#endregion
#region - LoadSound : 音声ファイルの読み込み
/// <summary>
/// 音声ファイルの読み込み
/// </summary>
/// <param name="fileName">ファイル名</param>
/// <returns>リソースハンドル</returns>
public static int LoadSound(string fileName)
=> DX.LoadSoundMem(fileName);
#endregion
#endregion
#region ☆ 時間関係の関数
#region - GetNowCount : ミリ秒単位の精度を持つカウンタの現在値を得る
/// <summary>
/// ミリ秒単位の精度を持つカウンタの現在値を得る
/// </summary>
/// <returns> Windowsが起動してから経過時間(mm秒)</returns>
public static int GetNowCount()
=> DX.GetNowCount();
#endregion
#endregion
#region ☆ 非同期読み込み関係
#region - SetUseASyncLoadFlag : 非同期読み込みを行うかどうかを設定する
/// <summary>
/// 非同期読み込みを行うかどうかを設定する
/// </summary>
/// <param name="sw">フラグ True: 非同期読み込みを行う / False : 非同期読み込みを行わない</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool SetUseASyncLoadFlag(bool sw)
=> DX.SetUseASyncLoadFlag(DXBool(sw)) == 0;
#endregion
#region - GetASyncLoadNum : 非同期読み込み中の処理の数を取得する
/// <summary>
/// 非同期読み込み中の処理の数を取得する
/// </summary>
/// <returns>非同期読み込み中の件数</returns>
public static int GetASyncLoadNum()
=> DX.GetASyncLoadNum();
#endregion
#endregion
#region ☆ アーカイブファイル関連
#region - SetDXArchiveKeyString : DXアーカイブファイルの鍵文字列を設定する
/// <summary>
/// DXアーカイブファイルの鍵文字列を設定する
/// </summary>
/// <param name="key">鍵文字列</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool SetDXArchiveKeyString(string key)
{
return DX.SetDXArchiveKeyString(key) == 0;
}
#endregion
#region - SetUseDXArchiveFlag : DXアーカイブファイルの読み込み機能を使うかどうかを設定する
/// <summary>
/// DXアーカイブファイルの読み込み機能を使うかどうかを設定する
/// </summary>
/// <param name="sw">フラグ True: 読み込み機能を使用する / False: 使用しない</param>
/// <returns>True : 成功 / False : 失敗</returns>
public static bool SetUseDXArchiveFlag(bool sw)
{
return DX.SetUseDXArchiveFlag(DXBool(sw)) == 0;
}
#endregion
#endregion
#region ☆ その他
#region F2I : Float -> Int
/// <summary>
/// Float型をInt32に変換(少数以下切り捨て)
/// </summary>
/// <param name="f">Float値</param>
/// <returns>Int32</returns>
public static int F2I(float f) => Convert.ToInt32(Math.Floor(f));
#endregion
#region - Pos : Point型の生成
/// <summary>
/// Point型の生成
/// </summary>
/// <param name="x">X座標</param>
/// <param name="y">Y座標</param>
/// <returns>Point</returns>
public static Point Pt(float x, float y)
=> new Point(x, y);
#endregion
#region - Size : RectangleSize型の生成
/// <summary>
/// RectangleSize型の生成
/// </summary>
/// <param name="width">幅</param>
/// <param name="height">高さ</param>
/// <returns>RectangleSize</returns>
public static RectangleSize Size(float width, float height)
=> new RectangleSize(width, height);
#endregion
#region - Rect : Rectangle型の生成
/// <summary>
/// Rectangle型の生成
/// </summary>
/// <param name="x">X座標</param>
/// <param name="y">Y座標</param>
/// <param name="width">幅</param>
/// <param name="heigth">高さ</param>
/// <returns>Rectangle</returns>
public static Rectangle Rect(float x, float y, float width, float heigth)
=> new Rectangle(x, y, width, heigth);
#endregion
#region - Rect : Rectangle型の生成
/// <summary>
/// Rectangle型の生成
/// </summary>
/// <param name="pt">位置</param>
/// <param name="size">サイズ</param>
/// <returns></returns>
public static Rectangle Rect(Point pt, RectangleSize size)
=> new Rectangle(pt, size);
#endregion
#region - MoveRect : 指定位置に移動させたRectanlge型を生成する
/// <summary>
/// 指定位置に移動させたRectanlge型を生成する
/// </summary>
/// <param name="r">Rectangle</param>
/// <param name="x">X軸移動距離</param>
/// <param name="y">Y軸移動距離</param>
/// <returns>Rectangle</returns>
public static Rectangle MoveRect(Rectangle r, float x, float y)
=> new Rectangle(r.X + x, r.Y + y, r.Width, r.Height);
#endregion
#region - MoveRect : 指定位置に移動させたRectanlge型を生成する
/// <summary>
/// 指定位置に移動させたRectanlge型を生成する
/// </summary>
/// <param name="r">Rectangle</param>
/// <param name="v">Vector</param>
/// <returns>Rectangle</returns>
public static Rectangle MoveRect(Rectangle r, Vector v)
=> new Rectangle(r.X + v.X, r.Y + v.Y, r.Width, r.Height);
#endregion
#region - Vec : Vector型の生成
/// <summary>
/// Vector型の生成
/// </summary>
/// <param name="x">X方向</param>
/// <param name="y">Y方向</param>
/// <returns>Vector</returns>
public static Vector Vec(float x = 0.0f, float y = 0.0f)
=> new Vector(x, y);
#endregion
#region - VecMD : 大きさと方向からVector型を生成する
/// <summary>
/// 大きさと方向からVector型を生成する
/// </summary>
/// <param name="magnitude">大きさ</param>
/// <param name="direction">方向</param>
/// <returns>Vector</returns>
public static Vector VecMD(float magnitude, float direction)
=> Vector.CreateByMagnitudeAndDirection(magnitude, direction);
#endregion
#region - Distance : 2点間の距離を算出する
/// <summary>
/// 2点間の距離を算出する
/// </summary>
/// <param name="x1">点1のX座標</param>
/// <param name="y1">点1のY座標</param>
/// <param name="x2">点2のX座標</param>
/// <param name="y2">点2のY座標</param>
/// <returns>距離</returns>
public static float Distance(float x1, float y1, float x2, float y2)
=> (float)Math.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
#endregion
#region - Distance : 2点間の距離を算出する
/// <summary>
/// 2点間の距離を算出する
/// </summary>
/// <param name="p1">点1の座標</param>
/// <param name="p2">点2の座標</param>
/// <returns>距離</returns>
public static float Distance(Point p1, Point p2)
=> Distance(p1.X, p1.Y, p2.X, p2.Y);
#endregion
#region - SaveDrawScreen : 現在描画対象になっている画面をBMP形式で保存する
/// <summary>
/// 現在描画対象になっている画面をBMP形式で保存する
/// </summary>
/// <param name="x1">保存対象の左上X座標(px)</param>
/// <param name="y1">保存対象の左上Y座標(px)</param>
/// <param name="x2">保存対象の右下X座標(px)</param>
/// <param name="y2">保存対象の右下Y座標(px)</param>
/// <param name="fileName">保存先のファイル名</param>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool SaveDrawScreen(int x1, int y1, int x2, int y2, string fileName)
=> DX.SaveDrawScreen(x1, y1, x2, y2, fileName) == 0;
#endregion
#region - SaveDrawScreen : 現在描画対象になっている画面をBMP形式で保存する
/// <summary>
/// 現在描画対象になっている画面をBMP形式で保存する
/// </summary>
/// <param name="leftTop">保存対象の左上座標</param>
/// <param name="rightBottom">保存対象の右下座標</param>
/// <param name="fileName">保存先のファイル名</param>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool SaveDrawScreen(Point leftTop, Point rightBottom, string fileName)
=> DX.SaveDrawScreen(leftTop.IX, leftTop.IY, rightBottom.IX, rightBottom.IY, fileName) == 0;
#endregion
#region - SaveDrawScreen : 現在描画対象になっている画面をBMP形式で保存する
/// <summary>
/// 現在描画対象になっている画面をBMP形式で保存する
/// </summary>
/// <param name="rect">保存対象の矩形</param>
/// <param name="fileName">保存先のファイル名</param>
/// <returns>True: 成功 / False: 失敗</returns>
public static bool SaveDrawScreen(Rectangle rect, string fileName)
=> DX.SaveDrawScreen(rect.IX, rect.IY, rect.IX2, rect.IY2, fileName) == 0;
#endregion
#region - NumberKeyCode2Int : 数字キーコードを数値に変換する
/// <summary>
/// 数字キーコードを数値に変換する
/// </summary>
/// <param name="keyCode">キーコード</param>
/// <returns>対応数値</returns>
public static int? NumberKeyCode2Int(KeyCode keyCode)
{
switch (keyCode)
{
case KeyCode.KEY_0:
case KeyCode.KEY_NUMPAD0:
return 0;
case KeyCode.KEY_1:
case KeyCode.KEY_NUMPAD1:
return 1;
case KeyCode.KEY_2:
case KeyCode.KEY_NUMPAD2:
return 2;
case KeyCode.KEY_3:
case KeyCode.KEY_NUMPAD3:
return 3;
case KeyCode.KEY_4:
case KeyCode.KEY_NUMPAD4:
return 4;
case KeyCode.KEY_5:
case KeyCode.KEY_NUMPAD5:
return 5;
case KeyCode.KEY_6:
case KeyCode.KEY_NUMPAD6:
return 6;
case KeyCode.KEY_7:
case KeyCode.KEY_NUMPAD7:
return 7;
case KeyCode.KEY_8:
case KeyCode.KEY_NUMPAD8:
return 8;
case KeyCode.KEY_9:
case KeyCode.KEY_NUMPAD9:
return 9;
default:
return null;
}
}
#endregion
#region - KeyCode2Char : KeyCodeを文字に変換する
/// <summary>
/// KeyCodeを文字に変換する
/// </summary>
/// <param name="key">KeCode</param>
/// <returns>Char</returns>
public static char KeyCode2Char(KeyCode key) => KeyCode2CharTable.Get((int)key, (char)0);
#endregion
#region - BresenhamsLine : ブレゼンハムのアルゴリズムに基づき直線を描画する
/// <summary>
/// ブレゼンハムのアルゴリズムに基づき直線を描画する
/// </summary>
/// <param name="pt1">開始点</param>
/// <param name="pt2">終了点</param>
/// <param name="callBack">コールバック</param>
public static void BresenhamsLine(Point pt1, Point pt2, Action<Point> callBack)
{
(var x, var y) = pt1.Coordinate();
(var x2, var y2) = pt2.Coordinate();
var dx = Math.Abs(x - x2);
var dy = Math.Abs(y - y2);
var sx = x < x2 ? 1 : -1;
var sy = y < y2 ? 1 : -1;
var err = dx - dy;
callBack?.Invoke(Pt(x, y));
while (x != x2 || y != y2)
{
var e2 = 2f * err;
if (e2 > -dy)
{
err -= dy;
x += sx;
}
if (e2 < dx)
{
err += dx;
y += sy;
}
callBack?.Invoke(Pt(x, y));
}
}
#endregion
#endregion
#endregion
}
#endregion
}
| 36.206866
| 153
| 0.501946
|
[
"MIT"
] |
osamu-nomura/dxw
|
dxw/Helper.cs
| 92,106
|
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Algorithms")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Algorithms")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9bd27fdb-4b19-4868-b372-17f09d4f5309")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.486486
| 85
| 0.72823
|
[
"MIT"
] |
DJJA/S3FUN-Algorithm
|
cee sharp/oefening1/Algorithms/Properties/AssemblyInfo.cs
| 1,427
|
C#
|
namespace WinsForm0718
{
partial class Form1
{
/// <summary>
/// 設計工具所需的變數。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清除任何使用中的資源。
/// </summary>
/// <param name="disposing">如果應該處置受控資源則為 true,否則為 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form 設計工具產生的程式碼
/// <summary>
/// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器修改
/// 這個方法的內容。
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.radyear = new System.Windows.Forms.RadioButton();
this.radpart = new System.Windows.Forms.RadioButton();
this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker();
this.dateTimePicker2 = new System.Windows.Forms.DateTimePicker();
this.cbxCar = new System.Windows.Forms.ComboBox();
this.cbxgasbic = new System.Windows.Forms.ComboBox();
this.btnCalculator = new System.Windows.Forms.Button();
this.btnReset = new System.Windows.Forms.Button();
this.lble = new System.Windows.Forms.Label();
this.Alldays = new System.Windows.Forms.Label();
this.cbxtruck = new System.Windows.Forms.ComboBox();
this.cbxbus = new System.Windows.Forms.ComboBox();
this.cbxcari = new System.Windows.Forms.ComboBox();
this.cbxcarb = new System.Windows.Forms.ComboBox();
this.label6 = new System.Windows.Forms.Label();
this.AllResult = new System.Windows.Forms.Label();
this.lbls = new System.Windows.Forms.Label();
this.lblResult = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("微軟正黑體", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
this.label1.Location = new System.Drawing.Point(111, 25);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(185, 20);
this.label1.TabIndex = 0;
this.label1.Text = "使用牌照稅應納稅額試算";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("微軟正黑體", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
this.label2.Location = new System.Drawing.Point(30, 70);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(41, 20);
this.label2.TabIndex = 1;
this.label2.Text = "時間";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("微軟正黑體", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
this.label3.Location = new System.Drawing.Point(30, 150);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(41, 20);
this.label3.TabIndex = 2;
this.label3.Text = "車種";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("微軟正黑體", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
this.label4.Location = new System.Drawing.Point(30, 226);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(199, 20);
this.label4.TabIndex = 3;
this.label4.Text = "汽缸總排氣量(立方公分cc) ";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Font = new System.Drawing.Font("微軟正黑體", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
this.label5.Location = new System.Drawing.Point(30, 277);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(73, 20);
this.label5.TabIndex = 4;
this.label5.Text = "試算結果";
//
// radyear
//
this.radyear.AutoSize = true;
this.radyear.Font = new System.Drawing.Font("微軟正黑體", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
this.radyear.Location = new System.Drawing.Point(104, 66);
this.radyear.Name = "radyear";
this.radyear.Size = new System.Drawing.Size(59, 24);
this.radyear.TabIndex = 5;
this.radyear.TabStop = true;
this.radyear.Text = "年度";
this.radyear.UseVisualStyleBackColor = true;
this.radyear.CheckedChanged += new System.EventHandler(this.radyear_CheckedChanged);
//
// radpart
//
this.radpart.AutoSize = true;
this.radpart.Font = new System.Drawing.Font("微軟正黑體", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
this.radpart.Location = new System.Drawing.Point(189, 66);
this.radpart.Name = "radpart";
this.radpart.Size = new System.Drawing.Size(59, 24);
this.radpart.TabIndex = 6;
this.radpart.TabStop = true;
this.radpart.Text = "區間";
this.radpart.UseVisualStyleBackColor = true;
this.radpart.CheckedChanged += new System.EventHandler(this.radpart_CheckedChanged);
//
// dateTimePicker1
//
this.dateTimePicker1.CalendarFont = new System.Drawing.Font("微軟正黑體", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
this.dateTimePicker1.Font = new System.Drawing.Font("微軟正黑體", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
this.dateTimePicker1.Location = new System.Drawing.Point(267, 66);
this.dateTimePicker1.Name = "dateTimePicker1";
this.dateTimePicker1.Size = new System.Drawing.Size(200, 25);
this.dateTimePicker1.TabIndex = 7;
//
// dateTimePicker2
//
this.dateTimePicker2.Font = new System.Drawing.Font("微軟正黑體", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
this.dateTimePicker2.Location = new System.Drawing.Point(517, 65);
this.dateTimePicker2.Name = "dateTimePicker2";
this.dateTimePicker2.Size = new System.Drawing.Size(200, 25);
this.dateTimePicker2.TabIndex = 8;
//
// cbxCar
//
this.cbxCar.Font = new System.Drawing.Font("微軟正黑體", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
this.cbxCar.FormattingEnabled = true;
this.cbxCar.Items.AddRange(new object[] {
"機車",
"貨車",
"大客車",
"自用小客車",
"營業用小客車"});
this.cbxCar.Location = new System.Drawing.Point(346, 150);
this.cbxCar.Name = "cbxCar";
this.cbxCar.Size = new System.Drawing.Size(121, 28);
this.cbxCar.TabIndex = 9;
this.cbxCar.SelectedIndexChanged += new System.EventHandler(this.cbxCar_SelectedIndexChanged);
//
// cbxgasbic
//
this.cbxgasbic.Font = new System.Drawing.Font("微軟正黑體", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
this.cbxgasbic.FormattingEnabled = true;
this.cbxgasbic.Items.AddRange(new object[] {
"150 ( 含 150 以 下 ) \t",
"151-250 \t",
"251-500 \t",
"501-600 \t",
"601-1200 \t",
"1201-1800 \t",
"1801以上 "});
this.cbxgasbic.Location = new System.Drawing.Point(270, 218);
this.cbxgasbic.Name = "cbxgasbic";
this.cbxgasbic.Size = new System.Drawing.Size(197, 28);
this.cbxgasbic.TabIndex = 10;
this.cbxgasbic.SelectedIndexChanged += new System.EventHandler(this.cbxgasbic_SelectedIndexChanged);
//
// btnCalculator
//
this.btnCalculator.Location = new System.Drawing.Point(564, 335);
this.btnCalculator.Name = "btnCalculator";
this.btnCalculator.Size = new System.Drawing.Size(103, 48);
this.btnCalculator.TabIndex = 11;
this.btnCalculator.Text = "開始計算";
this.btnCalculator.UseVisualStyleBackColor = true;
this.btnCalculator.Click += new System.EventHandler(this.btnCalculator_Click);
//
// btnReset
//
this.btnReset.Location = new System.Drawing.Point(685, 335);
this.btnReset.Name = "btnReset";
this.btnReset.Size = new System.Drawing.Size(103, 48);
this.btnReset.TabIndex = 12;
this.btnReset.Text = "重新填寫";
this.btnReset.UseVisualStyleBackColor = true;
this.btnReset.Click += new System.EventHandler(this.btnReset_Click);
//
// lble
//
this.lble.AutoSize = true;
this.lble.Location = new System.Drawing.Point(664, 103);
this.lble.Name = "lble";
this.lble.Size = new System.Drawing.Size(53, 12);
this.lble.TabIndex = 14;
this.lble.Text = "結束日期";
//
// Alldays
//
this.Alldays.AutoSize = true;
this.Alldays.Location = new System.Drawing.Point(664, 125);
this.Alldays.Name = "Alldays";
this.Alldays.Size = new System.Drawing.Size(53, 12);
this.Alldays.TabIndex = 15;
this.Alldays.Text = "總共天數";
this.Alldays.Visible = false;
//
// cbxtruck
//
this.cbxtruck.Font = new System.Drawing.Font("微軟正黑體", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
this.cbxtruck.FormattingEnabled = true;
this.cbxtruck.Items.AddRange(new object[] {
"500 以 下 \t",
"501-600 \t",
"601-1200 \t",
"1201-1800 \t",
"1801-2400 \t",
"2401-3000 \t",
"3001-3600 \t",
"3601-4200 \t",
"4201-4800 \t",
"4801-5400 \t",
"5401-6000 \t",
"6001-6600 \t",
"6601-7200 \t",
"7201-7800 \t",
"7801-8400 \t",
"8401-9000 \t",
"9001-9600 \t",
"9601-10200 \t",
"10201 以上"});
this.cbxtruck.Location = new System.Drawing.Point(270, 218);
this.cbxtruck.Name = "cbxtruck";
this.cbxtruck.Size = new System.Drawing.Size(197, 28);
this.cbxtruck.TabIndex = 19;
this.cbxtruck.Visible = false;
//
// cbxbus
//
this.cbxbus.Font = new System.Drawing.Font("微軟正黑體", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
this.cbxbus.FormattingEnabled = true;
this.cbxbus.Items.AddRange(new object[] {
"500 以 下 \t",
"501-600 \t",
"601-1200 \t",
"1201-1800 \t",
"1801-2400 \t",
"2401-3000 \t",
"3001-3600 \t",
"3601-4200 \t",
"4201-4800 \t",
"4801-5400 \t",
"5401-6000 \t",
"6001-6600 \t",
"6601-7200 \t",
"7201-7800 \t",
"7801-8400 \t",
"8401-9000 \t",
"9001-9600 \t",
"9601-10200 \t",
"10201 以上"});
this.cbxbus.Location = new System.Drawing.Point(270, 218);
this.cbxbus.Name = "cbxbus";
this.cbxbus.Size = new System.Drawing.Size(197, 28);
this.cbxbus.TabIndex = 20;
this.cbxbus.Visible = false;
//
// cbxcari
//
this.cbxcari.Font = new System.Drawing.Font("微軟正黑體", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
this.cbxcari.FormattingEnabled = true;
this.cbxcari.Items.AddRange(new object[] {
"500 以下 \t",
"501-600 \t",
"601-1200 \t",
"1201-1800 \t",
"1801-2400 \t",
"2401-3000 \t",
"3001-4200 \t",
"4201-5400 \t",
"5401-6600 \t",
"6601-7800",
"7801 以上"});
this.cbxcari.Location = new System.Drawing.Point(270, 218);
this.cbxcari.Name = "cbxcari";
this.cbxcari.Size = new System.Drawing.Size(197, 28);
this.cbxcari.TabIndex = 21;
this.cbxcari.Visible = false;
//
// cbxcarb
//
this.cbxcarb.Font = new System.Drawing.Font("微軟正黑體", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
this.cbxcarb.FormattingEnabled = true;
this.cbxcarb.Items.AddRange(new object[] {
"500 以下 \t",
"501-600 \t",
"601-1200 \t",
"1201-1800 \t",
"1801-2400 \t",
"2401-3000 \t",
"3001-4200 \t",
"4201-5400 \t",
"5401-6600 \t",
"6601-7800",
"7801 以上"});
this.cbxcarb.Location = new System.Drawing.Point(270, 218);
this.cbxcarb.Name = "cbxcarb";
this.cbxcarb.Size = new System.Drawing.Size(197, 28);
this.cbxcarb.TabIndex = 22;
this.cbxcarb.Visible = false;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Font = new System.Drawing.Font("微軟正黑體", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
this.label6.Location = new System.Drawing.Point(45, 421);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(633, 20);
this.label6.TabIndex = 23;
this.label6.Text = "本表試算之稅額僅供參考之用,不做任何證明,實際應納稅額仍應以稽徵機關核定為準。";
//
// AllResult
//
this.AllResult.AutoSize = true;
this.AllResult.Font = new System.Drawing.Font("微軟正黑體", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(136)));
this.AllResult.ForeColor = System.Drawing.SystemColors.HotTrack;
this.AllResult.Location = new System.Drawing.Point(106, 277);
this.AllResult.Name = "AllResult";
this.AllResult.Size = new System.Drawing.Size(57, 20);
this.AllResult.TabIndex = 27;
this.AllResult.Text = "含細項";
//
// lbls
//
this.lbls.AutoSize = true;
this.lbls.Location = new System.Drawing.Point(414, 103);
this.lbls.Name = "lbls";
this.lbls.Size = new System.Drawing.Size(53, 12);
this.lbls.TabIndex = 13;
this.lbls.Text = "開始日期";
//
// lblResult
//
this.lblResult.AutoSize = true;
this.lblResult.Location = new System.Drawing.Point(777, 448);
this.lblResult.Name = "lblResult";
this.lblResult.Size = new System.Drawing.Size(11, 12);
this.lblResult.TabIndex = 17;
this.lblResult.Text = "0";
this.lblResult.Visible = false;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 469);
this.Controls.Add(this.AllResult);
this.Controls.Add(this.label6);
this.Controls.Add(this.cbxcarb);
this.Controls.Add(this.cbxcari);
this.Controls.Add(this.cbxbus);
this.Controls.Add(this.cbxtruck);
this.Controls.Add(this.lblResult);
this.Controls.Add(this.Alldays);
this.Controls.Add(this.lble);
this.Controls.Add(this.lbls);
this.Controls.Add(this.btnReset);
this.Controls.Add(this.btnCalculator);
this.Controls.Add(this.cbxgasbic);
this.Controls.Add(this.cbxCar);
this.Controls.Add(this.dateTimePicker2);
this.Controls.Add(this.dateTimePicker1);
this.Controls.Add(this.radpart);
this.Controls.Add(this.radyear);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.RadioButton radyear;
private System.Windows.Forms.RadioButton radpart;
private System.Windows.Forms.DateTimePicker dateTimePicker1;
private System.Windows.Forms.DateTimePicker dateTimePicker2;
private System.Windows.Forms.ComboBox cbxCar;
private System.Windows.Forms.ComboBox cbxgasbic;
private System.Windows.Forms.Button btnCalculator;
private System.Windows.Forms.Button btnReset;
private System.Windows.Forms.Label lble;
private System.Windows.Forms.ComboBox cbxtruck;
private System.Windows.Forms.ComboBox cbxbus;
private System.Windows.Forms.ComboBox cbxcari;
private System.Windows.Forms.ComboBox cbxcarb;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label AllResult;
private System.Windows.Forms.Label lbls;
private System.Windows.Forms.Label Alldays;
private System.Windows.Forms.Label lblResult;
}
}
| 44.830626
| 172
| 0.554653
|
[
"MIT"
] |
llaannn/trygithub1
|
WinsForm homework 0718ver/WinsForm0718/Form1.Designer.cs
| 19,934
|
C#
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IEventHub.cs" company="Kephas Software SRL">
// Copyright (c) Kephas Software SRL. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
// Declares the IEventHub interface.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Interaction
{
using System;
using System.Threading;
using System.Threading.Tasks;
using Kephas.Diagnostics.Contracts;
using Kephas.Operations;
using Kephas.Reflection;
using Kephas.Services;
/// <summary>
/// Contract for the singleton application service handling in-process event publishing/subscribing.
/// </summary>
[SingletonAppServiceContract]
public interface IEventHub
{
/// <summary>
/// Publishes the event asynchronously to its subscribers.
/// </summary>
/// <param name="event">The event.</param>
/// <param name="context">The context.</param>
/// <param name="cancellationToken">Optional. The cancellation token.</param>
/// <returns>
/// An asynchronous result.
/// </returns>
Task<IOperationResult> PublishAsync(object @event, IContext context, CancellationToken cancellationToken = default);
/// <summary>
/// Subscribes to the event(s) matching the criteria.
/// </summary>
/// <param name="match">Specifies the match criteria.</param>
/// <param name="callback">The callback.</param>
/// <returns>
/// An IEventSubscription.
/// </returns>
IEventSubscription Subscribe(Func<object, bool> match, Func<object, IContext?, CancellationToken, Task> callback);
/// <summary>
/// Subscribes to the event(s) matching the provided type.
/// </summary>
/// <param name="typeMatch">Specifies the type match criteria.</param>
/// <param name="callback">The callback.</param>
/// <returns>
/// An IEventSubscription.
/// </returns>
IEventSubscription Subscribe(Type typeMatch, Func<object, IContext?, CancellationToken, Task> callback);
}
/// <summary>
/// Extensions for <see cref="IEventHub"/>.
/// </summary>
public static class EventHubExtensions
{
/// <summary>
/// Subscribes to the event(s) matching the provided type.
/// </summary>
/// <typeparam name="TEvent">Type of the event.</typeparam>
/// <param name="eventHub">The event hub to act on.</param>
/// <param name="callback">The callback.</param>
/// <returns>
/// An IEventSubscription.
/// </returns>
public static IEventSubscription Subscribe<TEvent>(this IEventHub eventHub, Func<TEvent, IContext?, CancellationToken, Task> callback)
where TEvent : class
{
Requires.NotNull(eventHub, nameof(eventHub));
Requires.NotNull(callback, nameof(callback));
return eventHub.Subscribe(typeof(TEvent), (e, ctx, token) => callback((TEvent)e, ctx, token));
}
/// <summary>
/// Subscribes to the event(s) matching the provided type.
/// </summary>
/// <typeparam name="TEvent">Type of the event.</typeparam>
/// <typeparam name="TResult">The type of the result returned by the event handler.</typeparam>
/// <param name="eventHub">The event hub to act on.</param>
/// <param name="callback">The callback.</param>
/// <returns>
/// An IEventSubscription.
/// </returns>
public static IEventSubscription Subscribe<TEvent, TResult>(this IEventHub eventHub, Func<TEvent, IContext?, CancellationToken, Task<TResult>> callback)
where TEvent : class
{
Requires.NotNull(eventHub, nameof(eventHub));
Requires.NotNull(callback, nameof(callback));
return eventHub.Subscribe(typeof(TEvent), (e, ctx, token) => callback((TEvent)e, ctx, token));
}
/// <summary>
/// Subscribes to the event(s) matching the provided type.
/// </summary>
/// <typeparam name="TEvent">Type of the event.</typeparam>
/// <param name="eventHub">The event hub to act on.</param>
/// <param name="callback">The callback.</param>
/// <returns>
/// An IEventSubscription.
/// </returns>
public static IEventSubscription Subscribe<TEvent>(this IEventHub eventHub, Action<TEvent, IContext?> callback)
where TEvent : class
{
Requires.NotNull(eventHub, nameof(eventHub));
Requires.NotNull(callback, nameof(callback));
return eventHub.Subscribe(
typeof(TEvent),
(e, ctx, token) =>
{
callback((TEvent)e, ctx);
return Task.CompletedTask;
});
}
/// <summary>
/// Subscribes to the event(s) matching the provided type.
/// </summary>
/// <typeparam name="TEvent">Type of the event.</typeparam>
/// <typeparam name="TResult">The type of the result returned by the event handler.</typeparam>
/// <param name="eventHub">The event hub to act on.</param>
/// <param name="callback">The callback.</param>
/// <returns>
/// An IEventSubscription.
/// </returns>
public static IEventSubscription Subscribe<TEvent, TResult>(this IEventHub eventHub, Func<TEvent, IContext?, TResult> callback)
where TEvent : class
{
Requires.NotNull(eventHub, nameof(eventHub));
Requires.NotNull(callback, nameof(callback));
return eventHub.Subscribe(
typeof(TEvent),
(e, ctx, token) =>
{
var result = callback((TEvent)e, ctx);
return Task.FromResult(result);
});
}
}
}
| 41.164474
| 160
| 0.566885
|
[
"MIT"
] |
snakefoot/kephas
|
src/Kephas.Core/Interaction/IEventHub.cs
| 6,259
|
C#
|
namespace Nutanix.Powershell.Models
{
using static Microsoft.Rest.ClientRuntime.Extensions;
/// <summary>The status for a resource domain (limits and values)</summary>
public partial class ResourceDomainResourcesStatus
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Carbon.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Carbon.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Carbon.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Carbon.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Carbon.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Carbon.Json.JsonNode"/> into an instance of Nutanix.Powershell.Models.IResourceDomainResourcesStatus.
/// </summary>
/// <param name="node">a <see cref="Carbon.Json.JsonNode" /> to deserialize from.</param>
/// <returns>an instance of Nutanix.Powershell.Models.IResourceDomainResourcesStatus.</returns>
public static Nutanix.Powershell.Models.IResourceDomainResourcesStatus FromJson(Carbon.Json.JsonNode node)
{
return node is Carbon.Json.JsonObject json ? new ResourceDomainResourcesStatus(json) : null;
}
/// <summary>
/// Deserializes a Carbon.Json.JsonObject into a new instance of <see cref="ResourceDomainResourcesStatus" />.
/// </summary>
/// <param name="json">A Carbon.Json.JsonObject instance to deserialize from.</param>
internal ResourceDomainResourcesStatus(Carbon.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
_resources = If( json?.PropertyT<Carbon.Json.JsonArray>("resources"), out var __jsonResources) ? If( __jsonResources, out var __w) ? new System.Func<Nutanix.Powershell.Models.IResourceUtilizationStatus[]>(()=> System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Select( __w, (__v)=> Nutanix.Powershell.Models.ResourceUtilizationStatus.FromJson(__v) ) ) )() : null : Resources;
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="ResourceDomainResourcesStatus" /> into a <see cref="Carbon.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Carbon.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Rest.ClientRuntime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="ResourceDomainResourcesStatus" /> as a <see cref="Carbon.Json.JsonNode" />.
/// </returns>
public Carbon.Json.JsonNode ToJson(Carbon.Json.JsonObject container, Microsoft.Rest.ClientRuntime.SerializationMode serializationMode)
{
container = container ?? new Carbon.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
if (null != Resources)
{
var __x = new Carbon.Json.XNodeArray();
foreach( var __y in Resources )
{
AddIf(__y?.ToJson(null) ,__x.Add);
}
container.Add("resources",__x);
}
AfterToJson(ref container);
return container;
}
}
}
| 61.166667
| 391
| 0.650204
|
[
"MIT"
] |
gmlp/PowerShell
|
private/api/Nutanix/Powershell/Models/ResourceDomainResourcesStatus.json.cs
| 5,872
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BookSpade.Revamped.Utilities
{
public enum ActionBy
{
Seller = 0,
Buyer = 1
}
public enum BookCondition
{
Salvageable = 1,
Poor = 2,
Decent = 3,
Good = 4,
Excellent = 5
}
public enum Confirmed
{
ByNone = 0,
ByBuyer = 1,
BySeller = 2,
ByBoth = 3
}
public sealed class EnumsUtility
{
}
}
| 16.029412
| 38
| 0.506422
|
[
"MIT"
] |
hw3jung/Chanel
|
BookSpade/BookSpade.Revamped/Utilities/EnumsUtility.cs
| 547
|
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("05. PizzaCalories")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("05. PizzaCalories")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4a53698c-fc9d-4563-a7b2-da7f469523c5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.027027
| 84
| 0.744136
|
[
"MIT"
] |
nikolaydechev/CSharp-OOP-Basics
|
02 Encapsulation/05. PizzaCalories/Properties/AssemblyInfo.cs
| 1,410
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AElf.Cryptography.SecretSharing;
using AElf.Kernel;
using Google.Protobuf;
namespace AElf.Contracts.Consensus.DPoS
{
public partial class ConsensusContract
{
public override DPoSHeaderInformation GetInformationToUpdateConsensus(DPoSTriggerInformation input)
{
// Some basic checks.
Assert(input.PublicKey.Any(), "Invalid public key.");
var publicKey = input.PublicKey;
var currentBlockTime = Context.CurrentBlockTime;
var behaviour = input.Behaviour;
Assert(TryToGetCurrentRoundInformation(out var currentRound),
ContractErrorCode.GetErrorMessage(ContractErrorCode.AttemptFailed,
"Failed to get current round information."));
switch (behaviour)
{
case DPoSBehaviour.UpdateValueWithoutPreviousInValue:
case DPoSBehaviour.UpdateValue:
Assert(input.RandomHash != null, "Random hash should not be null.");
var inValue = currentRound.CalculateInValue(input.RandomHash);
var outValue = Hash.FromMessage(inValue);
var signature = Hash.FromTwoHashes(outValue, input.RandomHash); // Just initial signature value.
var previousInValue = Hash.Empty; // Just initial previous in value.
if (TryToGetPreviousRoundInformation(out var previousRound) && !IsJustChangedTerm(out _))
{
signature = previousRound.CalculateSignature(inValue);
LogVerbose($"Previous random hash: {input.PreviousRandomHash.ToHex()}");
if (input.PreviousRandomHash != Hash.Empty)
{
// If PreviousRandomHash is Hash.Empty, it means the sender unable or unwilling to publish his previous in value.
previousInValue = previousRound.CalculateInValue(input.PreviousRandomHash);
}
}
var updatedRound = currentRound.ApplyNormalConsensusData(publicKey.ToHex(), previousInValue,
outValue, signature, currentBlockTime);
ShareAndRecoverInValue(updatedRound, previousRound, inValue, publicKey.ToHex());
// To publish Out Value.
return new DPoSHeaderInformation
{
SenderPublicKey = publicKey,
Round = updatedRound,
Behaviour = behaviour,
};
case DPoSBehaviour.NextRound:
Assert(
GenerateNextRoundInformation(currentRound, currentBlockTime, out var nextRound),
"Failed to generate next round information.");
nextRound.RealTimeMinersInformation[publicKey.ToHex()].ProducedBlocks += 1;
Context.LogDebug(() => $"Mined blocks: {nextRound.GetMinedBlocks()}");
nextRound.ExtraBlockProducerOfPreviousRound = publicKey.ToHex();
return new DPoSHeaderInformation
{
SenderPublicKey = publicKey,
Round = nextRound,
Behaviour = behaviour
};
case DPoSBehaviour.NextTerm:
var firstRoundOfNextTerm = GenerateFirstRoundOfNextTerm(publicKey.ToHex());
Assert(firstRoundOfNextTerm.RoundId != 0, "Failed to generate new round information.");
var information = new DPoSHeaderInformation
{
SenderPublicKey = publicKey,
Round = firstRoundOfNextTerm,
Behaviour = behaviour
};
return information;
default:
return new DPoSHeaderInformation();
}
}
private void ShareAndRecoverInValue(Round round, Round previousRound, Hash inValue, string publicKey)
{
var minersCount = round.RealTimeMinersInformation.Count;
var minimumCount = (int) (minersCount * 2d / 3);
minimumCount = minimumCount == 0 ? 1 : minimumCount;
var secretShares = SecretSharingHelper.EncodeSecret(inValue.ToHex(), minimumCount, minersCount);
foreach (var pair in round.RealTimeMinersInformation.OrderBy(m => m.Value.Order))
{
var currentPublicKey = pair.Key;
if (!round.RealTimeMinersInformation.ContainsKey(publicKey))
{
return;
}
if (currentPublicKey == publicKey)
{
continue;
}
// Encrypt every secret share with other miner's public key, then fill own EncryptedInValues field.
var plainMessage = Encoding.UTF8.GetBytes(secretShares[pair.Value.Order - 1]);
var receiverPublicKey = ByteArrayHelpers.FromHexString(currentPublicKey);
var encryptedInValue = Context.EncryptMessage(receiverPublicKey, plainMessage);
round.RealTimeMinersInformation[publicKey].EncryptedInValues
.Add(currentPublicKey, ByteString.CopyFrom(encryptedInValue));
if (previousRound.RoundId == 0 || round.TermNumber != previousRound.TermNumber)
{
continue;
}
if (!previousRound.RealTimeMinersInformation.ContainsKey(currentPublicKey))
{
continue;
}
var encryptedInValues = previousRound.RealTimeMinersInformation[currentPublicKey].EncryptedInValues;
if (encryptedInValues.Any())
{
var interestingMessage = encryptedInValues[publicKey];
var senderPublicKey = ByteArrayHelpers.FromHexString(currentPublicKey);
// Decrypt every miner's secret share then add a result to other miner's DecryptedInValues field.
var decryptedInValue = Context.DecryptMessage(senderPublicKey, interestingMessage.ToByteArray());
round.RealTimeMinersInformation[pair.Key].DecryptedPreviousInValues
.Add(publicKey, ByteString.CopyFrom(decryptedInValue));
}
if (pair.Value.DecryptedPreviousInValues.Count < minimumCount)
{
continue;
}
Context.LogDebug(() => "Now it's enough to recover previous in values.");
// Try to recover others' previous in value.
var orders = pair.Value.DecryptedPreviousInValues.Select((t, i) =>
previousRound.RealTimeMinersInformation.Values
.First(m => m.PublicKey == pair.Value.DecryptedPreviousInValues.Keys.ToList()[i]).Order)
.ToList();
var previousInValue = Hash.LoadHex(SecretSharingHelper.DecodeSecret(
pair.Value.DecryptedPreviousInValues.Values.ToList()
.Select(s => Encoding.UTF8.GetString(s.ToByteArray())).ToList(),
orders, minimumCount));
if (round.RealTimeMinersInformation[pair.Key].PreviousInValue != null &&
round.RealTimeMinersInformation[pair.Key].PreviousInValue != previousInValue)
{
Context.LogDebug(() => $"Different previous in value: {pair.Key}");
}
round.RealTimeMinersInformation[pair.Key].PreviousInValue = previousInValue;
}
}
private bool GenerateNextRoundInformation(Round currentRound, DateTime blockTime, out Round nextRound)
{
TryToGetBlockchainStartTimestamp(out var blockchainStartTimestamp);
if (TryToGetPreviousRoundInformation(out var previousRound))
{
var evilMinersPublicKey = GetEvilMinersPublicKey(currentRound, previousRound);
var evilMinersCount = evilMinersPublicKey.Count;
if (evilMinersCount != 0)
{
foreach (var publicKeyToRemove in evilMinersPublicKey)
{
var theOneFeelingLucky = GetNextAvailableMinerPublicKey(currentRound);
if (theOneFeelingLucky == null)
{
break;
}
// Update history information of evil node.
var history = State.HistoryMap[publicKeyToRemove.ToStringValue()];
history.ProducedBlocks +=
currentRound.RealTimeMinersInformation[publicKeyToRemove].ProducedBlocks;
history.MissedTimeSlots +=
currentRound.RealTimeMinersInformation[publicKeyToRemove].MissedTimeSlots;
history.IsEvilNode = true;
State.HistoryMap[publicKeyToRemove.ToStringValue()] = history;
// Transfer evil node's consensus information to the chosen backup.
var minerInRound = currentRound.RealTimeMinersInformation[publicKeyToRemove];
minerInRound.PublicKey = theOneFeelingLucky;
minerInRound.ProducedBlocks = 0;
minerInRound.MissedTimeSlots = 0;
currentRound.RealTimeMinersInformation[theOneFeelingLucky] = minerInRound;
currentRound.RealTimeMinersInformation.Remove(publicKeyToRemove);
}
}
}
var result = currentRound.GenerateNextRoundInformation(blockTime, blockchainStartTimestamp, out nextRound);
return result;
}
private List<string> GetEvilMinersPublicKey(Round currentRound, Round previousRound)
{
return (from minerInCurrentRound in currentRound.RealTimeMinersInformation.Values
where previousRound.RealTimeMinersInformation.ContainsKey(minerInCurrentRound.PublicKey) && minerInCurrentRound.PreviousInValue != null
let previousOutValue = previousRound.RealTimeMinersInformation[minerInCurrentRound.PublicKey].OutValue
where previousOutValue != null && Hash.FromMessage(minerInCurrentRound.PreviousInValue) != previousOutValue
select minerInCurrentRound.PublicKey).ToList();
}
private string GetNextAvailableMinerPublicKey(Round round)
{
string nextCandidate = null;
TryToGetRoundInformation(1, out var firstRound);
// Check out election snapshot.
if (TryToGetTermNumber(out var termNumber) && termNumber > 1 &&
TryToGetSnapshot(termNumber - 1, out var snapshot))
{
nextCandidate = snapshot.CandidatesSnapshot
// Except initial miners.
.Where(cs => !firstRound.RealTimeMinersInformation.ContainsKey(cs.PublicKey))
// Except current miners.
.Where(cs => !round.RealTimeMinersInformation.ContainsKey(cs.PublicKey))
.OrderByDescending(s => s.Votes)
.FirstOrDefault(c => !round.RealTimeMinersInformation.ContainsKey(c.PublicKey))?.PublicKey;
}
// Check out initial miners.
return nextCandidate ?? firstRound.RealTimeMinersInformation.Keys.FirstOrDefault(k =>
!round.RealTimeMinersInformation.ContainsKey(k));
}
public override TransactionList GenerateConsensusTransactions(DPoSTriggerInformation input)
{
// Some basic checks.
Assert(input.PublicKey.Any(), "Data to request consensus information should contain public key.");
var publicKey = input.PublicKey;
var consensusInformation = GetInformationToUpdateConsensus(input);
var round = consensusInformation.Round;
var behaviour = consensusInformation.Behaviour;
switch (behaviour)
{
case DPoSBehaviour.UpdateValueWithoutPreviousInValue:
case DPoSBehaviour.UpdateValue:
return new TransactionList
{
Transactions =
{
GenerateTransaction(nameof(UpdateValue),
round.ExtractInformationToUpdateConsensus(publicKey.ToHex()), input.PublicKey)
}
};
case DPoSBehaviour.NextRound:
return new TransactionList
{
Transactions =
{
GenerateTransaction(nameof(NextRound), round, input.PublicKey)
}
};
case DPoSBehaviour.NextTerm:
return new TransactionList
{
Transactions =
{
GenerateTransaction(nameof(NextTerm), round, input.PublicKey)
}
};
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
| 48.989324
| 151
| 0.566686
|
[
"MIT"
] |
quangdo3112/AElf
|
src/AElf.Contracts.Consensus.DPoS/ConsensusContract/UpdateConsensus.cs
| 13,766
|
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DBCreator")]
[assembly: AssemblyDescription("IIS (Independent Investigation Software) Suite.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ddisthatoneguyyouknow")]
[assembly: AssemblyProduct("DBCreator")]
[assembly: AssemblyCopyright("MIT")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7c4718c3-525e-4924-8da7-a53689d80d0b")]
// 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("5.1.2.1")]
[assembly: AssemblyFileVersion("5.1.2.1")]
| 38.891892
| 84
| 0.753996
|
[
"MIT"
] |
Independent-Investigation-Software/DBCreator
|
DBCreator/DBCreator/Properties/AssemblyInfo.cs
| 1,441
|
C#
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Andrew B. Johnson
*
* 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.Threading.Tasks;
namespace DataSwallow.Stream
{
/// <summary>
/// Represents an message sink
/// </summary>
/// <typeparam name="TPayload">The type of the payload.</typeparam>
public interface IOutputMessageSink<TPayload>
{
/// <summary>
/// Accepts the specified message asynchronously.
/// </summary>
/// <param name="message">The message.</param>
/// <returns>A Task representing the accepting of the message</returns>
void Accept(IOutputStreamMessage<TPayload> message);
}
}
| 41.093023
| 81
| 0.697793
|
[
"MIT"
] |
helios2k6/Data-Swallow
|
Data Swallow/Stream/IOutputMessageSink.cs
| 1,769
|
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.Linq;
using Newtonsoft.Json.Linq;
using NuGet.Frameworks;
using Xunit;
namespace NuGet.ProjectModel.Test
{
public class PackagesLockFileFormatTests
{
[Fact]
public void PackagesLockFileFormat_Read()
{
var nuGetLockFileContent = @"{
""version"": 1,
""dependencies"": {
"".NETFramework,Version=v4.5"": {
""PackageA"": {
""type"": ""Direct"",
""requested"": ""[1.*, )"",
""resolved"": ""1.0.0"",
""contentHash"": ""sbWWhjA2/cXJHBBKAVo3m2U0KxzNuW5dQANDwx8L96V+L6SML96cM/Myvmp6fiBqIDibvF6+Ss9YC+qqclrXnw=="",
""dependencies"": {
""PackageB"": ""1.0.0""
}
},
""PackageB"": {
""type"": ""Transitive"",
""resolved"": ""1.0.0"",
""contentHash"": ""Fjiywrwerewr4dgbdgbfgjkoiuiorwrwn24+8hjnnuerwrwsfsHYWD3HJYUI7NJHssxDFSFSFEWEW34DFDFCVsxv=="",
}
}
}
}";
var lockFile = PackagesLockFileFormat.Parse(nuGetLockFileContent, "In Memory");
Assert.Equal(1, lockFile.Targets.Count);
var target = lockFile.Targets.First();
Assert.Equal(".NETFramework,Version=v4.5", target.Name);
Assert.Equal(2, target.Dependencies.Count);
Assert.Equal("PackageA", target.Dependencies[0].Id);
Assert.Equal(PackageDependencyType.Direct, target.Dependencies[0].Type);
Assert.Equal("[1.*, )", target.Dependencies[0].RequestedVersion.ToNormalizedString());
Assert.Equal("1.0.0", target.Dependencies[0].ResolvedVersion.ToNormalizedString());
Assert.NotEmpty(target.Dependencies[0].ContentHash);
Assert.Equal(1, target.Dependencies[0].Dependencies.Count);
Assert.Equal("PackageB", target.Dependencies[0].Dependencies[0].Id);
Assert.Equal("PackageB", target.Dependencies[1].Id);
Assert.Equal(PackageDependencyType.Transitive, target.Dependencies[1].Type);
Assert.Null(target.Dependencies[1].RequestedVersion);
Assert.Equal("1.0.0", target.Dependencies[0].ResolvedVersion.ToNormalizedString());
Assert.NotEmpty(target.Dependencies[1].ContentHash);
}
[Fact]
public void Read_VariousTargetFrameworksAndRuntimeIdentifiers_ParsedCorrectly()
{
// Arrange
var lockFileContents =
@"{
""version"": 1,
""dependencies"": {
"".NETFramework,Version=v4.7.2"": { },
"".NETStandard,Version=v2.0"": { },
"".NETCoreApp,Version=3.1"": { },
"".NETCoreApp,Version=3.1/win-x64"": { },
"".NETCoreApp,Version=5.0"": { },
"".NETCoreApp,Version=5.0/win-x64"": { },
""net5.0-windows7.0"": { },
""net5.0-windows7.0/win-x64"": { },
""net6.0"": { },
""net6.0/win-x64"": { },
""net6.0-windows7.0"": { },
""net6.0-windows7.0/win-x64"": { },
}
}";
// Act
var lockFile = PackagesLockFileFormat.Parse(lockFileContents, "In memory");
// Assert
Assert.Equal(12, lockFile.Targets.Count);
Assert.Equal(FrameworkConstants.CommonFrameworks.Net472, lockFile.Targets[0].TargetFramework);
Assert.Null(lockFile.Targets[0].RuntimeIdentifier);
Assert.Equal(FrameworkConstants.CommonFrameworks.NetStandard20, lockFile.Targets[1].TargetFramework);
Assert.Null(lockFile.Targets[1].RuntimeIdentifier);
Assert.Equal(FrameworkConstants.CommonFrameworks.NetCoreApp31, lockFile.Targets[2].TargetFramework);
Assert.Null(lockFile.Targets[2].RuntimeIdentifier);
Assert.Equal(FrameworkConstants.CommonFrameworks.NetCoreApp31, lockFile.Targets[3].TargetFramework);
Assert.Equal("win-x64", lockFile.Targets[3].RuntimeIdentifier);
Assert.Equal(FrameworkConstants.CommonFrameworks.Net50, lockFile.Targets[4].TargetFramework);
Assert.Null(lockFile.Targets[4].RuntimeIdentifier);
Assert.Equal(FrameworkConstants.CommonFrameworks.Net50, lockFile.Targets[5].TargetFramework);
Assert.Equal("win-x64", lockFile.Targets[5].RuntimeIdentifier);
NuGetFramework net5win7 = NuGetFramework.Parse("net5.0-windows7.0");
Assert.Equal(net5win7, lockFile.Targets[6].TargetFramework);
Assert.Null(lockFile.Targets[6].RuntimeIdentifier);
Assert.Equal(net5win7, lockFile.Targets[7].TargetFramework);
Assert.Equal("win-x64", lockFile.Targets[7].RuntimeIdentifier);
Assert.Equal(FrameworkConstants.CommonFrameworks.Net60, lockFile.Targets[8].TargetFramework);
Assert.Null(lockFile.Targets[8].RuntimeIdentifier);
Assert.Equal(FrameworkConstants.CommonFrameworks.Net60, lockFile.Targets[9].TargetFramework);
Assert.Equal("win-x64", lockFile.Targets[9].RuntimeIdentifier);
NuGetFramework net6win7 = NuGetFramework.Parse("net6.0-windows7.0");
Assert.Equal(net6win7, lockFile.Targets[10].TargetFramework);
Assert.Null(lockFile.Targets[10].RuntimeIdentifier);
Assert.Equal(net6win7, lockFile.Targets[11].TargetFramework);
Assert.Equal("win-x64", lockFile.Targets[11].RuntimeIdentifier);
}
[Fact]
public void PackagesLockFileFormat_ReadWithRuntimeGraph()
{
var nuGetLockFileContent = @"{
""version"": 1,
""dependencies"": {
"".NETFramework,Version=v4.5"": {
""PackageA"": {
""type"": ""Direct"",
""requested"": ""[1.*, )"",
""resolved"": ""1.0.0"",
""contentHash"": ""sbWWhjA2/cXJHBBKAVo3m2U0KxzNuW5dQANDwx8L96V+L6SML96cM/Myvmp6fiBqIDibvF6+Ss9YC+qqclrXnw=="",
""dependencies"": {
""PackageB"": ""1.0.0""
}
},
""PackageB"": {
""type"": ""Transitive"",
""resolved"": ""1.0.0"",
""contentHash"": ""Fjiywrwerewr4dgbdgbfgjkoiuiorwrwn24+8hjnnuerwrwsfsHYWD3HJYUI7NJHssxDFSFSFEWEW34DFDFCVsxv==""
}
},
"".NETFramework,Version=v4.5/win10-arm"": {
""PackageA"": {
""type"": ""Direct"",
""requested"": ""[1.*, )"",
""resolved"": ""1.0.0"",
""contentHash"": ""QuiokjhjA2/cXJHBBKAVo3m2U0KxzNuW5dQANDwx8L96V+L6SML96cM/Myvmp6fiBqIDibvF6+Ss9YC+qqcfwef=="",
""dependencies"": {
""PackageB"": ""1.0.0"",
""runtime.win10-arm.PackageA"": ""1.0.0""
}
},
""runtime.win10-arm.PackageA"": {
""type"": ""Transitive"",
""resolved"": ""1.0.0"",
""contentHash"": ""dfgdgdfIY434jhjkhkRARFSZSGFSDG423452bgdnuerwrwsfsHYWD3HJYUI7NJHssxDFSFSFEWEW34DFjkyuerd=="",
}
}
}
}";
var lockFile = PackagesLockFileFormat.Parse(nuGetLockFileContent, "In Memory");
Assert.Equal(2, lockFile.Targets.Count);
var target = lockFile.Targets.First(t => !string.IsNullOrEmpty(t.RuntimeIdentifier));
Assert.Equal(".NETFramework,Version=v4.5/win10-arm", target.Name);
Assert.Equal(2, target.Dependencies.Count);
Assert.Equal("PackageA", target.Dependencies[0].Id);
Assert.Equal(PackageDependencyType.Direct, target.Dependencies[0].Type);
Assert.Equal("[1.*, )", target.Dependencies[0].RequestedVersion.ToNormalizedString());
Assert.Equal("1.0.0", target.Dependencies[0].ResolvedVersion.ToNormalizedString());
Assert.NotEmpty(target.Dependencies[0].ContentHash);
Assert.Equal(2, target.Dependencies[0].Dependencies.Count);
Assert.Equal("PackageB", target.Dependencies[0].Dependencies[0].Id);
Assert.Equal("runtime.win10-arm.PackageA", target.Dependencies[0].Dependencies[1].Id);
// Runtime graph will only have additional transitive dependenies which are not part of
// original TFM graph
Assert.Equal("runtime.win10-arm.PackageA", target.Dependencies[1].Id);
Assert.Equal(PackageDependencyType.Transitive, target.Dependencies[1].Type);
Assert.Null(target.Dependencies[1].RequestedVersion);
Assert.Equal("1.0.0", target.Dependencies[0].ResolvedVersion.ToNormalizedString());
Assert.NotEmpty(target.Dependencies[1].ContentHash);
}
[Fact]
public void PackagesLockFileFormat_Write()
{
var nuGetLockFileContent = @"{
""version"": 1,
""dependencies"": {
"".NETFramework,Version=v4.5"": {
""PackageA"": {
""type"": ""Direct"",
""requested"": ""[1.*, )"",
""resolved"": ""1.0.0"",
""contentHash"": ""sbWWhjA2/cXJHBBKAVo3m2U0KxzNuW5dQANDwx8L96V+L6SML96cM/Myvmp6fiBqIDibvF6+Ss9YC+qqclrXnw=="",
""dependencies"": {
""PackageB"": ""1.0.0""
}
},
""PackageB"": {
""type"": ""Transitive"",
""resolved"": ""1.0.0"",
""contentHash"": ""Fjiywrwerewr4dgbdgbfgjkoiuiorwrwn24+8hjnnuerwrwsfsHYWD3HJYUI7NJHssxDFSFSFEWEW34DFDFCVsxv=="",
}
}
}
}";
var lockFile = PackagesLockFileFormat.Parse(nuGetLockFileContent, "In Memory");
var output = JObject.Parse(PackagesLockFileFormat.Render(lockFile));
var expected = JObject.Parse(nuGetLockFileContent);
// Assert
Assert.Equal(expected.ToString(), output.ToString());
}
}
}
| 47.145923
| 140
| 0.537642
|
[
"Apache-2.0"
] |
AntonC9018/NuGet.Client
|
test/NuGet.Core.Tests/NuGet.ProjectModel.Test/PackagesLockFileFormatTests.cs
| 10,985
|
C#
|
using System;
using System.Collections.Generic;
class PQ<T> : List<T>
{
public static PQ<T> Create(bool desc = false)
{
var c = Comparer<T>.Default;
return desc ?
new PQ<T>((x, y) => c.Compare(y, x)) :
new PQ<T>(c.Compare);
}
public static PQ<T> Create<TKey>(Func<T, TKey> toKey, bool desc = false)
{
var c = Comparer<TKey>.Default;
return desc ?
new PQ<T>((x, y) => c.Compare(toKey(y), toKey(x))) :
new PQ<T>((x, y) => c.Compare(toKey(x), toKey(y)));
}
public static PQ<T, TKey> CreateWithKey<TKey>(Func<T, TKey> toKey, bool desc = false)
{
var c = Comparer<TKey>.Default;
return desc ?
new PQ<T, TKey>(toKey, (x, y) => c.Compare(y.Item2, x.Item2)) :
new PQ<T, TKey>(toKey, (x, y) => c.Compare(x.Item2, y.Item2));
}
Comparison<T> c;
public T First => this[0];
internal PQ(Comparison<T> _c) { c = _c; }
void Swap(int i, int j) { var o = this[i]; this[i] = this[j]; this[j] = o; }
void UpHeap(int i) { for (int j; i > 0 && c(this[j = (i - 1) / 2], this[i]) > 0; Swap(i, i = j)) ; }
void DownHeap(int i)
{
for (int j; (j = 2 * i + 1) < Count;)
{
if (j + 1 < Count && c(this[j], this[j + 1]) > 0) j++;
if (c(this[i], this[j]) > 0) Swap(i, i = j); else break;
}
}
public void Push(T v)
{
Add(v);
UpHeap(Count - 1);
}
public void PushRange(T[] vs) { foreach (var v in vs) Push(v); }
public T Pop()
{
var r = this[0];
this[0] = this[Count - 1];
RemoveAt(Count - 1);
DownHeap(0);
return r;
}
}
class PQ<T, TKey> : PQ<(T value, TKey key)>
{
Func<T, TKey> ToKey;
internal PQ(Func<T, TKey> toKey, Comparison<(T, TKey)> c) : base(c) { ToKey = toKey; }
public void Push(T v) => Push((v, ToKey(v)));
public void PushRange(T[] vs) { foreach (var v in vs) Push(v); }
}
| 25.957143
| 102
| 0.544304
|
[
"MIT"
] |
sakapon/AtCoder-Contests
|
CSharp/YJLC/YGR001/Lib/PriorityQueue.cs
| 1,819
|
C#
|
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// 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.
// Modifications Copyright 2017 David Serfozo
using System;
using System.Globalization;
namespace DSerfozo.RpcBindings.Castle.Core.Configuration
{
/// <summary>
/// This is an abstract <see cref = "IConfiguration" /> implementation
/// that deals with methods that can be abstracted away
/// from underlying implementations.
/// </summary>
/// <remarks>
/// <para><b>AbstractConfiguration</b> makes easier to implementers
/// to create a new version of <see cref = "IConfiguration" /></para>
/// </remarks>
#if FEATURE_SERIALIZATION
[Serializable]
#endif
public abstract class AbstractConfiguration : IConfiguration
{
private readonly ConfigurationAttributeCollection attributes = new ConfigurationAttributeCollection();
private readonly ConfigurationCollection children = new ConfigurationCollection();
/// <summary>
/// Gets node attributes.
/// </summary>
/// <value>
/// All attributes of the node.
/// </value>
public virtual ConfigurationAttributeCollection Attributes
{
get { return attributes; }
}
/// <summary>
/// Gets all child nodes.
/// </summary>
/// <value>The <see cref = "ConfigurationCollection" /> of child nodes.</value>
public virtual ConfigurationCollection Children
{
get { return children; }
}
/// <summary>
/// Gets the name of the <see cref = "IConfiguration" />.
/// </summary>
/// <value>
/// The Name of the <see cref = "IConfiguration" />.
/// </value>
public string Name { get; protected set; }
/// <summary>
/// Gets the value of <see cref = "IConfiguration" />.
/// </summary>
/// <value>
/// The Value of the <see cref = "IConfiguration" />.
/// </value>
public string Value { get; protected set; }
/// <summary>
/// Gets the value of the node and converts it
/// into specified <see cref = "Type" />.
/// </summary>
/// <param name = "type">The <see cref = "Type" /></param>
/// <param name = "defaultValue">
/// The Default value returned if the conversion fails.
/// </param>
/// <returns>The Value converted into the specified type.</returns>
public virtual object GetValue(Type type, object defaultValue)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
try
{
return Convert.ChangeType(Value, type, CultureInfo.CurrentCulture);
}
catch (InvalidCastException)
{
return defaultValue;
}
}
}
}
| 30.068627
| 104
| 0.671014
|
[
"Apache-2.0"
] |
rpc-bindings/core
|
src/DSerfozo.RpcBindings/DynamicProxy/Castle.Core/Configuration/AbstractConfiguration.cs
| 3,067
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>This code was generated by LLBLGen Pro v4.1.</auto-generated>
//------------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using System.Collections.Specialized;
using System.Collections.Generic;
namespace EF6.Bencher.EntityClasses
{
/// <summary>Class which represents the entity 'Culture'.</summary>
[Serializable]
[DataContract(IsReference=true)]
public partial class Culture : CommonEntityBase
{
/// <summary>Initializes a new instance of the <see cref="Culture"/> class.</summary>
public Culture() : base()
{
this.ProductModelProductDescriptionCultures = new HashSet<ProductModelProductDescriptionCulture>();
}
#region Class Property Declarations
/// <summary>Gets or sets the CultureId field. </summary>
[DataMember]
public System.String CultureId { get; set;}
/// <summary>Gets or sets the ModifiedDate field. </summary>
[DataMember]
public System.DateTime ModifiedDate { get; set;}
/// <summary>Gets or sets the Name field. </summary>
[DataMember]
public System.String Name { get; set;}
/// <summary>Represents the navigator which is mapped onto the association 'ProductModelProductDescriptionCulture.Culture - Culture.ProductModelProductDescriptionCultures (m:1)'</summary>
[DataMember]
public virtual ICollection<ProductModelProductDescriptionCulture> ProductModelProductDescriptionCultures { get; set;}
#endregion
}
}
| 40.175
| 189
| 0.690106
|
[
"MIT"
] |
FransBouma/RawDataAccessBencher
|
EF6/Model/EntityClasses/Culture.cs
| 1,609
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class RandomPicker : MonoBehaviour
{
/* Start is called before the first frame update
public List<int> BlueCard = new List<int>();
public List<int> RedCard = new List<int>();
public int BlueScore;
public int RedScore;
public int B_textSc=0;
public int R_textSc=0;
public bool isPlayingCard = false;
public bool isGM = true;
//manager = GameObject.FindGameObjectWithTag("GM");
public void Update()
{
GameObject temp = GameObject.FindGameObjectWithTag("con");
if (temp)
{
if (isGM)
{
if (!isPlayingCard && temp)
{
temp.SetActive(false);
}
}
}
}
public void cardOff()
{
GameObject temp = GameObject.FindGameObjectWithTag("GM");
temp.GetComponent<RandomPicker>().isPlayingCard = false;
}
public void Reset()
{
B_textSc = 0;
R_textSc = 0;
GameObject[] tempB = GameObject.FindGameObjectsWithTag("bs");
GameObject[] tempR = GameObject.FindGameObjectsWithTag("rs");
for (int i = 0; i < tempB.Length; i++)
{
tempB[i].GetComponent<Text>().text = B_textSc.ToString();
tempR[i].GetComponent<Text>().text = R_textSc.ToString();
}
BlueCard.Clear();
RedCard.Clear();
for (int i = 1; i <= 7; i++)
{
BlueCard.Add(i);
RedCard.Add(i);
}
}
public void BluePick(int num)
{
BlueScore = num;
int index = BlueCard.IndexOf(num);
BlueCard.RemoveAt(index);
}
public void RedPick(int num)
{
RedScore = num;
int index = RedCard.IndexOf(num);
RedCard.RemoveAt(index);
}
*/
public void MoveGame2()
{
SceneLoader.Instance.LoadScene("SoccerTwos");
}
public void MoveGame1()
{
SceneLoader.Instance.LoadScene("WalkerStatic");
}
}
| 24.202247
| 69
| 0.55896
|
[
"Apache-2.0"
] |
oereo/ML_Agents_App
|
Project/Assets/Scripts/menu_scripts/RandomPicker.cs
| 2,156
|
C#
|
using System;
using DevExpress.CodeRush.StructuralParser;
namespace CR_Documentor.Test.Transformation.Syntax.Proxies
{
public abstract class AccessSpecifiedElementProxy : LanguageElementProxy
{
public GenericModifier GenericModifier { get; private set; }
public bool IsAbstract { get; set; }
public bool IsConst { get; set; }
public bool IsGeneric
{
get
{
return this.GenericModifier != null;
}
}
public bool IsNew { get; set; }
public bool IsOverride { get; set; }
public bool IsReadOnly { get; set; }
public bool IsSealed { get; set; }
public bool IsStatic { get; set; }
public bool IsVirtual { get; set; }
public bool IsWriteOnly { get; set; }
public string Name { get; set; }
public MemberVisibility Visibility { get; set; }
protected AccessSpecifiedElementProxy()
{
this.Visibility = MemberVisibility.Public;
this.GenericModifier = null;
}
public void SetTypeParameters(TypeParameterCollection parameters)
{
if (parameters == null)
{
this.GenericModifier = null;
}
else
{
this.GenericModifier = new GenericModifier(parameters);
}
}
}
}
| 24.148936
| 73
| 0.701322
|
[
"Apache-2.0"
] |
tillig/CR_Documentor
|
CR_Documentor.Test/Transformation/Syntax/Proxies/AccessSpecifiedElementProxy.cs
| 1,137
|
C#
|
using Coldairarrow.Util;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
namespace Coldairarrow.Web.Areas.Base_SysManage.Controllers
{
[Area("Base_SysManage")]
public class CityController : BaseController
{
static CityController()
{
string jsonStr = System.IO.File.ReadAllText(PathHelper.GetAbsolutePath("~/Config/Province.json"));
_countryRegin = jsonStr.ToObject<CountryRegin>();
}
private static CountryRegin _countryRegin { get; } = null;
#region 视图功能
public ActionResult Index()
{
return View();
}
#endregion
#region 获取数据
/// <summary>
/// 获取省份列表
/// </summary>
/// <param name="q">省份名</param>
/// <returns></returns>
public ActionResult GetProvinceList(string q)
{
var predicate = LinqHelper.True<ProvinceListItem>();
if (!q.IsNullOrEmpty())
predicate = predicate.And(x => x.ProName.Contains(q));
return Content(_countryRegin.provinceList.Where(predicate.Compile()).ToJson());
}
/// <summary>
/// 获取城市列表
/// </summary>
/// <param name="q">城市名</param>
/// <param name="proId">省份Id</param>
/// <returns></returns>
public ActionResult GetCityList(string q, string proId)
{
var predicate = LinqHelper.True<CityListItem>();
if (!q.IsNullOrEmpty())
predicate = predicate.And(x => x.CityName.Contains(q));
if (!proId.IsNullOrEmpty())
predicate = predicate.And(x => x.ProID.ToString() == proId);
return Content(_countryRegin.cityList.Where(predicate.Compile()).ToJson());
}
/// <summary>
/// 获取县城列表
/// </summary>
/// <param name="q">县城名</param>
/// <param name="cityId">城市Id</param>
/// <returns></returns>
public ActionResult GetCountyList(string q, string cityId)
{
var predicate = LinqHelper.True<CountyListItem>();
if (!q.IsNullOrEmpty())
predicate = predicate.And(x => x.DisName.Contains(q));
if (!cityId.IsNullOrEmpty())
predicate = predicate.And(x => x.CityID.ToString() == cityId);
return Content(_countryRegin.countyList.Where(predicate.Compile()).ToJson());
}
#endregion
#region 提交数据
#endregion
#region 数据模型
public class ProvinceListItem
{
/// <summary>
///
/// </summary>
public int ProID { get; set; }
/// <summary>
/// 北京市
/// </summary>
public string ProName { get; set; }
/// <summary>
///
/// </summary>
public int ProSort { get; set; }
/// <summary>
/// 直辖市
/// </summary>
public string ProRemark { get; set; }
}
public class CityListItem
{
/// <summary>
///
/// </summary>
public int CityID { get; set; }
/// <summary>
/// 北京市
/// </summary>
public string CityName { get; set; }
/// <summary>
///
/// </summary>
public int ProID { get; set; }
/// <summary>
///
/// </summary>
public int CitySort { get; set; }
}
public class CountyListItem
{
/// <summary>
///
/// </summary>
public int Id { get; set; }
/// <summary>
/// 县城名
/// </summary>
public string DisName { get; set; }
/// <summary>
///
/// </summary>
public int CityID { get; set; }
/// <summary>
///
/// </summary>
public string DisSort { get; set; }
}
public class CountryRegin
{
/// <summary>
///
/// </summary>
public List<ProvinceListItem> provinceList { get; set; }
/// <summary>
///
/// </summary>
public List<CityListItem> cityList { get; set; }
/// <summary>
///
/// </summary>
public List<CountyListItem> countyList { get; set; }
}
#endregion
}
}
| 27.777108
| 110
| 0.465843
|
[
"MIT"
] |
Coldairarrow/Colder.Fx.Core.AdminLTE
|
src/Coldairarrow.Web/Areas/Base_SysManage/Controllers/CityController.cs
| 4,731
|
C#
|
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
#if STRIDE_GRAPHICS_API_DIRECT3D12
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using SharpDX.Direct3D12;
using Stride.Core.Collections;
using Stride.Core.Threading;
namespace Stride.Graphics
{
public partial class GraphicsDevice
{
// D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT (not exposed by SharpDX)
internal readonly int ConstantBufferDataPlacementAlignment = 256;
private const GraphicsPlatform GraphicPlatform = GraphicsPlatform.Direct3D12;
internal readonly ConcurrentPool<List<GraphicsResource>> StagingResourceLists = new ConcurrentPool<List<GraphicsResource>>(() => new List<GraphicsResource>());
internal readonly ConcurrentPool<List<DescriptorHeap>> DescriptorHeapLists = new ConcurrentPool<List<DescriptorHeap>>(() => new List<DescriptorHeap>());
private bool simulateReset = false;
private string rendererName;
private SharpDX.Direct3D12.Device nativeDevice;
internal CommandQueue NativeCommandQueue;
internal GraphicsProfile RequestedProfile;
internal SharpDX.Direct3D.FeatureLevel CurrentFeatureLevel;
internal CommandQueue NativeCopyCommandQueue;
internal CommandAllocator NativeCopyCommandAllocator;
internal GraphicsCommandList NativeCopyCommandList;
private Fence nativeCopyFence;
private long nextCopyFenceValue = 1;
internal CommandAllocatorPool CommandAllocators;
internal HeapPool SrvHeaps;
internal HeapPool SamplerHeaps;
internal const int SrvHeapSize = 2048;
internal const int SamplerHeapSize = 64;
internal DescriptorAllocator SamplerAllocator;
internal DescriptorAllocator ShaderResourceViewAllocator;
internal DescriptorAllocator UnorderedAccessViewAllocator => ShaderResourceViewAllocator;
internal DescriptorAllocator DepthStencilViewAllocator;
internal DescriptorAllocator RenderTargetViewAllocator;
private SharpDX.Direct3D12.Resource nativeUploadBuffer;
private IntPtr nativeUploadBufferStart;
private int nativeUploadBufferOffset;
internal int SrvHandleIncrementSize;
internal int SamplerHandleIncrementSize;
private Fence nativeFence;
private long lastCompletedFence;
internal long NextFenceValue = 1;
private AutoResetEvent fenceEvent = new AutoResetEvent(false);
// Temporary or destroyed resources kept around until the GPU doesn't need them anymore
internal Queue<KeyValuePair<long, object>> TemporaryResources = new Queue<KeyValuePair<long, object>>();
private readonly FastList<SharpDX.Direct3D12.CommandList> nativeCommandLists = new FastList<SharpDX.Direct3D12.CommandList>();
/// <summary>
/// The tick frquency of timestamp queries in Hertz.
/// </summary>
public long TimestampFrequency { get; private set; }
/// <summary>
/// Gets the status of this device.
/// </summary>
/// <value>The graphics device status.</value>
public GraphicsDeviceStatus GraphicsDeviceStatus
{
get
{
if (simulateReset)
{
simulateReset = false;
return GraphicsDeviceStatus.Reset;
}
var result = NativeDevice.DeviceRemovedReason;
if (result == SharpDX.DXGI.ResultCode.DeviceRemoved)
{
return GraphicsDeviceStatus.Removed;
}
if (result == SharpDX.DXGI.ResultCode.DeviceReset)
{
return GraphicsDeviceStatus.Reset;
}
if (result == SharpDX.DXGI.ResultCode.DeviceHung)
{
return GraphicsDeviceStatus.Hung;
}
if (result == SharpDX.DXGI.ResultCode.DriverInternalError)
{
return GraphicsDeviceStatus.InternalError;
}
if (result == SharpDX.DXGI.ResultCode.InvalidCall)
{
return GraphicsDeviceStatus.InvalidCall;
}
if (result.Code < 0)
{
return GraphicsDeviceStatus.Reset;
}
return GraphicsDeviceStatus.Normal;
}
}
/// <summary>
/// Gets the native device.
/// </summary>
/// <value>The native device.</value>
internal SharpDX.Direct3D12.Device NativeDevice
{
get
{
return nativeDevice;
}
}
/// <summary>
/// Marks context as active on the current thread.
/// </summary>
public void Begin()
{
FrameTriangleCount = 0;
FrameDrawCalls = 0;
}
/// <summary>
/// Enables profiling.
/// </summary>
/// <param name="enabledFlag">if set to <c>true</c> [enabled flag].</param>
public void EnableProfile(bool enabledFlag)
{
}
/// <summary>
/// Unmarks context as active on the current thread.
/// </summary>
public void End()
{
}
/// <summary>
/// Executes a deferred command list.
/// </summary>
/// <param name="commandList">The deferred command list.</param>
public void ExecuteCommandList(CompiledCommandList commandList)
{
ExecuteCommandListInternal(commandList);
}
/// <summary>
/// Executes multiple deferred command lists.
/// </summary>
/// <param name="count">Number of command lists to execute.</param>
/// <param name="commandLists">The deferred command lists.</param>
public void ExecuteCommandLists(int count, CompiledCommandList[] commandLists)
{
if (commandLists == null) throw new ArgumentNullException(nameof(commandLists));
if (count > commandLists.Length) throw new ArgumentOutOfRangeException(nameof(count));
var fenceValue = NextFenceValue++;
// Recycle resources
for (int index = 0; index < count; index++)
{
var commandList = commandLists[index];
nativeCommandLists.Add(commandList.NativeCommandList);
RecycleCommandListResources(commandList, fenceValue);
}
// Submit and signal fence
NativeCommandQueue.ExecuteCommandLists(count, nativeCommandLists.Items);
NativeCommandQueue.Signal(nativeFence, fenceValue);
ReleaseTemporaryResources();
nativeCommandLists.Clear();
}
public void SimulateReset()
{
simulateReset = true;
}
private void InitializePostFeatures()
{
}
private string GetRendererName()
{
return rendererName;
}
/// <summary>
/// Initializes the specified device.
/// </summary>
/// <param name="graphicsProfiles">The graphics profiles.</param>
/// <param name="deviceCreationFlags">The device creation flags.</param>
/// <param name="windowHandle">The window handle.</param>
private void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle)
{
if (nativeDevice != null)
{
// Destroy previous device
ReleaseDevice();
}
rendererName = Adapter.NativeAdapter.Description.Description;
// Profiling is supported through pix markers
IsProfilingSupported = true;
// Command lists are thread-safe and execute deferred
IsDeferred = true;
bool isDebug = (deviceCreationFlags & DeviceCreationFlags.Debug) != 0;
if (isDebug)
{
SharpDX.Direct3D12.DebugInterface.Get().EnableDebugLayer();
}
// Create Device D3D12 with feature Level based on profile
for (int index = 0; index < graphicsProfiles.Length; index++)
{
var graphicsProfile = graphicsProfiles[index];
try
{
// D3D12 supports only feature level 11+
var level = graphicsProfile.ToFeatureLevel();
if (level < SharpDX.Direct3D.FeatureLevel.Level_11_0)
level = SharpDX.Direct3D.FeatureLevel.Level_11_0;
nativeDevice = new SharpDX.Direct3D12.Device(Adapter.NativeAdapter, level);
RequestedProfile = graphicsProfile;
CurrentFeatureLevel = level;
break;
}
catch (Exception)
{
if (index == graphicsProfiles.Length - 1)
throw;
}
}
// Describe and create the command queue.
var queueDesc = new SharpDX.Direct3D12.CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Direct);
NativeCommandQueue = nativeDevice.CreateCommandQueue(queueDesc);
//queueDesc.Type = CommandListType.Copy;
NativeCopyCommandQueue = nativeDevice.CreateCommandQueue(queueDesc);
TimestampFrequency = NativeCommandQueue.TimestampFrequency;
SrvHandleIncrementSize = NativeDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
SamplerHandleIncrementSize = NativeDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.Sampler);
if (isDebug)
{
var debugDevice = nativeDevice.QueryInterfaceOrNull<DebugDevice>();
if (debugDevice != null)
{
var infoQueue = debugDevice.QueryInterfaceOrNull<InfoQueue>();
if (infoQueue != null)
{
MessageId[] disabledMessages =
{
// This happens when render target or depth stencil clear value is diffrent
// than provided during resource allocation.
MessageId.CleardepthstencilviewMismatchingclearvalue,
MessageId.ClearrendertargetviewMismatchingclearvalue,
// This occurs when there are uninitialized descriptors in a descriptor table,
// even when a shader does not access the missing descriptors.
MessageId.InvalidDescriptorHandle,
// These happen when capturing with VS diagnostics
MessageId.MapInvalidNullRange,
MessageId.UnmapInvalidNullRange,
};
// Disable irrelevant debug layer warnings
InfoQueueFilter filter = new InfoQueueFilter
{
DenyList = new InfoQueueFilterDescription
{
Ids = disabledMessages
}
};
infoQueue.AddStorageFilterEntries(filter);
//infoQueue.SetBreakOnSeverity(MessageSeverity.Error, true);
//infoQueue.SetBreakOnSeverity(MessageSeverity.Warning, true);
infoQueue.Dispose();
}
debugDevice.Dispose();
}
}
// Prepare pools
CommandAllocators = new CommandAllocatorPool(this);
SrvHeaps = new HeapPool(this, SrvHeapSize, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
SamplerHeaps = new HeapPool(this, SamplerHeapSize, DescriptorHeapType.Sampler);
// Prepare descriptor allocators
SamplerAllocator = new DescriptorAllocator(this, DescriptorHeapType.Sampler);
ShaderResourceViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
DepthStencilViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.DepthStencilView);
RenderTargetViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.RenderTargetView);
// Prepare copy command list (start it closed, so that every new use start with a Reset)
NativeCopyCommandAllocator = NativeDevice.CreateCommandAllocator(CommandListType.Direct);
NativeCopyCommandList = NativeDevice.CreateCommandList(CommandListType.Direct, NativeCopyCommandAllocator, null);
NativeCopyCommandList.Close();
// Fence for next frame and resource cleaning
nativeFence = NativeDevice.CreateFence(0, FenceFlags.None);
nativeCopyFence = NativeDevice.CreateFence(0, FenceFlags.None);
}
internal IntPtr AllocateUploadBuffer(int size, out SharpDX.Direct3D12.Resource resource, out int offset, int alignment = 0)
{
// TODO D3D12 thread safety, should we simply use locks?
// Align
if (alignment > 0)
nativeUploadBufferOffset = (nativeUploadBufferOffset + alignment - 1) / alignment * alignment;
if (nativeUploadBuffer == null || nativeUploadBufferOffset + size > nativeUploadBuffer.Description.Width)
{
if (nativeUploadBuffer != null)
{
nativeUploadBuffer.Unmap(0);
TemporaryResources.Enqueue(new KeyValuePair<long, object>(NextFenceValue, nativeUploadBuffer));
}
// Allocate new buffer
// TODO D3D12 recycle old ones (using fences to know when GPU is done with them)
// TODO D3D12 ResourceStates.CopySource not working?
var bufferSize = Math.Max(4 * 1024*1024, size);
nativeUploadBuffer = NativeDevice.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(bufferSize), ResourceStates.GenericRead);
nativeUploadBufferStart = nativeUploadBuffer.Map(0, new SharpDX.Direct3D12.Range());
nativeUploadBufferOffset = 0;
}
// Bump allocate
resource = nativeUploadBuffer;
offset = nativeUploadBufferOffset;
nativeUploadBufferOffset += size;
return nativeUploadBufferStart + offset;
}
internal void WaitCopyQueue()
{
NativeCommandQueue.ExecuteCommandList(NativeCopyCommandList);
NativeCommandQueue.Signal(nativeCopyFence, nextCopyFenceValue);
NativeCommandQueue.Wait(nativeCopyFence, nextCopyFenceValue);
nextCopyFenceValue++;
}
internal void ReleaseTemporaryResources()
{
lock (TemporaryResources)
{
// Release previous frame resources
while (TemporaryResources.Count > 0 && IsFenceCompleteInternal(TemporaryResources.Peek().Key))
{
var temporaryResource = TemporaryResources.Dequeue().Value;
//temporaryResource.Value.Dispose();
var comObject = temporaryResource as SharpDX.ComObject;
if (comObject != null)
((SharpDX.IUnknown)comObject).Release();
else
{
var referenceLink = temporaryResource as GraphicsResourceLink;
if (referenceLink != null)
{
referenceLink.ReferenceCount--;
}
}
}
}
}
private void AdjustDefaultPipelineStateDescription(ref PipelineStateDescription pipelineStateDescription)
{
}
protected void DestroyPlatformDevice()
{
ReleaseDevice();
}
private void ReleaseDevice()
{
// Wait for completion of everything queued
NativeCommandQueue.Signal(nativeFence, NextFenceValue);
NativeCommandQueue.Wait(nativeFence, NextFenceValue);
// Release command queue
NativeCommandQueue.Dispose();
NativeCommandQueue = null;
NativeCopyCommandQueue.Dispose();
NativeCopyCommandQueue = null;
NativeCopyCommandAllocator.Dispose();
NativeCopyCommandList.Dispose();
nativeUploadBuffer.Dispose();
// Release temporary resources
ReleaseTemporaryResources();
nativeFence.Dispose();
nativeFence = null;
nativeCopyFence.Dispose();
nativeCopyFence = null;
// Release pools
CommandAllocators.Dispose();
SrvHeaps.Dispose();
SamplerHeaps.Dispose();
// Release allocators
SamplerAllocator.Dispose();
ShaderResourceViewAllocator.Dispose();
DepthStencilViewAllocator.Dispose();
RenderTargetViewAllocator.Dispose();
if (IsDebugMode)
{
var debugDevice = NativeDevice.QueryInterfaceOrNull<SharpDX.Direct3D12.DebugDevice>();
if (debugDevice != null)
{
debugDevice.ReportLiveDeviceObjects(SharpDX.Direct3D12.ReportingLevel.Detail);
debugDevice.Dispose();
}
}
nativeDevice.Dispose();
nativeDevice = null;
}
internal void OnDestroyed()
{
}
internal long ExecuteCommandListInternal(CompiledCommandList commandList)
{
var fenceValue = NextFenceValue++;
// Submit and signal fence
NativeCommandQueue.ExecuteCommandList(commandList.NativeCommandList);
NativeCommandQueue.Signal(nativeFence, fenceValue);
// Recycle resources
RecycleCommandListResources(commandList, fenceValue);
return fenceValue;
}
private void RecycleCommandListResources(CompiledCommandList commandList, long fenceValue)
{
// Set fence on staging textures
foreach (var stagingResource in commandList.StagingResources)
{
stagingResource.StagingFenceValue = fenceValue;
}
StagingResourceLists.Release(commandList.StagingResources);
commandList.StagingResources.Clear();
// Recycle resources
foreach (var heap in commandList.SrvHeaps)
{
SrvHeaps.RecycleObject(fenceValue, heap);
}
commandList.SrvHeaps.Clear();
DescriptorHeapLists.Release(commandList.SrvHeaps);
foreach (var heap in commandList.SamplerHeaps)
{
SamplerHeaps.RecycleObject(fenceValue, heap);
}
commandList.SamplerHeaps.Clear();
DescriptorHeapLists.Release(commandList.SamplerHeaps);
commandList.Builder.NativeCommandLists.Enqueue(commandList.NativeCommandList);
CommandAllocators.RecycleObject(fenceValue, commandList.NativeCommandAllocator);
}
internal bool IsFenceCompleteInternal(long fenceValue)
{
// Try to avoid checking the fence if possible
if (fenceValue > lastCompletedFence)
lastCompletedFence = Math.Max(lastCompletedFence, nativeFence.CompletedValue); // Protect against race conditions
return fenceValue <= lastCompletedFence;
}
internal void WaitForFenceInternal(long fenceValue)
{
if (IsFenceCompleteInternal(fenceValue))
return;
// TODO D3D12 in case of concurrency, this lock could end up blocking too long a second thread with lower fenceValue then first one
lock (nativeFence)
{
nativeFence.SetEventOnCompletion(fenceValue, fenceEvent.SafeWaitHandle.DangerousGetHandle());
fenceEvent.WaitOne();
lastCompletedFence = fenceValue;
}
}
internal void TagResource(GraphicsResourceLink resourceLink)
{
var texture = resourceLink.Resource as Texture;
if (texture != null && texture.Usage == GraphicsResourceUsage.Dynamic)
{
// Increase the reference count until GPU is done with the resource
resourceLink.ReferenceCount++;
TemporaryResources.Enqueue(new KeyValuePair<long, object>(NextFenceValue, resourceLink));
}
var buffer = resourceLink.Resource as Buffer;
if (buffer != null && buffer.Usage == GraphicsResourceUsage.Dynamic)
{
// Increase the reference count until GPU is done with the resource
resourceLink.ReferenceCount++;
TemporaryResources.Enqueue(new KeyValuePair<long, object>(NextFenceValue, resourceLink));
}
}
internal abstract class ResourcePool<T> : IDisposable where T : Pageable
{
protected readonly GraphicsDevice GraphicsDevice;
private readonly Queue<KeyValuePair<long, T>> liveObjects = new Queue<KeyValuePair<long, T>>();
protected ResourcePool(GraphicsDevice graphicsDevice)
{
GraphicsDevice = graphicsDevice;
}
public void Dispose()
{
lock (liveObjects)
{
foreach (var liveObject in liveObjects)
{
liveObject.Value.Dispose();
}
liveObjects.Clear();
}
}
public T GetObject()
{
// TODO D3D12: SpinLock
lock (liveObjects)
{
// Check if first allocator is ready for reuse
if (liveObjects.Count > 0)
{
var firstAllocator = liveObjects.Peek();
if (firstAllocator.Key <= GraphicsDevice.nativeFence.CompletedValue)
{
liveObjects.Dequeue();
ResetObject(firstAllocator.Value);
if (firstAllocator.Value == null)
{
}
return firstAllocator.Value;
}
}
return CreateObject();
}
}
protected abstract T CreateObject();
protected abstract void ResetObject(T obj);
public void RecycleObject(long fenceValue, T obj)
{
// TODO D3D12: SpinLock
lock (liveObjects)
{
liveObjects.Enqueue(new KeyValuePair<long, T>(fenceValue, obj));
}
}
}
internal class CommandAllocatorPool : ResourcePool<CommandAllocator>
{
public CommandAllocatorPool(GraphicsDevice graphicsDevice) : base(graphicsDevice)
{
}
protected override CommandAllocator CreateObject()
{
// No allocator ready to be used, let's create a new one
return GraphicsDevice.NativeDevice.CreateCommandAllocator(CommandListType.Direct);
}
protected override void ResetObject(CommandAllocator obj)
{
obj.Reset();
}
}
internal class HeapPool : ResourcePool<DescriptorHeap>
{
private readonly int heapSize;
private readonly DescriptorHeapType heapType;
public HeapPool(GraphicsDevice graphicsDevice, int heapSize, DescriptorHeapType heapType) : base(graphicsDevice)
{
this.heapSize = heapSize;
this.heapType = heapType;
}
protected override DescriptorHeap CreateObject()
{
// No allocator ready to be used, let's create a new one
return GraphicsDevice.NativeDevice.CreateDescriptorHeap(new DescriptorHeapDescription
{
DescriptorCount = heapSize,
Flags = DescriptorHeapFlags.ShaderVisible,
Type = heapType,
});
}
protected override void ResetObject(DescriptorHeap obj)
{
}
}
/// <summary>
/// Allocate descriptor handles. For now a simple bump alloc, but at some point we will have to make a real allocator with free
/// </summary>
internal class DescriptorAllocator : IDisposable
{
private const int DescriptorPerHeap = 256;
private GraphicsDevice device;
private DescriptorHeapType descriptorHeapType;
private DescriptorHeap currentHeap;
private CpuDescriptorHandle currentHandle;
private int remainingHandles;
private readonly int descriptorSize;
public DescriptorAllocator(GraphicsDevice device, DescriptorHeapType descriptorHeapType)
{
this.device = device;
this.descriptorHeapType = descriptorHeapType;
this.descriptorSize = device.NativeDevice.GetDescriptorHandleIncrementSize(descriptorHeapType);
}
public void Dispose()
{
currentHeap?.Dispose();
currentHeap = null;
}
public CpuDescriptorHandle Allocate(int count)
{
if (currentHeap == null || remainingHandles < count)
{
currentHeap = device.NativeDevice.CreateDescriptorHeap(new DescriptorHeapDescription
{
Flags = DescriptorHeapFlags.None,
Type = descriptorHeapType,
DescriptorCount = DescriptorPerHeap,
NodeMask = 1,
});
remainingHandles = DescriptorPerHeap;
currentHandle = currentHeap.CPUDescriptorHandleForHeapStart;
}
var result = currentHandle;
currentHandle.Ptr += descriptorSize;
remainingHandles -= count;
return result;
}
}
}
}
#endif
| 38.772152
| 195
| 0.578046
|
[
"MIT"
] |
Alan-love/xenko
|
sources/engine/Stride.Graphics/Direct3D12/GraphicsDevice.Direct3D12.cs
| 27,567
|
C#
|
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Domain
{
/// <summary>
/// ActionProperty Data Structure.
/// </summary>
public class ActionProperty : AlipayObject
{
/// <summary>
/// 属性C端渲染key
/// </summary>
[JsonPropertyName("key")]
public string Key { get; set; }
/// <summary>
/// 交互动作属性元素类型,IMG-图片;TEXT-普通文本
/// </summary>
[JsonPropertyName("type")]
public string Type { get; set; }
/// <summary>
/// 属性图片URL;属性文本值
/// </summary>
[JsonPropertyName("value")]
public string Value { get; set; }
}
}
| 23.241379
| 46
| 0.532641
|
[
"MIT"
] |
Frunck8206/payment
|
src/Essensoft.Paylink.Alipay/Domain/ActionProperty.cs
| 742
|
C#
|
namespace FinTech.Models
{
public class DeribitGetTickerRequest : DeribitRpcRequest<DeribitGetTickerRequest.DeribitGetTickerParams>
{
public DeribitGetTickerRequest(string instrument_name)
{
this.method = "public/ticker";
this.@params = new DeribitGetTickerParams(instrument_name);
}
public class DeribitGetTickerParams
{
public DeribitGetTickerParams(string instrument_name)
{
this.instrument_name = instrument_name;
}
public string instrument_name { get; }
}
}
}
| 30.238095
| 108
| 0.607874
|
[
"MIT"
] |
Misza13/FinTech-Excel
|
FinTech/Models/DeribitGetTickerRequest.cs
| 637
|
C#
|
namespace Navigation.Core.Pages.TestStudioPage
{
using ArtOfTest.WebAii.Controls.HtmlControls;
public partial class TestStudioPage
{
public HtmlSpan TestingFrameworkTreeItem
{
get
{
this.Browser.WaitForElement(5000, "TextContent=Testing Framework");
return this.Browser.Find.ByExpression<HtmlSpan>("TextContent=Testing Framework");
}
}
public HtmlSpan WriteTestsInCodeTreeItem
{
get
{
this.Browser.WaitForElement(5000, "TextContent=Write Tests in Code");
return this.Browser.Find.ByExpression<HtmlSpan>("TextContent=Write Tests in Code");
}
}
public HtmlSpan AdvancedTopicsSubTreeItem
{
get
{
this.Browser.WaitForElement(5000, "TextContent=Advanced Topics");
return this.Browser.Find.AllByExpression<HtmlSpan>("TextContent=Advanced Topics")[1];
}
}
public HtmlSpan HtmlPopupsAndDialogsSubTreeItem
{
get
{
this.Browser.WaitForElement(5000, "TextContent=HTML Popups and Dialogs");
return this.Browser.Find.ByExpression<HtmlSpan>("TextContent=HTML Popups and Dialogs");
}
}
public HtmlAnchor BuiltInHandlersSubTreeItem
{
get
{
this.Browser.WaitForElement(5000, "TextContent=Built-In Handlers");
return this.Browser.Find.ByExpression<HtmlAnchor>("TextContent=Built-In Handlers");
}
}
}
}
| 32.019231
| 103
| 0.575976
|
[
"MIT"
] |
YaneYosifov/Telerik
|
Quality Assurance/Part II/Practical Exam/Problem 2. Telerik Testing Framework/TreeNavigation.Core/Pages/TestStudioPage/TestStudioPage.Map.cs
| 1,667
|
C#
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Text;
namespace CommandLineInjector.Extensions
{
public static class ParameterExtensions
{
/// <summary>
/// Indexes the parameters by creating shortcut names for each parameter and returning the result in a dictionary
/// </summary>
/// <param name="parameterInfos">Set of method parameters with unique names</param>
/// <param name="excludeKeys">Shortcut keys to exclude</param>s
/// <returns>The parameters indexed by their new shortcut names</returns>
public static IDictionary<string, ParameterInfo> IndexShortenedNames(this IEnumerable<ParameterInfo> parameterInfos, HashSet<string> excludeKeys)
{
var dictionary = new Dictionary<string, ParameterInfo>();
foreach (var parameterInfo in parameterInfos)
{
string MakeKey(int length) => parameterInfo.Name.Substring(0, length).ToLower();
if (parameterInfo.HasDefaultValue)
{
int length = 1;
while (dictionary.ContainsKey(MakeKey(length)) || excludeKeys.Contains(MakeKey(length)))
length++;
dictionary.Add(MakeKey(length), parameterInfo);
}
else
{
dictionary.Add(parameterInfo.Name, parameterInfo);
}
}
return dictionary;
}
/// <summary>
/// Gets the description of this parameter, looking first for a <see cref="DescriptionAttribute"/> and falling back to just splitting up the name of the parameter
/// </summary>
/// <param name="parameterInfo">A parameter, preferable with a <see cref="DescriptionAttribute"/> defined</param>
/// <returns>A description of the type</returns>
public static string GetHelpText(this ParameterInfo parameterInfo)
{
return parameterInfo.GetCustomAttribute<DescriptionAttribute>()?.Description ?? parameterInfo.Name.SplitOutPascalCase();
}
/// <summary>
/// Returns true if this parameter requires a value to be passed in the command line
/// </summary>
/// <param name="parameterInfo">A parameter</param>
/// <returns>True if this parameter needs an accompanying value</returns>
public static bool RequiresPassedValue(this ParameterInfo parameterInfo)
{
return parameterInfo.ParameterType != typeof(bool) && parameterInfo.ParameterType != typeof(bool?);
}
}
}
| 43.885246
| 170
| 0.629062
|
[
"MIT"
] |
jcharlesworthuk/CommandLineInjector
|
src/CommandLineInjector/Extensions/ParameterExtensions.cs
| 2,679
|
C#
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ARKBreedingStats
{
public partial class RaisingControl : UserControl
{
public delegate void ExtractBabyEventHandler(Creature mother, Creature father);
public event ExtractBabyEventHandler extractBaby;
public event Form1.collectionChangedEventHandler onChange;
public event Form1.setSpeciesIndexEventHandler setSpeciesIndex;
private int speciesIndex;
public bool updateListView;
private TimeSpan babyTime, maturationTime;
private CreatureCollection cc;
public TimerControl timerControl;
private IncubationTimerEntry iteEdit;
private Creature creatureMaturationEdit;
public RaisingControl()
{
InitializeComponent();
listViewBabies.Groups.Add("incubation", "Incubation/Gestation");
listViewBabies.Groups.Add("baby", "Babies");
listViewBabies.Groups.Add("growing", "Juveniles / Adolescent");
updateListView = false;
ControlExtensions.DoubleBuffered(listViewBabies, true); // prevent flickering
}
public void updateRaisingData()
{
updateRaisingData(speciesIndex, true);
}
public void updateRaisingData(int speciesIndex, bool forceUpdate = false)
{
if (forceUpdate || this.speciesIndex != speciesIndex)
{
this.speciesIndex = speciesIndex;
if (speciesIndex >= 0 && Values.V.species[speciesIndex].taming != null && Values.V.species[speciesIndex].breeding != null)
{
this.SuspendLayout();
BreedingData bd = Values.V.species[speciesIndex].breeding;
string incubationMode;
TimeSpan incubationTime, nextMatingMin, nextMatingMax;
listViewRaisingTimes.Items.Clear();
if (Raising.getRaisingTimes(speciesIndex, out incubationMode, out incubationTime, out babyTime, out maturationTime, out nextMatingMin, out nextMatingMax))
{
string eggInfo = Raising.eggTemperature(speciesIndex);
if (eggInfo.Length > 0)
eggInfo = "\n\n" + eggInfo;
TimeSpan totalTime = incubationTime;
DateTime until = DateTime.Now.Add(totalTime);
string[] times = new string[] { incubationMode, incubationTime.ToString("d':'hh':'mm':'ss"), totalTime.ToString("d':'hh':'mm':'ss"), Utils.shortTimeDate(until) };
listViewRaisingTimes.Items.Add(new ListViewItem(times));
totalTime += babyTime;
until = DateTime.Now.Add(totalTime);
times = new string[] { "Baby", babyTime.ToString("d':'hh':'mm':'ss"), totalTime.ToString("d':'hh':'mm':'ss"), Utils.shortTimeDate(until) };
listViewRaisingTimes.Items.Add(new ListViewItem(times));
totalTime = incubationTime + maturationTime;
until = DateTime.Now.Add(totalTime);
times = new string[] { "Maturation", maturationTime.ToString("d':'hh':'mm':'ss"), totalTime.ToString("d':'hh':'mm':'ss"), Utils.shortTimeDate(until) };
listViewRaisingTimes.Items.Add(new ListViewItem(times));
// food amount needed
string foodadmount = "";
double babyfood, totalfood;
if (Values.V.species[speciesIndex].taming.eats != null &&
uiControls.Trough.foodAmount(speciesIndex, Values.V.babyFoodConsumptionSpeedMultiplier, out babyfood, out totalfood))
{
if (Values.V.species[speciesIndex].taming.eats.IndexOf("Raw Meat") >= 0)
{
foodadmount = "\n\nFood for Baby-Phase: ~" + Math.Ceiling(babyfood / 50) + " Raw Meat"
+ "\nTotal Food for maturation: ~" + Math.Ceiling(totalfood / 50) + " Raw Meat";
}
else if (Values.V.species[speciesIndex].taming.eats.IndexOf("Mejoberry") >= 0)
{
foodadmount = "\n\nFood for Baby-Phase: ~" + Math.Ceiling(babyfood / 30) + " Mejoberries"
+ "\nTotal Food for maturation: ~" + Math.Ceiling(totalfood / 30) + " Mejoberries";
}
foodadmount += "\n - Loss by spoiling is only a rough estimate and may vary.";
}
labelRaisingInfos.Text = "Time between mating: " + nextMatingMin.ToString("d':'hh':'mm':'ss") + " to " + nextMatingMax.ToString("d':'hh':'mm':'ss")
+ eggInfo
+ foodadmount;
tabPageMaturationProgress.Enabled = true;
}
else
{
labelRaisingInfos.Text = "No raising-data available.";
tabPageMaturationProgress.Enabled = false;
}
ResumeLayout();
}
}
}
public CreatureCollection creatureCollection
{
set
{
if (value != null)
cc = value;
}
}
private void nudCurrentWeight_ValueChanged(object sender, EventArgs e)
{
updateMaturationProgress();
}
private void nudTotalWeight_ValueChanged(object sender, EventArgs e)
{
updateMaturationProgress();
}
private void updateMaturationProgress()
{
double babyTimeReciproke = maturationTime.TotalSeconds / babyTime.TotalSeconds;
double maturation = Math.Round((double)(nudCurrentWeight.Value / nudTotalWeight.Value), 3);
labelMaturationProgress.Text = Math.Round(100 * maturation, 1).ToString() + " %";
if (maturationTime.TotalSeconds * maturation < babyTime.TotalSeconds)
{
labelTimeLeftBaby.Text = Utils.durationUntil(babyTime.Subtract(new TimeSpan(0, 0, (int)(babyTime.TotalSeconds * babyTimeReciproke * maturation))));
labelTimeLeftBaby.ForeColor = SystemColors.ControlText;
}
else
{
labelTimeLeftBaby.Text = "not a baby anymore";
labelTimeLeftBaby.ForeColor = SystemColors.GrayText;
}
if (maturation < 1)
{
labelTimeLeftGrowing.Text = Utils.durationUntil(maturationTime.Subtract(new TimeSpan(0, 0, (int)(maturationTime.TotalSeconds * maturation))));
labelTimeLeftGrowing.ForeColor = SystemColors.ControlText;
}
else
{
labelTimeLeftGrowing.Text = "mature";
labelTimeLeftGrowing.ForeColor = SystemColors.GrayText;
}
double foodAmount = 0;
string foodAmountBabyString = "", foodAmountAdultString = "";
if (Values.V.species[speciesIndex].taming.eats != null)
{
if (Values.V.species[speciesIndex].taming.eats.IndexOf("Raw Meat") >= 0)
{
if (uiControls.Trough.foodAmountFromUntil(speciesIndex, Values.V.babyFoodConsumptionSpeedMultiplier, maturation, 0.1, out foodAmount))
foodAmountBabyString = Math.Ceiling(foodAmount / 50) + " Raw Meat";
if (uiControls.Trough.foodAmountFromUntil(speciesIndex, Values.V.babyFoodConsumptionSpeedMultiplier, maturation, 1, out foodAmount))
foodAmountAdultString = Math.Ceiling(foodAmount / 50) + " Raw Meat";
}
else if (Values.V.species[speciesIndex].taming.eats.IndexOf("Mejoberry") >= 0)
{
if (uiControls.Trough.foodAmountFromUntil(speciesIndex, Values.V.babyFoodConsumptionSpeedMultiplier, maturation, 0.1, out foodAmount))
foodAmountBabyString = Math.Ceiling(foodAmount / 30) + " Mejoberries";
if (uiControls.Trough.foodAmountFromUntil(speciesIndex, Values.V.babyFoodConsumptionSpeedMultiplier, maturation, 1, out foodAmount))
foodAmountAdultString = Math.Ceiling(foodAmount / 30) + " Mejoberries";
}
}
labelAmountFoodBaby.Text = foodAmountBabyString;
labelAmountFoodAdult.Text = foodAmountAdultString;
}
public void addIncubationTimer(Creature mother, Creature father, TimeSpan incubationDuration, bool incubationStarted)
{
cc.incubationListEntries.Add(new IncubationTimerEntry(mother, father, incubationDuration, incubationStarted));
onChange?.Invoke();
recreateList();
}
private void removeIncubationTimer(IncubationTimerEntry ite)
{
cc.incubationListEntries.Remove(ite);
}
public void recreateList()
{
if (cc != null)
{
updateListView = false;
listViewBabies.BeginUpdate();
listViewBabies.Items.Clear();
ListViewGroup g = listViewBabies.Groups[0];
// add eggs / pregnancies
foreach (IncubationTimerEntry t in cc.incubationListEntries)
{
int i = Values.V.speciesNames.IndexOf(t.mother.species);
if (i >= 0 && Values.V.species[i].breeding != null)
{
string kind;
if (Values.V.species[i].breeding.gestationTimeAdjusted > 0)
kind = "Gestation";
else kind = "Egg";
string[] cols = new string[] { kind,
t.mother.species,
Utils.timeLeft(t.incubationEnd),
Utils.duration((int)(Values.V.species[i].breeding.maturationTimeAdjusted / 10)),
Utils.duration((int)Values.V.species[i].breeding.maturationTimeAdjusted) };
ListViewItem lvi = new ListViewItem(cols, g);
lvi.Tag = t;
listViewBabies.Items.Add(lvi);
}
}
// add babies / growing
DateTime now = DateTime.Now;
foreach (Creature c in cc.creatures)
{
if (c.growingUntil > now)
{
int i = Values.V.speciesNames.IndexOf(c.species);
if (i >= 0 && Values.V.species[i].breeding != null)
{
DateTime babyUntil = c.growingUntil.AddSeconds(-0.9 * Values.V.species[i].breeding.maturationTimeAdjusted);
string[] cols;
if (babyUntil > now)
{
g = listViewBabies.Groups[1];
cols = new string[] { c.name,
c.species,
"-",
Utils.timeLeft(babyUntil),
Utils.timeLeft(c.growingUntil) };
}
else
{
g = listViewBabies.Groups[2];
cols = new string[] { c.name,
c.species,
"-",
"-",
Utils.timeLeft(c.growingUntil) };
}
ListViewItem lvi = new ListViewItem(cols, g);
lvi.Tag = c;
listViewBabies.Items.Add(lvi);
}
}
}
listViewBabies.EndUpdate();
updateListView = true;
}
}
public void Tick()
{
DateTime now = DateTime.Now;
DateTime alertTime = now.AddMinutes(1);
if (updateListView)
{
listViewBabies.BeginUpdate();
foreach (ListViewItem lvi in listViewBabies.Items)
{
if ((lvi.Tag.GetType() == typeof(IncubationTimerEntry)))
{
var t = (IncubationTimerEntry)lvi.Tag;
int i = Values.V.speciesNames.IndexOf(t.mother.species);
if (i >= 0)
{
lvi.SubItems[2].Text = Utils.timeLeft(t.incubationEnd);
lvi.SubItems[3].Text = Utils.duration((int)(Values.V.species[i].breeding.maturationTimeAdjusted / 10));
lvi.SubItems[4].Text = Utils.duration((int)Values.V.species[i].breeding.maturationTimeAdjusted);
double diff = t.incubationEnd.Subtract(alertTime).TotalSeconds;
if (diff >= 0 && diff < 1)
timerControl.playSound("Birth", 1);
}
}
else if ((lvi.Tag.GetType() == typeof(Creature)))
{
var c = (Creature)lvi.Tag;
int i = Values.V.speciesNames.IndexOf(c.species);
if (i >= 0 && Values.V.species[i].breeding != null)
{
DateTime babyUntil = c.growingUntil.AddSeconds(-0.9 * Values.V.species[i].breeding.maturationTimeAdjusted);
lvi.SubItems[3].Text = Utils.timeLeft(babyUntil);
lvi.SubItems[4].Text = Utils.timeLeft(c.growingUntil);
}
}
}
listViewBabies.EndUpdate();
}
else
{
foreach (ListViewItem lvi in listViewBabies.Items)
{
if ((lvi.Tag.GetType() == typeof(IncubationTimerEntry)))
{
var t = (IncubationTimerEntry)lvi.Tag;
int i = Values.V.speciesNames.IndexOf(t.mother.species);
double diff = t.incubationEnd.Subtract(alertTime).TotalSeconds;
if (diff >= 0 && diff < 1)
timerControl.playSound("Birth", 1);
}
}
}
}
private void extractValuesOfHatchedbornBabyToolStripMenuItem_Click(object sender, EventArgs e)
{
if (listViewBabies.SelectedIndices.Count > 0 && listViewBabies.SelectedItems[0].Tag.GetType() == typeof(IncubationTimerEntry))
{
var ite = (IncubationTimerEntry)listViewBabies.SelectedItems[0].Tag;
extractBaby?.Invoke(ite.mother, ite.father);
}
}
private void deleteTimerToolStripMenuItem_Click(object sender, EventArgs e)
{
if (listViewBabies.SelectedIndices.Count > 0
&& listViewBabies.SelectedItems[0].Tag.GetType() == typeof(IncubationTimerEntry))
{
IncubationTimerEntry ite = (IncubationTimerEntry)listViewBabies.SelectedItems[0].Tag;
if (MessageBox.Show("Delete this timer?\n" + ite.mother.species + ", ending in " + Utils.timeLeft(ite.incubationEnd)
+ (listViewBabies.SelectedIndices.Count > 1 ? "\n\nand " + (listViewBabies.SelectedIndices.Count - 1).ToString() + " more selected timers" : "") + "?"
, "Delete?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
for (int t = listViewBabies.SelectedIndices.Count - 1; t >= 0; t--)
removeIncubationTimer((IncubationTimerEntry)listViewBabies.SelectedItems[t].Tag);
recreateList();
onChange?.Invoke();
}
}
}
public void deleteAllExpiredIncubationTimers()
{
if (MessageBox.Show("Delete all expired incubation timers?", "Delete?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
foreach (ListViewItem lvi in listViewBabies.Items)
{
if ((lvi.Tag.GetType() == typeof(IncubationTimerEntry)))
{
IncubationTimerEntry ite = (IncubationTimerEntry)lvi.Tag;
if (ite.incubationStarted && ite.incubationEnd < DateTime.Now)
removeIncubationTimer(ite);
}
}
recreateList();
onChange?.Invoke();
}
}
private void removeAllExpiredTimersToolStripMenuItem_Click(object sender, EventArgs e)
{
deleteAllExpiredIncubationTimers();
}
private void listViewBabies_SelectedIndexChanged(object sender, EventArgs e)
{
if (listViewBabies.SelectedIndices.Count > 0)
{
if (listViewBabies.SelectedItems[0].Tag.GetType() == typeof(Creature))
{
Creature c = (Creature)listViewBabies.SelectedItems[0].Tag;
int sI = Values.V.speciesNames.IndexOf(c.species);
setSpeciesIndex?.Invoke(sI);
if (sI >= 0 && Values.V.species[sI].breeding != null && c.growingUntil > DateTime.Now)
{
double maturing = Math.Round(1 - c.growingUntil.Subtract(DateTime.Now).TotalSeconds / Values.V.species[sI].breeding.maturationTimeAdjusted, 2);
if (maturing > 0 && maturing <= 1)
{
nudCurrentWeight.Value = (decimal)(maturing * c.valuesBreeding[4]);
nudTotalWeight.Value = (decimal)c.valuesBreeding[4];
}
}
parentStats1.setParentValues(c.Mother, c.Father);
// edit-box
creatureMaturationEdit = c;
iteEdit = null;
setEditTimer();
}
else if (listViewBabies.SelectedItems[0].Tag.GetType() == typeof(IncubationTimerEntry))
{
IncubationTimerEntry ite = (IncubationTimerEntry)listViewBabies.SelectedItems[0].Tag;
int sI = Values.V.speciesNames.IndexOf(ite.mother.species);
setSpeciesIndex?.Invoke(sI);
parentStats1.setParentValues(ite.mother, ite.father);
// edit-box
creatureMaturationEdit = null;
iteEdit = ite;
setEditTimer();
}
}
else
{
iteEdit = null;
creatureMaturationEdit = null;
setEditTimer();
}
}
private void setEditTimer()
{
if (iteEdit != null)
{
lEditTimerName.Text = "Incubation" + (iteEdit.mother != null ? " (" + iteEdit.mother.species + ")" : "");
dateTimePickerEditTimerFinish.Value = iteEdit.incubationEnd;
TimeSpan ts = iteEdit.incubationEnd.Subtract(DateTime.Now);
dhmsInputTimerEditTimer.Timespan = (ts.TotalSeconds > 0 ? ts : TimeSpan.Zero);
}
else if (creatureMaturationEdit != null)
{
lEditTimerName.Text = creatureMaturationEdit.name + " (" + creatureMaturationEdit.species + ")";
dateTimePickerEditTimerFinish.Value = creatureMaturationEdit.growingUntil;
TimeSpan ts = creatureMaturationEdit.growingUntil.Subtract(DateTime.Now);
dhmsInputTimerEditTimer.Timespan = (ts.TotalSeconds > 0 ? ts : TimeSpan.Zero);
}
else
{
lEditTimerName.Text = "no timer selected";
dateTimePickerEditTimerFinish.Value = DateTime.Now;
dhmsInputTimerEditTimer.Timespan = TimeSpan.Zero;
}
}
private void dhmsInputTimerEditTimer_TextChanged(object sender, EventArgs e)
{
if (dhmsInputTimerEditTimer.Focused)
dateTimePickerEditTimerFinish.Value = DateTime.Now.Add(dhmsInputTimerEditTimer.Timespan);
}
private void dateTimePickerEditTimerFinish_ValueChanged(object sender, EventArgs e)
{
if (dateTimePickerEditTimerFinish.Focused)
dhmsInputTimerEditTimer.Timespan = dateTimePickerEditTimerFinish.Value.Subtract(DateTime.Now);
}
private void bSaveTimerEdit_Click(object sender, EventArgs e)
{
if (iteEdit != null)
{
iteEdit.incubationEnd = dateTimePickerEditTimerFinish.Value;
}
else if (creatureMaturationEdit != null)
{
creatureMaturationEdit.growingUntil = dateTimePickerEditTimerFinish.Value;
}
else return;
recreateList();
onChange?.Invoke();
}
}
}
| 47.004255
| 186
| 0.516386
|
[
"MIT"
] |
LaoArchAngel/ARKStatsExtractor
|
ARKBreedingStats/RaisingControl.cs
| 22,094
|
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#if NO_THREAD
using System;
using System.Threading;
namespace System.Reactive.Concurrency
{
class Thread
{
private readonly ThreadStart _start;
public Thread(ThreadStart start)
{
_start = start;
}
public string Name { get; set; }
public bool IsBackground { get; set; }
public void Start()
{
System.Threading.Tasks.Task.Factory.StartNew(Run, System.Threading.Tasks.TaskCreationOptions.LongRunning);
}
private void Run()
{
_start();
}
}
delegate void ThreadStart();
}
#endif
| 23.305556
| 118
| 0.624553
|
[
"Apache-2.0"
] |
LeeCampbell/Rx.NET
|
Rx.NET/Source/System.Reactive.PlatformServices/Reactive/Concurrency/Thread.Stub.cs
| 841
|
C#
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Tripous;
using DevApp.Web.Models;
namespace DevApp.Web.Controllers
{
/// <summary>
/// A test controller
/// </summary>
[AllowAnonymous]
public class TestController : BaseControllerMvc
{
/* actions */
/// <summary>
/// Test
/// </summary>
public IActionResult EmptyTest()
{
//Sys.Error("That's a big mistake");
return View();
}
/// <summary>
/// Test
/// </summary>
public IActionResult TabIndexAndFocus()
{
return View();
}
}
}
| 19.404762
| 51
| 0.566871
|
[
"Unlicense"
] |
tbebekis/Tripous
|
DevApps/DevApp.Web/Controllers/TestController.cs
| 817
|
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;
using Pulumi.Utilities;
namespace Pulumi.Aws.Ec2
{
public static class GetInstance
{
/// <summary>
/// Use this data source to get the ID of an Amazon EC2 Instance for use in other
/// resources.
///
/// {{% examples %}}
/// ## Example Usage
/// {{% example %}}
///
/// ```csharp
/// using Pulumi;
/// using Aws = Pulumi.Aws;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var foo = Output.Create(Aws.Ec2.GetInstance.InvokeAsync(new Aws.Ec2.GetInstanceArgs
/// {
/// Filters =
/// {
/// new Aws.Ec2.Inputs.GetInstanceFilterArgs
/// {
/// Name = "image-id",
/// Values =
/// {
/// "ami-xxxxxxxx",
/// },
/// },
/// new Aws.Ec2.Inputs.GetInstanceFilterArgs
/// {
/// Name = "tag:Name",
/// Values =
/// {
/// "instance-name-tag",
/// },
/// },
/// },
/// InstanceId = "i-instanceid",
/// }));
/// }
///
/// }
/// ```
/// {{% /example %}}
/// {{% /examples %}}
/// </summary>
public static Task<GetInstanceResult> InvokeAsync(GetInstanceArgs? args = null, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetInstanceResult>("aws:ec2/getInstance:getInstance", args ?? new GetInstanceArgs(), options.WithVersion());
/// <summary>
/// Use this data source to get the ID of an Amazon EC2 Instance for use in other
/// resources.
///
/// {{% examples %}}
/// ## Example Usage
/// {{% example %}}
///
/// ```csharp
/// using Pulumi;
/// using Aws = Pulumi.Aws;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var foo = Output.Create(Aws.Ec2.GetInstance.InvokeAsync(new Aws.Ec2.GetInstanceArgs
/// {
/// Filters =
/// {
/// new Aws.Ec2.Inputs.GetInstanceFilterArgs
/// {
/// Name = "image-id",
/// Values =
/// {
/// "ami-xxxxxxxx",
/// },
/// },
/// new Aws.Ec2.Inputs.GetInstanceFilterArgs
/// {
/// Name = "tag:Name",
/// Values =
/// {
/// "instance-name-tag",
/// },
/// },
/// },
/// InstanceId = "i-instanceid",
/// }));
/// }
///
/// }
/// ```
/// {{% /example %}}
/// {{% /examples %}}
/// </summary>
public static Output<GetInstanceResult> Invoke(GetInstanceInvokeArgs? args = null, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.Invoke<GetInstanceResult>("aws:ec2/getInstance:getInstance", args ?? new GetInstanceInvokeArgs(), options.WithVersion());
}
public sealed class GetInstanceArgs : Pulumi.InvokeArgs
{
[Input("filters")]
private List<Inputs.GetInstanceFilterArgs>? _filters;
/// <summary>
/// One or more name/value pairs to use as filters. There are
/// several valid keys, for a full reference, check out
/// [describe-instances in the AWS CLI reference][1].
/// </summary>
public List<Inputs.GetInstanceFilterArgs> Filters
{
get => _filters ?? (_filters = new List<Inputs.GetInstanceFilterArgs>());
set => _filters = value;
}
/// <summary>
/// If true, wait for password data to become available and retrieve it. Useful for getting the administrator password for instances running Microsoft Windows. The password data is exported to the `password_data` attribute. See [GetPasswordData](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_GetPasswordData.html) for more information.
/// </summary>
[Input("getPasswordData")]
public bool? GetPasswordData { get; set; }
/// <summary>
/// Retrieve Base64 encoded User Data contents into the `user_data_base64` attribute. A SHA-1 hash of the User Data contents will always be present in the `user_data` attribute. Defaults to `false`.
/// </summary>
[Input("getUserData")]
public bool? GetUserData { get; set; }
/// <summary>
/// Specify the exact Instance ID with which to populate the data source.
/// </summary>
[Input("instanceId")]
public string? InstanceId { get; set; }
[Input("instanceTags")]
private Dictionary<string, string>? _instanceTags;
/// <summary>
/// A map of tags, each pair of which must
/// exactly match a pair on the desired Instance.
/// </summary>
public Dictionary<string, string> InstanceTags
{
get => _instanceTags ?? (_instanceTags = new Dictionary<string, string>());
set => _instanceTags = value;
}
[Input("tags")]
private Dictionary<string, string>? _tags;
/// <summary>
/// A map of tags assigned to the Instance.
/// </summary>
public Dictionary<string, string> Tags
{
get => _tags ?? (_tags = new Dictionary<string, string>());
set => _tags = value;
}
public GetInstanceArgs()
{
}
}
public sealed class GetInstanceInvokeArgs : Pulumi.InvokeArgs
{
[Input("filters")]
private InputList<Inputs.GetInstanceFilterInputArgs>? _filters;
/// <summary>
/// One or more name/value pairs to use as filters. There are
/// several valid keys, for a full reference, check out
/// [describe-instances in the AWS CLI reference][1].
/// </summary>
public InputList<Inputs.GetInstanceFilterInputArgs> Filters
{
get => _filters ?? (_filters = new InputList<Inputs.GetInstanceFilterInputArgs>());
set => _filters = value;
}
/// <summary>
/// If true, wait for password data to become available and retrieve it. Useful for getting the administrator password for instances running Microsoft Windows. The password data is exported to the `password_data` attribute. See [GetPasswordData](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_GetPasswordData.html) for more information.
/// </summary>
[Input("getPasswordData")]
public Input<bool>? GetPasswordData { get; set; }
/// <summary>
/// Retrieve Base64 encoded User Data contents into the `user_data_base64` attribute. A SHA-1 hash of the User Data contents will always be present in the `user_data` attribute. Defaults to `false`.
/// </summary>
[Input("getUserData")]
public Input<bool>? GetUserData { get; set; }
/// <summary>
/// Specify the exact Instance ID with which to populate the data source.
/// </summary>
[Input("instanceId")]
public Input<string>? InstanceId { get; set; }
[Input("instanceTags")]
private InputMap<string>? _instanceTags;
/// <summary>
/// A map of tags, each pair of which must
/// exactly match a pair on the desired Instance.
/// </summary>
public InputMap<string> InstanceTags
{
get => _instanceTags ?? (_instanceTags = new InputMap<string>());
set => _instanceTags = value;
}
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// A map of tags assigned to the Instance.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public GetInstanceInvokeArgs()
{
}
}
[OutputType]
public sealed class GetInstanceResult
{
/// <summary>
/// The ID of the AMI used to launch the instance.
/// </summary>
public readonly string Ami;
/// <summary>
/// The ARN of the instance.
/// </summary>
public readonly string Arn;
/// <summary>
/// Whether or not the Instance is associated with a public IP address or not (Boolean).
/// </summary>
public readonly bool AssociatePublicIpAddress;
/// <summary>
/// The availability zone of the Instance.
/// </summary>
public readonly string AvailabilityZone;
/// <summary>
/// The credit specification of the Instance.
/// </summary>
public readonly ImmutableArray<Outputs.GetInstanceCreditSpecificationResult> CreditSpecifications;
public readonly bool DisableApiTermination;
/// <summary>
/// The EBS block device mappings of the Instance.
/// </summary>
public readonly ImmutableArray<Outputs.GetInstanceEbsBlockDeviceResult> EbsBlockDevices;
/// <summary>
/// Whether the Instance is EBS optimized or not (Boolean).
/// </summary>
public readonly bool EbsOptimized;
/// <summary>
/// The enclave options of the Instance.
/// </summary>
public readonly ImmutableArray<Outputs.GetInstanceEnclaveOptionResult> EnclaveOptions;
/// <summary>
/// The ephemeral block device mappings of the Instance.
/// </summary>
public readonly ImmutableArray<Outputs.GetInstanceEphemeralBlockDeviceResult> EphemeralBlockDevices;
public readonly ImmutableArray<Outputs.GetInstanceFilterResult> Filters;
public readonly bool? GetPasswordData;
public readonly bool? GetUserData;
/// <summary>
/// The Id of the dedicated host the instance will be assigned to.
/// </summary>
public readonly string HostId;
/// <summary>
/// The name of the instance profile associated with the Instance.
/// </summary>
public readonly string IamInstanceProfile;
/// <summary>
/// The provider-assigned unique ID for this managed resource.
/// </summary>
public readonly string Id;
public readonly string? InstanceId;
/// <summary>
/// The state of the instance. One of: `pending`, `running`, `shutting-down`, `terminated`, `stopping`, `stopped`. See [Instance Lifecycle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) for more information.
/// </summary>
public readonly string InstanceState;
public readonly ImmutableDictionary<string, string> InstanceTags;
/// <summary>
/// The type of the Instance.
/// </summary>
public readonly string InstanceType;
/// <summary>
/// The IPv6 addresses associated to the Instance, if applicable. **NOTE**: Unlike the IPv4 address, this doesn't change if you attach an EIP to the instance.
/// </summary>
public readonly ImmutableArray<string> Ipv6Addresses;
/// <summary>
/// The key name of the Instance.
/// </summary>
public readonly string KeyName;
/// <summary>
/// The metadata options of the Instance.
/// </summary>
public readonly ImmutableArray<Outputs.GetInstanceMetadataOptionResult> MetadataOptions;
/// <summary>
/// Whether detailed monitoring is enabled or disabled for the Instance (Boolean).
/// </summary>
public readonly bool Monitoring;
/// <summary>
/// The ID of the network interface that was created with the Instance.
/// </summary>
public readonly string NetworkInterfaceId;
/// <summary>
/// The Amazon Resource Name (ARN) of the Outpost.
/// </summary>
public readonly string OutpostArn;
/// <summary>
/// Base-64 encoded encrypted password data for the instance.
/// Useful for getting the administrator password for instances running Microsoft Windows.
/// This attribute is only exported if `get_password_data` is true.
/// See [GetPasswordData](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_GetPasswordData.html) for more information.
/// </summary>
public readonly string PasswordData;
/// <summary>
/// The placement group of the Instance.
/// </summary>
public readonly string PlacementGroup;
/// <summary>
/// The number of the partition the instance is in.
/// </summary>
public readonly int PlacementPartitionNumber;
/// <summary>
/// The private DNS name assigned to the Instance. Can only be
/// used inside the Amazon EC2, and only available if you've enabled DNS hostnames
/// for your VPC.
/// </summary>
public readonly string PrivateDns;
/// <summary>
/// The private IP address assigned to the Instance.
/// </summary>
public readonly string PrivateIp;
/// <summary>
/// The public DNS name assigned to the Instance. For EC2-VPC, this
/// is only available if you've enabled DNS hostnames for your VPC.
/// </summary>
public readonly string PublicDns;
/// <summary>
/// The public IP address assigned to the Instance, if applicable. **NOTE**: If you are using an `aws.ec2.Eip` with your instance, you should refer to the EIP's address directly and not use `public_ip`, as this field will change after the EIP is attached.
/// </summary>
public readonly string PublicIp;
/// <summary>
/// The root block device mappings of the Instance
/// </summary>
public readonly ImmutableArray<Outputs.GetInstanceRootBlockDeviceResult> RootBlockDevices;
/// <summary>
/// The secondary private IPv4 addresses assigned to the instance's primary network interface (eth0) in a VPC.
/// </summary>
public readonly ImmutableArray<string> SecondaryPrivateIps;
/// <summary>
/// The associated security groups.
/// </summary>
public readonly ImmutableArray<string> SecurityGroups;
/// <summary>
/// Whether the network interface performs source/destination checking (Boolean).
/// </summary>
public readonly bool SourceDestCheck;
/// <summary>
/// The VPC subnet ID.
/// </summary>
public readonly string SubnetId;
/// <summary>
/// A map of tags assigned to the Instance.
/// </summary>
public readonly ImmutableDictionary<string, string> Tags;
/// <summary>
/// The tenancy of the instance: `dedicated`, `default`, `host`.
/// </summary>
public readonly string Tenancy;
/// <summary>
/// SHA-1 hash of User Data supplied to the Instance.
/// </summary>
public readonly string UserData;
/// <summary>
/// Base64 encoded contents of User Data supplied to the Instance. This attribute is only exported if `get_user_data` is true.
/// </summary>
public readonly string UserDataBase64;
/// <summary>
/// The associated security groups in a non-default VPC.
/// </summary>
public readonly ImmutableArray<string> VpcSecurityGroupIds;
[OutputConstructor]
private GetInstanceResult(
string ami,
string arn,
bool associatePublicIpAddress,
string availabilityZone,
ImmutableArray<Outputs.GetInstanceCreditSpecificationResult> creditSpecifications,
bool disableApiTermination,
ImmutableArray<Outputs.GetInstanceEbsBlockDeviceResult> ebsBlockDevices,
bool ebsOptimized,
ImmutableArray<Outputs.GetInstanceEnclaveOptionResult> enclaveOptions,
ImmutableArray<Outputs.GetInstanceEphemeralBlockDeviceResult> ephemeralBlockDevices,
ImmutableArray<Outputs.GetInstanceFilterResult> filters,
bool? getPasswordData,
bool? getUserData,
string hostId,
string iamInstanceProfile,
string id,
string? instanceId,
string instanceState,
ImmutableDictionary<string, string> instanceTags,
string instanceType,
ImmutableArray<string> ipv6Addresses,
string keyName,
ImmutableArray<Outputs.GetInstanceMetadataOptionResult> metadataOptions,
bool monitoring,
string networkInterfaceId,
string outpostArn,
string passwordData,
string placementGroup,
int placementPartitionNumber,
string privateDns,
string privateIp,
string publicDns,
string publicIp,
ImmutableArray<Outputs.GetInstanceRootBlockDeviceResult> rootBlockDevices,
ImmutableArray<string> secondaryPrivateIps,
ImmutableArray<string> securityGroups,
bool sourceDestCheck,
string subnetId,
ImmutableDictionary<string, string> tags,
string tenancy,
string userData,
string userDataBase64,
ImmutableArray<string> vpcSecurityGroupIds)
{
Ami = ami;
Arn = arn;
AssociatePublicIpAddress = associatePublicIpAddress;
AvailabilityZone = availabilityZone;
CreditSpecifications = creditSpecifications;
DisableApiTermination = disableApiTermination;
EbsBlockDevices = ebsBlockDevices;
EbsOptimized = ebsOptimized;
EnclaveOptions = enclaveOptions;
EphemeralBlockDevices = ephemeralBlockDevices;
Filters = filters;
GetPasswordData = getPasswordData;
GetUserData = getUserData;
HostId = hostId;
IamInstanceProfile = iamInstanceProfile;
Id = id;
InstanceId = instanceId;
InstanceState = instanceState;
InstanceTags = instanceTags;
InstanceType = instanceType;
Ipv6Addresses = ipv6Addresses;
KeyName = keyName;
MetadataOptions = metadataOptions;
Monitoring = monitoring;
NetworkInterfaceId = networkInterfaceId;
OutpostArn = outpostArn;
PasswordData = passwordData;
PlacementGroup = placementGroup;
PlacementPartitionNumber = placementPartitionNumber;
PrivateDns = privateDns;
PrivateIp = privateIp;
PublicDns = publicDns;
PublicIp = publicIp;
RootBlockDevices = rootBlockDevices;
SecondaryPrivateIps = secondaryPrivateIps;
SecurityGroups = securityGroups;
SourceDestCheck = sourceDestCheck;
SubnetId = subnetId;
Tags = tags;
Tenancy = tenancy;
UserData = userData;
UserDataBase64 = userDataBase64;
VpcSecurityGroupIds = vpcSecurityGroupIds;
}
}
}
| 37.822878
| 356
| 0.564
|
[
"ECL-2.0",
"Apache-2.0"
] |
RafalSumislawski/pulumi-aws
|
sdk/dotnet/Ec2/GetInstance.cs
| 20,500
|
C#
|
using System;
using Dpws.Client;
using Dpws.Client.Discovery;
#if !Windows && !WindowsCE
using Microsoft.SPOT;
using System.Ext;
#endif
namespace Interop.SimpleService
{
class DiscoClient
{
private DpwsClient m_dpwsClient = null;
/// <summary>
/// Creates an instance of the eventing client.
/// </summary>
/// <param name="client">The DpwsClient instance that will receive events.</param>
public DiscoClient(DpwsClient client)
{
m_dpwsClient = client;
}
/// <summary>
/// Probe for a SimpleService endpoint.
/// </summary>
/// <param name="serviceAddress">A string containing the address of the simple service to find.</param>
/// <returns>
/// A DpwsMetadata object containing details about a SimpleService, null if
/// a SImpleService is not found.
/// </returns>
public DpwsMetadata GetSimpleService(string serviceAddress)
{
// Resolve the service address
m_dpwsClient.DiscoveryClient.ReceiveTimeout = 10000;
DpwsServiceDescription resolveMatch = m_dpwsClient.DiscoveryClient.Resolve(serviceAddress);
// Display results
string serviceEndpoint = null;
string targetService = null;
if (resolveMatch != null)
{
// Print resolve match information
System.Ext.Console.Write("");
System.Ext.Console.Write("ResolveMatch:");
System.Ext.Console.Write(" Endpoint Address = " + resolveMatch.Endpoint.Address);
System.Ext.Console.Write(" Types:");
targetService = resolveMatch.Endpoint.Address.AbsoluteUri;
for (int i = 0; i < resolveMatch.ServiceTypes.Count; ++i)
{
System.Ext.Console.Write(" Name = " + resolveMatch.ServiceTypes[i].TypeName);
System.Ext.Console.Write(" Namespace = " + resolveMatch.ServiceTypes[i].NamespaceUri);
}
System.Ext.Console.Write(" Xaddrs:");
foreach (string xaddr in resolveMatch.XAddrs)
{
System.Ext.Console.Write(" TransportAddress = " + xaddr);
// Since there's no support for IPV6 look for IPV4 address
if (xaddr.IndexOf(':') != -1)
{
serviceEndpoint = xaddr;
}
}
System.Ext.Console.Write(" Metadata Version = " + resolveMatch.MetadataVersion);
}
else
{
System.Ext.Console.Write("");
System.Ext.Console.Write("SimpleDeviceType at address: " + serviceAddress + " failed to resolve. Discovery aborted");
return null;
}
// Mae sure we got an address
if (serviceEndpoint == null)
{
System.Ext.Console.Write("");
System.Ext.Console.Write("Resolve did not send an IPV4 xaddr. Discovery aborted.");
}
// Send DirectedProbe
DpwsMetadata m_mexDetails = null;
// Create an empty search types collection
DpwsServiceTypes searchTypes = new DpwsServiceTypes();
// Build a SimpleDeviceType search type
DpwsServiceType searchType1 = new DpwsServiceType("SimpleService", "http://schemas.example.org/SimpleService");
searchTypes.Add(searchType1);
// Get the SimpleDeviceType service details
// Note: Uncomment the next line to test DirectedProbe to any MF Dpws service
// DpwsServiceDescriptions probeMatches = m_dpwsClient.DiscoveryClient.DirectedProbe(serviceEndpoint, m_dpwsClient.DiscoveryClient.DiscoVersion.WellKnownAddress, searchTypes);
// Note: Uncomment the next line to test against a DiscoveryProxy
// DpwsServiceDescriptions probeMatches = m_dpwsClient.DiscoveryClient.DirectedProbe(serviceEndpoint, targetService, searchTypes);
DpwsServiceDescriptions probeMatches = m_dpwsClient.DiscoveryClient.Probe(searchTypes);
if (probeMatches != null && probeMatches.Count > 0)
{
// Select the probe match
DpwsServiceDescription probeMatch = probeMatches[0];
// Note: Uncoment the following line to test DirectedResolve against any MF Dpws Service.
// DpwsServiceDescription resolveMatch1 = m_dpwsClient.DiscoveryClient.DirectedResolve(probeMatch.XAddrs[0], m_dpwsClient.DiscoveryClient.DiscoVersion.WellKnownAddress, serviceAddress);
// Print the probe match information
System.Ext.Console.Write("**********************");
System.Ext.Console.Write("ProbeMatch received: " + probeMatches.Count);
System.Ext.Console.Write("");
System.Ext.Console.Write("ProbeMatch:");
System.Ext.Console.Write(" Endpoint Address = " + probeMatch.Endpoint.Address);
System.Ext.Console.Write(" Types:");
for (int i = 0; i < probeMatch.ServiceTypes.Count; ++i)
{
System.Ext.Console.Write(" Name = " + probeMatch.ServiceTypes[i].TypeName);
System.Ext.Console.Write(" Namespace = " + probeMatch.ServiceTypes[i].NamespaceUri);
}
System.Ext.Console.Write(" Xaddrs:");
foreach (string xaddr in probeMatch.XAddrs)
System.Ext.Console.Write(" TransportAddress = " + xaddr);
System.Ext.Console.Write(" Metadata Version = " + probeMatch.MetadataVersion);
}
// If we had a probe match store the service endpoint and get metadata
if (probeMatches != null)
{
m_dpwsClient.EndpointAddress = serviceAddress;
m_mexDetails = m_dpwsClient.MexClient.Get(serviceEndpoint);
if (m_mexDetails == null)
{
System.Ext.Console.Write("");
System.Ext.Console.Write("Get did not receive metadata. Discovery aborted.");
return null;
}
// Display metadata information
System.Ext.Console.Write(" Metadata:");
System.Ext.Console.Write(" ThisModel:");
System.Ext.Console.Write(" Manufacturer: " + m_mexDetails.ThisModel.Manufacturer);
System.Ext.Console.Write(" ManufacturerUrl: " + m_mexDetails.ThisModel.ManufacturerUrl);
System.Ext.Console.Write(" ModelName: " + m_mexDetails.ThisModel.ModelName);
System.Ext.Console.Write(" ModelNumber: " + m_mexDetails.ThisModel.ModelNumber);
System.Ext.Console.Write(" ModelUrl: " + m_mexDetails.ThisModel.ModelUrl);
System.Ext.Console.Write(" PresentationUrl: " + m_mexDetails.ThisModel.PresentationUrl);
System.Ext.Console.Write(" ThisDevice:");
System.Ext.Console.Write(" FirmwareVersion: " + m_mexDetails.ThisDevice.FirmwareVersion);
System.Ext.Console.Write(" FriendlyName: " + m_mexDetails.ThisDevice.FriendlyName);
System.Ext.Console.Write(" SerialNumber: " + m_mexDetails.ThisDevice.SerialNumber);
if (m_mexDetails.Relationship.Host != null)
{
System.Ext.Console.Write(" Host:");
System.Ext.Console.Write(" Service ID: " + m_mexDetails.Relationship.Host.ServiceID);
System.Ext.Console.Write(" Address: " + m_mexDetails.Relationship.Host.EndpointRefs[0].Address.AbsoluteUri);
System.Ext.Console.Write(" Types:");
for (int i = 0; i < m_mexDetails.Relationship.Host.ServiceTypes.Count; ++i)
{
DpwsServiceType serviceType = m_mexDetails.Relationship.Host.ServiceTypes[i];
System.Ext.Console.Write(" Name: " + serviceType.TypeName);
System.Ext.Console.Write(" NamespaceUri: " + serviceType.NamespaceUri);
}
}
if (m_mexDetails.Relationship.HostedServices != null)
{
System.Ext.Console.Write(" HostedServices:");
for (int i = 0; i < m_mexDetails.Relationship.HostedServices.Count; ++i)
{
DpwsMexService hostedService = m_mexDetails.Relationship.HostedServices[i];
System.Ext.Console.Write(" Service ID: " + hostedService.ServiceID);
System.Ext.Console.Write(" Address: " + hostedService.EndpointRefs[0].Address.AbsoluteUri);
System.Ext.Console.Write(" Types:");
for (int ii = 0; ii < hostedService.ServiceTypes.Count; ++ii)
{
System.Ext.Console.Write(" Type name: " + hostedService.ServiceTypes[ii].TypeName);
System.Ext.Console.Write(" NamespaceUri: " + hostedService.ServiceTypes[ii].NamespaceUri);
}
}
}
}
return m_mexDetails;
}
}
}
| 52.125
| 201
| 0.564488
|
[
"Apache-2.0"
] |
Sirokujira/MicroFrameworkPK_v4_3
|
Product/Samples/DPWS/SimpleServiceClient/DiscoveryClient.cs
| 9,591
|
C#
|
using System;
using System.Collections.Generic;
using UnityEngine;
namespace UnityEditor.Rendering.Universal.ShaderGUI
{
internal class ParticlesUnlitShader : BaseShaderGUI
{
// Properties
private BakedLitGUI.BakedLitProperties shadingModelProperties;
private ParticleGUI.ParticleProperties particleProps;
// List of renderers using this material in the scene, used for validating vertex streams
List<ParticleSystemRenderer> m_RenderersUsingThisMaterial = new List<ParticleSystemRenderer>();
public override void FindProperties(MaterialProperty[] properties)
{
base.FindProperties(properties);
shadingModelProperties = new BakedLitGUI.BakedLitProperties(properties);
particleProps = new ParticleGUI.ParticleProperties(properties);
}
public override void MaterialChanged(Material material)
{
if (material == null)
throw new ArgumentNullException("material");
SetMaterialKeywords(material, null, ParticleGUI.SetMaterialKeywords);
}
public override void DrawSurfaceOptions(Material material)
{
// Detect any changes to the material
EditorGUI.BeginChangeCheck();
{
base.DrawSurfaceOptions(material);
DoPopup(ParticleGUI.Styles.colorMode, particleProps.colorMode, Enum.GetNames(typeof(ParticleGUI.ColorMode)));
}
if (EditorGUI.EndChangeCheck())
{
foreach (var obj in blendModeProp.targets)
MaterialChanged((Material)obj);
}
}
public override void DrawSurfaceInputs(Material material)
{
base.DrawSurfaceInputs(material);
BakedLitGUI.Inputs(shadingModelProperties, materialEditor);
DrawEmissionProperties(material, true);
}
public override void DrawAdvancedOptions(Material material)
{
EditorGUI.BeginChangeCheck();
{
materialEditor.ShaderProperty(particleProps.flipbookMode, ParticleGUI.Styles.flipbookMode);
ParticleGUI.FadingOptions(material, materialEditor, particleProps);
ParticleGUI.DoVertexStreamsArea(material, m_RenderersUsingThisMaterial);
if (EditorGUI.EndChangeCheck())
{
MaterialChanged(material);
}
}
base.DrawAdvancedOptions(material);
}
public override void OnOpenGUI(Material material, MaterialEditor materialEditor)
{
CacheRenderersUsingThisMaterial(material);
base.OnOpenGUI(material, materialEditor);
}
void CacheRenderersUsingThisMaterial(Material material)
{
m_RenderersUsingThisMaterial.Clear();
ParticleSystemRenderer[] renderers = UnityEngine.Object.FindObjectsOfType(typeof(ParticleSystemRenderer)) as ParticleSystemRenderer[];
foreach (ParticleSystemRenderer renderer in renderers)
{
if (renderer.sharedMaterial == material)
m_RenderersUsingThisMaterial.Add(renderer);
}
}
}
} // namespace UnityEditor
| 38.522727
| 147
| 0.624779
|
[
"MIT"
] |
AlePPisa/GameJamPractice1
|
Cellular/Library/PackageCache/com.unity.render-pipelines.universal@8.2.0/Editor/ShaderGUI/Shaders/ParticlesUnlitShader.cs
| 3,390
|
C#
|
using System;
public class Program
{
public static void Main()
{
string character = Console.ReadLine();
string[] charac = character.Split(' ');
string[] reverceChar = new string[charac.Length];
for (int i = 0; i < charac.Length; i++)
{
reverceChar[i] = charac[i];
}
Array.Reverse(reverceChar);
for (int i = 0; i < reverceChar.Length; i++)
{
Console.Write("{0} ",reverceChar[i]);
}
}
}
| 21.583333
| 57
| 0.5
|
[
"MIT"
] |
IvayloKovachev09/SoftUni
|
Programming Fundamentals/Arrays and Lists - Lab/06. Reverse Array of Strings/Reverse Array of Strings.cs
| 520
|
C#
|
using ControleDespesas.Domain.Empresas.Commands.Output;
using ControleDespesas.Domain.Empresas.Handlers;
using ControleDespesas.Domain.Empresas.Interfaces.Handlers;
using ControleDespesas.Domain.Empresas.Interfaces.Repositories;
using ControleDespesas.Infra.Commands;
using ControleDespesas.Infra.Data.Repositories;
using ControleDespesas.Test.AppConfigurations.Base;
using ControleDespesas.Test.AppConfigurations.Settings;
using ControleDespesas.Test.AppConfigurations.Util;
using NUnit.Framework;
namespace ControleDespesas.Test.Empresas.Handlers
{
public class EmpresaHandlerTest : DatabaseTest
{
private readonly IEmpresaRepository _repository;
private readonly IEmpresaHandler _handler;
public EmpresaHandlerTest()
{
CriarBaseDeDadosETabelas();
_repository = new EmpresaRepository(MockSettingsInfraData);
_handler = new EmpresaHandler(_repository);
}
[SetUp]
public void Setup() => CriarBaseDeDadosETabelas();
[Test]
public void Handler_AdicionarEmpresa()
{
var empresaCommand = new SettingsTest().EmpresaAdicionarCommand;
var retorno = _handler.Handler(empresaCommand);
var retornoDados = (EmpresaCommandOutput)retorno.Dados;
TestContext.WriteLine(retornoDados.FormatarJsonDeSaida());
Assert.True(retorno.Sucesso);
Assert.AreEqual("Empresa gravada com sucesso!", retorno.Mensagem);
Assert.AreEqual(1, retornoDados.Id);
Assert.AreEqual(empresaCommand.Nome, retornoDados.Nome);
Assert.AreEqual(empresaCommand.Logo, retornoDados.Logo);
}
[Test]
public void Handler_AtualizarEmpresa()
{
var empresa = new SettingsTest().Empresa1;
_repository.Salvar(empresa);
var empresaCommand = new SettingsTest().EmpresaAtualizarCommand;
var retorno = _handler.Handler(empresa.Id, empresaCommand);
var retornoDados = (EmpresaCommandOutput)retorno.Dados;
TestContext.WriteLine(retornoDados.FormatarJsonDeSaida());
Assert.True(retorno.Sucesso);
Assert.AreEqual("Empresa atualizada com sucesso!", retorno.Mensagem);
Assert.AreEqual(empresaCommand.Id, retornoDados.Id);
Assert.AreEqual(empresaCommand.Nome, retornoDados.Nome);
Assert.AreEqual(empresaCommand.Logo, retornoDados.Logo);
}
[Test]
public void Handler_ApagarEmpresa()
{
var empresa = new SettingsTest().Empresa1;
_repository.Salvar(empresa);
var retorno = _handler.Handler(empresa.Id);
var retornoDados = (CommandOutput)retorno.Dados;
TestContext.WriteLine(retornoDados.FormatarJsonDeSaida());
Assert.True(retorno.Sucesso);
Assert.AreEqual("Empresa excluída com sucesso!", retorno.Mensagem);
Assert.AreEqual(empresa.Id, retornoDados.Id);
}
[TearDown]
public void TearDown() => DroparTabelas();
}
}
| 37.035714
| 81
| 0.676953
|
[
"MIT"
] |
lsantoss/ControleDespesas
|
ControleDespesas_ApiNetCore21_Dapper/ControleDespesas.Test/Empresas/Handlers/EmpresaHandlerTest.cs
| 3,114
|
C#
|
// ***********************************************************************
// Assembly : XLabs.Platform
// Author : XLabs Team
// Created : 01-02-2016
//
// Last Modified By : XLabs Team
// Last Modified On : 01-04-2016
// ***********************************************************************
// <copyright file="FontService.cs" company="XLabs Team">
// Copyright (c) XLabs Team. All rights reserved.
// </copyright>
// <summary>
// This project is licensed under the Apache 2.0 license
// https://github.com/XLabs/Xamarin-Forms-Labs/blob/master/LICENSE
//
// XLabs is a open source project that aims to provide a powerfull and cross
// platform set of controls tailored to work with Xamarin Forms.
// </summary>
// ***********************************************************************
//
using System.Collections.Generic;
namespace XLabs.Platform.Services
{
/// <summary>
/// A FontService implementation for Windows Platforms.
/// </summary>
public class FontService
{
/// <summary>
/// Gets the font names.
/// </summary>
/// <returns>IEnumerable<System.String>.</returns>
public IEnumerable<string> GetFontNames()
{
var fontList = new List<string>();
#if NETFX_CORE || WINDOWS_PHONE_APP
var factory = new SharpDX.DirectWrite.Factory();
var fontCollection = factory.GetSystemFontCollection(false);
var familyCount = fontCollection.FontFamilyCount;
for (int i = 0; i < familyCount; i++)
{
var fontFamily = fontCollection.GetFontFamily(i);
var familyNames = fontFamily.FamilyNames;
int index;
if (!familyNames.FindLocaleName(System.Globalization.CultureInfo.CurrentCulture.Name, out index))
{
familyNames.FindLocaleName("en-us", out index);
}
string name = familyNames.GetString(index);
fontList.Add(name);
}
#endif
return fontList;
}
}
}
| 34.063492
| 113
| 0.526561
|
[
"Apache-2.0"
] |
Bhekinkosi12/Xamarin-Forms-Labs
|
src/Platform/XLabs.Platform.WinRT.Shared/Services/FontService.cs
| 2,148
|
C#
|
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// </auto-generated>
namespace Microsoft.Azure.Management.Sql.Fluent
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for EncryptionProtectorsOperations.
/// </summary>
public static partial class EncryptionProtectorsOperationsExtensions
{
/// <summary>
/// Gets a list of server encryption protectors
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<EncryptionProtectorInner>> ListByServerAsync(this IEncryptionProtectorsOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServerWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a server encryption protector.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EncryptionProtectorInner> GetAsync(this IEncryptionProtectorsOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an existing encryption protector.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='parameters'>
/// The requested encryption protector resource state.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EncryptionProtectorInner> CreateOrUpdateAsync(this IEncryptionProtectorsOperations operations, string resourceGroupName, string serverName, EncryptionProtectorInner parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates an existing encryption protector.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='parameters'>
/// The requested encryption protector resource state.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<EncryptionProtectorInner> BeginCreateOrUpdateAsync(this IEncryptionProtectorsOperations operations, string resourceGroupName, string serverName, EncryptionProtectorInner parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a list of server encryption protectors
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<EncryptionProtectorInner>> ListByServerNextAsync(this IEncryptionProtectorsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServerNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| 47.136986
| 284
| 0.589364
|
[
"MIT"
] |
Azure/azure-libraries-for-net
|
src/ResourceManagement/Sql/Generated/EncryptionProtectorsOperationsExtensions.cs
| 6,882
|
C#
|
using Euricom.IoT.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Euricom.IoT.Api.Managers.Interfaces
{
public interface ILazyBoneManager
{
Task<IEnumerable<Euricom.IoT.Models.LazyBone>> GetAll();
Task<Euricom.IoT.Models.LazyBone> GetByDeviceId(string deviceId);
Task<Euricom.IoT.Models.LazyBone> GetByDeviceName(string deviceName);
Task<Euricom.IoT.Models.LazyBone> Add(Euricom.IoT.Models.LazyBone danaLock);
Task<Euricom.IoT.Models.LazyBone> Edit(Euricom.IoT.Models.LazyBone danaLock);
Task Remove(string devicename);
Task<bool> TestConnection(string deviceId);
Task<bool> GetCurrentStateSwitch(string deviceId);
Task<LazyBoneDimmerState> GetCurrentStateDimmer(string deviceId);
Task Switch(string deviceId, string state);
/// <summary>
/// Changes light intensity of specific device
/// </summary>
/// <param name="deviceId"></param>
/// <param name="value">Must be between 1 and 255 inclusive (1 is brightest, 255 is darkest)</param>
/// <returns></returns>
Task SetLightValue(string deviceId, short? value);
/// <summary>
/// Changes light intensity three times as a test
/// </summary>
/// <param name="deviceId"></param>
/// <returns></returns>
Task TestChangeLightIntensity(string deviceId);
}
}
| 38.891892
| 108
| 0.66713
|
[
"MIT"
] |
Euricom/case-iot-gateway
|
src/Euricom.IoT.Api.Managers/Interfaces/ILazyBoneManager.cs
| 1,441
|
C#
|
namespace NServiceBus
{
internal class EncryptionHeaders
{
public const string KeyIdentifier = "KeyIdentifier";
}
}
| 17.125
| 60
| 0.678832
|
[
"MIT"
] |
BobAtParticular/NServiceBus.AesEncryptionService
|
NServiceBus.AesEncryptionService/Headers.cs
| 139
|
C#
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace RostamBot.Persistence.Migrations
{
public partial class AddReportViaDirectField : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsViaDirect",
table: "SuspiciousAccountReports",
nullable: false,
defaultValue: false);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsViaDirect",
table: "SuspiciousAccountReports");
}
}
}
| 28.666667
| 71
| 0.606105
|
[
"MIT"
] |
Hameds/RostamBot
|
RostamBot.Persistence/Migrations/20190824074414_AddReportViaDirectField.cs
| 690
|
C#
|
//
// Tile.cs
// MB2D Engine
//
// --------------------------------------------------------------
//
// Created by Jacob Milligan on 13/10/2016.
// Copyright (c) Jacob Milligan All rights reserved
//
using System;
using Microsoft.Xna.Framework;
namespace MB2D
{
/// <summary>
/// Flags a tile as passable or impassable, used in collision checking.
/// </summary>
public enum TileFlag
{
/// <summary>
/// Flags a tile as walkable
/// </summary>
Passable,
/// <summary>
/// Flags a tile as collidable and unable to be walked on.
/// </summary>
Impassable
}
/// <summary>
/// Represents a single tile in a tile map.
/// </summary>
public class Tile
{
/// <summary>
/// Initializes a new instance of the <see cref="T:MidnightBlue.Tile"/> class
/// </summary>
/// <param name="textureID">ID of the texture region in the tile map to use for this tile, i.e. Grass or water.</param>
/// <param name="color">Color tint to apply to the tile.</param>
public Tile(int textureID, Color color)
{
ID = textureID;
TintColor = color;
Flag = TileFlag.Passable;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:MidnightBlue.Tile"/> class.
/// </summary>
public Tile() : this(1, Color.Transparent) { }
/// <summary>
/// Gets or sets the tile map region ID to use for this tile.
/// </summary>
/// <value>The tile map region ID.</value>
public int ID { get; protected set; }
/// <summary>
/// Gets or sets the color of the tint.
/// </summary>
/// <value>The color of the tint.</value>
public Color TintColor { get; protected set; }
/// <summary>
/// Gets or sets the tile flag for collision detection.
/// </summary>
/// <value>The flag.</value>
public TileFlag Flag { get; set; }
}
}
| 26.422535
| 123
| 0.578358
|
[
"Unlicense",
"MIT"
] |
jacobmilligan/MB2D
|
src/Tiles/Tile.cs
| 1,876
|
C#
|
using System.Threading.Tasks;
using Abp.Application.Services;
using lygwys.BookList.MultiTenancy.Dto;
namespace lygwys.BookList.MultiTenancy
{
public interface ITenantRegistrationAppService:IApplicationService
{
/// <summary>
/// 公开注册租户功能
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
Task<TenantDto> RegisterTenantAsync(CreateTenantDto input);
}
}
| 27.25
| 70
| 0.667431
|
[
"MIT"
] |
lygwys/lygwys.BookList-github
|
src/booklist-aspnet-core/src/lygwys.BookList.Application/MultiTenancy/ITenantRegistrationAppService.cs
| 454
|
C#
|
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OrmTest
{
public partial class NewUnitTest
{
public static SqlSugarClient Db=> new SqlSugarClient(new ConnectionConfig()
{
DbType = DbType.SqlServer,
ConnectionString = Config.ConnectionString,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true,
AopEvents = new AopEvents
{
OnLogExecuting = (sql, p) =>
{
Console.WriteLine(sql);
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
}
}
});
public static void RestData()
{
Db.DbMaintenance.TruncateTable<Order>();
Db.DbMaintenance.TruncateTable<OrderItem>();
}
public static void Init()
{
UCustom01.Init();
UCustom02.Init();
UCustom03.Init();
UCustom04.Init();
UCustom05.Init();
SubQueryTest();
UConfig();
DeleteTest();
Fastest2();
SplitTest();
Filter();
Insert();
Insert2();
Enum();
Tran();
Queue();
CodeFirst();
Updateable();
Json();
Ado();
Queryable();
Queryable2();
QueryableAsync();
AopTest();
//Thread();
//Thread2();
//Thread3();
}
}
}
| 25.96875
| 108
| 0.460289
|
[
"Apache-2.0"
] |
sy0574/SqlSugar
|
Src/Asp.Net/SqlServerTest/UnitTest/Main.cs
| 1,664
|
C#
|
/*
* Swagger Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace IO.Swagger.Model
{
/// <summary>
/// ArrayTest
/// </summary>
[DataContract]
public partial class ArrayTest : IEquatable<ArrayTest>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ArrayTest" /> class.
/// </summary>
/// <param name="ArrayOfString">ArrayOfString.</param>
/// <param name="ArrayArrayOfInteger">ArrayArrayOfInteger.</param>
/// <param name="ArrayArrayOfModel">ArrayArrayOfModel.</param>
public ArrayTest(List<string> ArrayOfString = default(List<string>), List<List<long?>> ArrayArrayOfInteger = default(List<List<long?>>), List<List<ReadOnlyFirst>> ArrayArrayOfModel = default(List<List<ReadOnlyFirst>>))
{
this.ArrayOfString = ArrayOfString;
this.ArrayArrayOfInteger = ArrayArrayOfInteger;
this.ArrayArrayOfModel = ArrayArrayOfModel;
}
/// <summary>
/// Gets or Sets ArrayOfString
/// </summary>
[DataMember(Name="array_of_string", EmitDefaultValue=false)]
public List<string> ArrayOfString { get; set; }
/// <summary>
/// Gets or Sets ArrayArrayOfInteger
/// </summary>
[DataMember(Name="array_array_of_integer", EmitDefaultValue=false)]
public List<List<long?>> ArrayArrayOfInteger { get; set; }
/// <summary>
/// Gets or Sets ArrayArrayOfModel
/// </summary>
[DataMember(Name="array_array_of_model", EmitDefaultValue=false)]
public List<List<ReadOnlyFirst>> ArrayArrayOfModel { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ArrayTest {\n");
sb.Append(" ArrayOfString: ").Append(ArrayOfString).Append("\n");
sb.Append(" ArrayArrayOfInteger: ").Append(ArrayArrayOfInteger).Append("\n");
sb.Append(" ArrayArrayOfModel: ").Append(ArrayArrayOfModel).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as ArrayTest);
}
/// <summary>
/// Returns true if ArrayTest instances are equal
/// </summary>
/// <param name="other">Instance of ArrayTest to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ArrayTest other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.ArrayOfString == other.ArrayOfString ||
this.ArrayOfString != null &&
this.ArrayOfString.SequenceEqual(other.ArrayOfString)
) &&
(
this.ArrayArrayOfInteger == other.ArrayArrayOfInteger ||
this.ArrayArrayOfInteger != null &&
this.ArrayArrayOfInteger.SequenceEqual(other.ArrayArrayOfInteger)
) &&
(
this.ArrayArrayOfModel == other.ArrayArrayOfModel ||
this.ArrayArrayOfModel != null &&
this.ArrayArrayOfModel.SequenceEqual(other.ArrayArrayOfModel)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.ArrayOfString != null)
hash = hash * 59 + this.ArrayOfString.GetHashCode();
if (this.ArrayArrayOfInteger != null)
hash = hash * 59 + this.ArrayArrayOfInteger.GetHashCode();
if (this.ArrayArrayOfModel != null)
hash = hash * 59 + this.ArrayArrayOfModel.GetHashCode();
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 38.33758
| 226
| 0.584981
|
[
"Apache-2.0"
] |
baynezy/swagger-codegen
|
samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayTest.cs
| 6,019
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using OmniSharp.Services;
namespace OmniSharp.Endpoint
{
public class LanguagePredicateHandler : IPredicateHandler
{
private readonly IEnumerable<IProjectSystem> _projectSystems;
public LanguagePredicateHandler(IEnumerable<IProjectSystem> projectSystems)
{
_projectSystems = projectSystems;
}
public string GetLanguageForFilePath(string filePath)
{
foreach (var projectSystem in _projectSystems)
{
if (projectSystem.Extensions.Any(extension => filePath.EndsWith(extension, StringComparison.OrdinalIgnoreCase)))
{
return projectSystem.Language;
}
}
return null;
}
}
}
| 26.903226
| 128
| 0.633094
|
[
"MIT"
] |
DustinCampbell/omnisharp-roslyn
|
src/OmniSharp.Host/Endpoint/LanguagePredicateHandler.cs
| 834
|
C#
|
using System;
namespace FindNthDigit
{
internal class Program
{
public static void Main(string[] args)
{
Console.WriteLine(new Solution().FindNthDigit(3));
Console.WriteLine(new Solution().FindNthDigit(11));
Console.WriteLine(new Solution().FindNthDigit(1000000000));
}
}
}
public class Solution
{
public int FindNthDigit(int n)
{
long length = 1;
long digits = 9;
long start = 1;
while (n > length * digits)
{
n -= (int)(length * digits);
digits *= 10;
start *= 10;
length++;
}
start += (n - 1) / length;
var s = start.ToString();
return s[(int)((n - 1) % length)] - '0';
}
}
| 21.243243
| 71
| 0.498728
|
[
"MIT"
] |
thenitro/leet-code-problems
|
2021/FindNthDigit/FindNthDigit/Program.cs
| 788
|
C#
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.Coyote.Random;
using Microsoft.Coyote.Specifications;
using Microsoft.Coyote.Tasks;
using Microsoft.Coyote.Tests.Common;
using Microsoft.Coyote.Tests.Common.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Coyote.Production.Tests.Tasks
{
public class TaskRandomBooleanTests : BaseTest
{
public TaskRandomBooleanTests(ITestOutputHelper output)
: base(output)
{
}
[Fact(Timeout = 5000)]
public void TestRandomBooleanInSynchronousTask()
{
this.TestWithError(async () =>
{
Generator generator = Generator.Create();
SharedEntry entry = new SharedEntry();
async Task WriteAsync()
{
await Task.CompletedTask;
if (generator.NextBoolean())
{
entry.Value = 3;
}
else
{
entry.Value = 5;
}
}
await WriteAsync();
Specification.Assert(entry.Value == 5, "Value is {0} instead of 5.", entry.Value);
},
configuration: GetConfiguration().WithTestingIterations(200),
expectedError: "Value is 3 instead of 5.",
replay: true);
}
[Fact(Timeout = 5000)]
public void TestRandomBooleanInAsynchronousTask()
{
this.TestWithError(async () =>
{
Generator generator = Generator.Create();
SharedEntry entry = new SharedEntry();
async Task WriteWithDelayAsync()
{
await Task.Delay(1);
if (generator.NextBoolean())
{
entry.Value = 3;
}
else
{
entry.Value = 5;
}
}
await WriteWithDelayAsync();
Specification.Assert(entry.Value == 5, "Value is {0} instead of 5.", entry.Value);
},
configuration: GetConfiguration().WithTestingIterations(200),
expectedError: "Value is 3 instead of 5.",
replay: true);
}
[Fact(Timeout = 5000)]
public void TestRandomBooleanInParallelTask()
{
this.TestWithError(async () =>
{
Generator generator = Generator.Create();
SharedEntry entry = new SharedEntry();
await Task.Run(() =>
{
if (generator.NextBoolean())
{
entry.Value = 3;
}
else
{
entry.Value = 5;
}
});
Specification.Assert(entry.Value == 5, "Value is {0} instead of 5.", entry.Value);
},
configuration: GetConfiguration().WithTestingIterations(200),
expectedError: "Value is 3 instead of 5.",
replay: true);
}
[Fact(Timeout = 5000)]
public void TestRandomBooleanInParallelSynchronousTask()
{
this.TestWithError(async () =>
{
Generator generator = Generator.Create();
SharedEntry entry = new SharedEntry();
await Task.Run(async () =>
{
await Task.CompletedTask;
if (generator.NextBoolean())
{
entry.Value = 3;
}
else
{
entry.Value = 5;
}
});
Specification.Assert(entry.Value == 5, "Value is {0} instead of 5.", entry.Value);
},
configuration: GetConfiguration().WithTestingIterations(200),
expectedError: "Value is 3 instead of 5.",
replay: true);
}
[Fact(Timeout = 5000)]
public void TestRandomBooleanInParallelAsynchronousTask()
{
this.TestWithError(async () =>
{
Generator generator = Generator.Create();
SharedEntry entry = new SharedEntry();
await Task.Run(async () =>
{
await Task.Delay(1);
if (generator.NextBoolean())
{
entry.Value = 3;
}
else
{
entry.Value = 5;
}
});
Specification.Assert(entry.Value == 5, "Value is {0} instead of 5.", entry.Value);
},
configuration: GetConfiguration().WithTestingIterations(200),
expectedError: "Value is 3 instead of 5.",
replay: true);
}
[Fact(Timeout = 5000)]
public void TestRandomBooleanInNestedParallelSynchronousTask()
{
this.TestWithError(async () =>
{
Generator generator = Generator.Create();
SharedEntry entry = new SharedEntry();
await Task.Run(async () =>
{
await Task.Run(async () =>
{
await Task.CompletedTask;
if (generator.NextBoolean())
{
entry.Value = 3;
}
else
{
entry.Value = 5;
}
});
});
Specification.Assert(entry.Value == 5, "Value is {0} instead of 5.", entry.Value);
},
configuration: GetConfiguration().WithTestingIterations(200),
expectedError: "Value is 3 instead of 5.",
replay: true);
}
}
}
| 32.128866
| 98
| 0.439756
|
[
"MIT"
] |
Bhaskers-Blu-Org2/coyote
|
Tests/Production.Tests/Tasks/RandomValues/TaskRandomBooleanTests.cs
| 6,235
|
C#
|
namespace Notes.App.Controllers
{
using SimpleMvc.Framework.Attributes.Methods;
using SimpleMvc.Framework.Contracts;
public class HomeController : BaseController
{
[HttpGet]
public IActionResult Index() => View();
}
}
| 21.333333
| 49
| 0.679688
|
[
"MIT"
] |
msotiroff/Softuni-learning
|
C# Web Module/CSharp-Web-Development-Basics/09.WorkShop/NotesApplication/Notes.App/Controllers/HomeController.cs
| 258
|
C#
|
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace SpaceShipSurvival
{
public class ShopController : MonoBehaviour
{
[SerializeField] private GameObject _upgradeButtonPrefab;
[SerializeField] private Transform _upgradeButtonsParent;
[SerializeField] private Button _shopButton;
[SerializeField] private GameObject _shopPanel;
private bool _showingPanel = false;
[SerializeField] private Upgrades.Upgrades _upgrades;
private void Awake()
{
RoundController.Instance.RoundChangeState += RoundChangeState;
_shopPanel.SetActive(false);
GenerateButtonUpgrades();
}
public void GenerateButtonUpgrades()
{
foreach (var upgrade in _upgrades.upgrades)
{
GameObject newUpgradeButton = Instantiate(_upgradeButtonPrefab, _upgradeButtonsParent);
newUpgradeButton.GetComponentsInChildren<Image>()[1].sprite = upgrade.icon;
Button button = newUpgradeButton.GetComponent<Button>();
button.onClick.AddListener(() =>
{
upgrade.Upgrading();
//Actualitzar el text de la ui al nou preu.
});
}
}
public void RoundChangeState(bool roundActive)
{
if (roundActive)
{
_shopButton.interactable = false;
_shopPanel.SetActive(false);
_showingPanel = false;
}
else
{
_shopButton.interactable = true;
}
}
public void ShowShopPanel()
{
_showingPanel = !_showingPanel;
_shopPanel.SetActive(_showingPanel);
}
}
}
| 30.33871
| 103
| 0.564593
|
[
"MIT"
] |
JoanOrtiga/Spaceship-survival
|
Spaceship-Survival/Assets/ShopController.cs
| 1,881
|
C#
|
using System;
using System.IO;
using System.Reflection;
using System.Text;
using Newtonsoft.Json;
using NUnit.Framework;
// ReSharper disable InconsistentNaming
namespace Bodoconsult.Core.Typography.Test
{
[TestFixture]
public class UnitTestTypographyBase
{
private const double Tolerance = 0.0001;
private readonly string ExportFolderName;
public UnitTestTypographyBase()
{
var directoryInfo = new DirectoryInfo(Assembly.GetExecutingAssembly().Location).Parent;
var dir = directoryInfo?.Parent?.Parent?.Parent;
if (dir != null) ExportFolderName = Path.Combine(dir.FullName, "SampleData");
}
[Test]
public void TestSetLayout()
{
var t = new TypographyBase();
t.SetMargins();
Assert.IsTrue(t.TypeAreaWidth - 175 < Tolerance);
Assert.IsTrue(Math.Abs(t.MarginUnit - 0.875) < Tolerance);
Assert.IsTrue(Math.Abs(t.MarginLeft - 1.75) < Tolerance);
Assert.IsTrue(Math.Abs(t.MarginRight - 1.75) < Tolerance);
Assert.IsTrue(Math.Abs(t.MarginTop - 0.875) < Tolerance);
Assert.IsTrue(Math.Abs(t.MarginBottom - 1.75) < Tolerance);
//var erg = t.GetPixelHeight(4);
Assert.IsTrue(Math.Abs(t.GetWidth(4) - 11.5) < Tolerance);
Assert.IsTrue(Math.Abs(t.GetHeight(4) - 7.11) < Tolerance);
Assert.IsTrue(Math.Abs(t.GetPixelWidth(4) - (int)(11.5 * TypographicConstants.InchPerCentimeter * 96)) < Tolerance);
Assert.IsTrue(Math.Abs(t.GetPixelHeight(4) - (int)(7.11 * TypographicConstants.InchPerCentimeter * 96)) < Tolerance);
}
[Test]
public void TestExportImport_Elegant()
{
var t = new ElegantTypographyPageHeader("Cambria", "Calibri", "Calibri")
{
MarginLeftFactor = 1,
MarginRightFactor = 1,
MarginTopFactor = 1,
MarginBottomFactor = 1
};
t.SetMargins();
var fileName = Path.Combine(ExportFolderName, "ElegantTypography.json");
if (File.Exists(fileName)) File.Delete(fileName);
ExportToJson(t, fileName);
var typo2 = ImportFromJson<ElegantTypographyPageHeader>(fileName);
typo2.SetMargins();
Assert.IsTrue(File.Exists(fileName));
Assert.IsFalse(typo2 == null);
Assert.IsTrue(t.MarginUnit - typo2.MarginUnit < Tolerance);
}
[Test]
public void TestExportImport_Elegant_Bodoprivate()
{
var t = new ElegantTypographyPageHeader("Cambria", "Cambria", "Cambria")
{
LogoPath = @"C:\bodoconsult\Logos\logoStatera.jpg"
};
t.SetMargins();
var fileName = Path.Combine(ExportFolderName, "ElegantTypographyBodoPrivate.json");
if (File.Exists(fileName)) File.Delete(fileName);
ExportToJson(t, fileName);
var typo2 = ImportFromJson<ElegantTypographyPageHeader>(fileName);
typo2.SetMargins();
Assert.IsTrue(File.Exists(fileName));
Assert.IsFalse(typo2 == null);
Assert.IsTrue(t.MarginUnit - typo2.MarginUnit < Tolerance);
}
[Test]
public void TestExportImport_Compact()
{
var t = new CompactTypographyPageHeader("Cambria", "Calibri", "Calibri")
{
MarginLeftFactor = 1,
MarginRightFactor = 1,
MarginTopFactor = 1,
MarginBottomFactor = 1
};
t.SetMargins();
var fileName = Path.Combine(ExportFolderName, "CompactTypography.json");
if (File.Exists(fileName)) File.Delete(fileName);
ExportToJson(t, fileName);
var typo2 = ImportFromJson<CompactTypographyPageHeader>(fileName);
typo2.SetMargins();
Assert.IsTrue(File.Exists(fileName));
Assert.IsFalse(typo2 == null);
Assert.IsTrue(t.MarginUnit - typo2.MarginUnit < Tolerance);
}
private static void ExportToJson(ITypography typography, string fileName)
{
var json = JsonConvert.SerializeObject(
typography,
Formatting.Indented,
new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
});
//json = Encrypt(json);
var sw11 = new StreamWriter(fileName, false, Encoding.UTF8);
sw11.WriteLine(json);
sw11.Close();
}
private static T ImportFromJson<T>(string fileName) where T : ITypography
{
var json = File.ReadAllText(fileName, Encoding.UTF8);
//json = Decrypt(json);
var erg = (T)JsonConvert.DeserializeObject(json, typeof(T),
new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
});
return erg;
}
}
}
| 29.597765
| 129
| 0.558324
|
[
"MIT"
] |
RobertLeisner/Bodoconsult.Core.Typography
|
Bodoconsult.Core.Typography.Test/UnitTestTypographyBase.cs
| 5,300
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SimpleDeviceDiscovery : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
| 16.105263
| 52
| 0.637255
|
[
"Apache-2.0"
] |
M8s-Inc/M8s-Magic-Leap-Playground
|
Assets/Scripts/SimpleDeviceDiscovery.cs
| 308
|
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.EventHub.V20180101Preview
{
/// <summary>
/// Single Event Hubs Cluster resource in List or Get operations.
/// </summary>
[AzureNativeResourceType("azure-native:eventhub/v20180101preview:Cluster")]
public partial class Cluster : Pulumi.CustomResource
{
/// <summary>
/// The UTC time when the Event Hubs Cluster was created.
/// </summary>
[Output("createdAt")]
public Output<string> CreatedAt { get; private set; } = null!;
/// <summary>
/// Resource location.
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// The metric ID of the cluster resource. Provided by the service and not modifiable by the user.
/// </summary>
[Output("metricId")]
public Output<string> MetricId { get; private set; } = null!;
/// <summary>
/// Resource name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Properties of the cluster SKU.
/// </summary>
[Output("sku")]
public Output<Outputs.ClusterSkuResponse?> Sku { get; private set; } = null!;
/// <summary>
/// Status of the Cluster resource
/// </summary>
[Output("status")]
public Output<string> Status { get; private set; } = null!;
/// <summary>
/// Resource tags.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// The UTC time when the Event Hubs Cluster was last updated.
/// </summary>
[Output("updatedAt")]
public Output<string> UpdatedAt { get; private set; } = null!;
/// <summary>
/// Create a Cluster resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public Cluster(string name, ClusterArgs args, CustomResourceOptions? options = null)
: base("azure-native:eventhub/v20180101preview:Cluster", name, args ?? new ClusterArgs(), MakeResourceOptions(options, ""))
{
}
private Cluster(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:eventhub/v20180101preview:Cluster", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:eventhub/v20180101preview:Cluster"},
new Pulumi.Alias { Type = "azure-native:eventhub:Cluster"},
new Pulumi.Alias { Type = "azure-nextgen:eventhub:Cluster"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing Cluster resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static Cluster Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new Cluster(name, id, options);
}
}
public sealed class ClusterArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the Event Hubs Cluster.
/// </summary>
[Input("clusterName")]
public Input<string>? ClusterName { get; set; }
/// <summary>
/// Resource location.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// Name of the resource group within the azure subscription.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// Properties of the cluster SKU.
/// </summary>
[Input("sku")]
public Input<Inputs.ClusterSkuArgs>? Sku { get; set; }
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Resource tags.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public ClusterArgs()
{
}
}
}
| 36.067073
| 135
| 0.571767
|
[
"Apache-2.0"
] |
polivbr/pulumi-azure-native
|
sdk/dotnet/EventHub/V20180101Preview/Cluster.cs
| 5,915
|
C#
|
using AutoMapper;
using HelloWorld.V2.Infrastructure;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace HelloWorld.V2.Domain
{
public class HelloWorldService : IHelloWorldService
{
private static readonly HashSet<string> ValidHelloWorlds = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"hello,world",
"hello world",
"hello world!",
"hello,world!"
};
private readonly IHelloWorldRepository _repository;
public HelloWorldService(IHelloWorldRepository repository)
{
this._repository = repository;
}
public async Task<HelloWorldModel> CreateAsync(HelloWorldModel helloWorld)
{
if (!ValidHelloWorlds.Contains(helloWorld?.Message))
{
throw new InvalidException(nameof(HelloWorldModel));
}
var created = await _repository.CreateAsync(Mapper.Map<Infrastructure.HelloWorld>(helloWorld));
return Mapper.Map<HelloWorldModel>(created);
}
public async Task<IEnumerable<HelloWorldModel>> GetAllAsync()
{
var result = await _repository.GetAllAsync();
return Mapper.Map<IEnumerable<HelloWorldModel>>(result);
}
}
}
| 30.363636
| 121
| 0.638473
|
[
"MIT"
] |
superchar/hello-world-app
|
HelloWorld.Domain/HelloWorldService.cs
| 1,338
|
C#
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
/**
* mostly following: http://rbwhitaker.wikidot.com/monogame-texture-atlases-1
*/
namespace TileMapAndMoveCharacter
{
class Character
{
public Texture2D Texture { get; set; }
public int Height { get; set; }
public int Width { get; set; }
public Rectangle Rectangle { get; set; }
private int currentFrame;
private int totalFrames;
public Vector2 Location { get; set; }
public int InternalFrameCounter { get; set; }
public enum Directions { NORTH, EAST, SOUTH, WEST}
public Directions Facing { get; set; }
private bool CharacterMoving { get; set; }
private int movingSteps = 0;
public Character(Texture2D Texture)
{
this.Texture = Texture;
Height = 36;
Width = 32;
currentFrame = 0;
totalFrames = 3;
Location = new Vector2(320, 240);
Facing = Directions.SOUTH;
CharacterMoving = false;
}
public void Update()
{
InternalFrameCounter++;
if (InternalFrameCounter % 12 == 0) {
currentFrame++;
if (CharacterMoving && movingSteps < 3) {
Location = GetNewLocation(Facing);
movingSteps++;
}
if (movingSteps >= 3) {
movingSteps = 0;
CharacterMoving = false;
}
if (currentFrame == totalFrames) {
currentFrame = 0;
}
}
if (InternalFrameCounter > 60) {
InternalFrameCounter = 0;
}
}
public void Draw(SpriteBatch spriteBatch)
{
int row;
switch (Facing) { // This assumes the vertical order in the spritesheet this project comes with.
case Directions.NORTH:
row = 0;
break;
case Directions.EAST:
row = 1;
break;
case Directions.SOUTH:
row = 2;
break;
case Directions.WEST:
row = 3;
break;
default:
row = 0;
break;
}
int column = currentFrame;
Rectangle sourceRectangle = new Rectangle(Width * column, Height * row, 32, 36);
Rectangle destinationRectangle;
destinationRectangle = new Rectangle((int)Location.X, (int)Location.Y, 32, 36);
spriteBatch.Begin();
spriteBatch.Draw(Texture, destinationRectangle, sourceRectangle, Color.White);
spriteBatch.End();
}
public void MoveCharacter(Directions direction)
{
if (!CharacterMoving) {
Facing = direction;
CharacterMoving = true;
}
}
public Vector2 GetNewLocation(Directions direction)
{
Vector2 newLocation;
switch (direction) {
case Directions.NORTH:
newLocation = new Vector2(Location.X, Location.Y - 8);
break;
case Directions.EAST:
newLocation = new Vector2(Location.X + 8, Location.Y);
break;
case Directions.SOUTH:
newLocation = new Vector2(Location.X, Location.Y + 8);
break;
case Directions.WEST:
newLocation = new Vector2(Location.X - 8, Location.Y);
break;
default:
newLocation = new Vector2(Location.X + 8, Location.Y);
break;
}
return newLocation;
}
}
}
| 34.824561
| 108
| 0.483879
|
[
"MIT"
] |
klnsem/TileMapAndMoveCharacter
|
TileMapAndMoveCharacter/Character.cs
| 3,972
|
C#
|
namespace Qsi.MongoDB.Internal.Nodes;
internal class TemplateElementNode : BaseNode, INode
{
public bool Tail { get; set; }
public TemplateElementValue Value { get; set; }
}
// TODO: Implicit casting
internal class TemplateElementValue
{
public string Cooked { get; set; }
public string Raw { get; set; }
}
| 19.294118
| 52
| 0.704268
|
[
"MIT"
] |
ScriptBox99/chequer-qsi
|
Qsi.MongoDB/Internal/Nodes/TemplateElementNode.cs
| 330
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace System.Collections.Generic
{
/// <summary>
/// Enume for sort a <see cref="List{T}"/> using sa <see cref="KeyValuePair{TKey, TVlaue}"/>
/// </summary>
public enum ListKeyValueSort
{
/// <summary></summary>
OnlyKeys,
/// <summary></summary>
OnlyValues,
/// <summary></summary>
KeysAndValues,
/// <summary></summary>
ValuesAndKeys
}
/// <summary>
/// Static class to extend <see cref="List{T}"/>
/// </summary>
static public class ListExtension
{
static ListExtension() { }
/// <summary></summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TVlaue"></typeparam>
/// <param name="list"></param>
static public void Sort<TKey, TVlaue>(this List<KeyValuePair<TKey, TVlaue>> list)
{
list.Sort(Comparator<TKey, TVlaue>.Default);
}
/// <summary></summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TVlaue"></typeparam>
/// <param name="list"></param>
/// <param name="KeyValueSort"></param>
static public void Sort<TKey, TVlaue>(this List<KeyValuePair<TKey, TVlaue>> list, ListKeyValueSort KeyValueSort)
{
switch (KeyValueSort)
{
case ListKeyValueSort.OnlyKeys:
list.Sort(Comparator<TKey, TVlaue>.DefaultOnlyKeys);
break;
case ListKeyValueSort.OnlyValues:
list.Sort(Comparator<TKey, TVlaue>.DefaultOnlyValues);
break;
case ListKeyValueSort.KeysAndValues:
list.Sort(Comparator<TKey, TVlaue>.DefaultKeysAndValues);
break;
case ListKeyValueSort.ValuesAndKeys:
list.Sort(Comparator<TKey, TVlaue>.DefaultValuesAndKeys);
break;
default:
list.Sort(Comparator<TKey, TVlaue>.Default);
break;
}
}
/// <summary></summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TVlaue"></typeparam>
/// <param name="list"></param>
/// <param name="key"></param>
/// <param name="value"></param>
static public void Add<TKey, TVlaue>(this List<KeyValuePair<TKey, TVlaue>> list, TKey key, TVlaue value)
{
list.Add(new KeyValuePair<TKey, TVlaue>(key, value));
}
}
}
| 34.893333
| 120
| 0.538021
|
[
"MIT"
] |
un-pogaz/ChromatikTool
|
Chromatik/Collections/ListExtension.cs
| 2,619
|
C#
|
using CryptoExchange.Net.Converters;
using Newtonsoft.Json;
using System;
namespace Switcheo.Net.Objects
{
/// <summary>
/// Candlestick information for pair
/// </summary>
public class SwitcheoCandlestick
{
/// <summary>
/// The time this candlestick opened
/// </summary>
[JsonProperty("time")]
[JsonConverter(typeof(TimestampSecondsConverter))]
public DateTime Time { get; set; }
/// <summary>
/// The price at which this candlestick opened
/// </summary>
[JsonProperty("open")]
public decimal Open { get; set; }
/// <summary>
/// The price at which this candlestick closed
/// </summary>
[JsonProperty("close")]
public decimal Close { get; set; }
/// <summary>
/// The highest price in this candlestick
/// </summary>
[JsonProperty("high")]
public decimal High { get; set; }
/// <summary>
/// The lowest price in this candlestick
/// </summary>
[JsonProperty("low")]
public decimal Low { get; set; }
/// <summary>
/// The volume traded during this candlestick
/// </summary>
[JsonProperty("volume")]
public decimal Volume { get; set; }
/// <summary>
/// The quote asset volume traded during this candlestick
/// </summary>
[JsonProperty("quote_volume")]
public decimal QuoteVolume { get; set; }
public override string ToString()
{
return string.Format("{{ Time : {0}, Open : {1}, Close : {2}, High : {3}, Low : {4}, Volume : {5}, QuoteVolume : {6} }}",
this.Time, this.Open, this.Close, this.High, this.Low, this.Volume, this.QuoteVolume);
}
}
}
| 29.868852
| 133
| 0.547201
|
[
"MIT"
] |
Switcheo/Switcheo.Net
|
Switcheo.Net/Objects/SwitcheoCandlestick.cs
| 1,824
|
C#
|
using DevelopmentInProgress.Socket.Client;
using DevelopmentInProgress.TradeView.Wpf.Common.Cache;
using DevelopmentInProgress.TradeView.Wpf.Common.Events;
using DevelopmentInProgress.TradeView.Wpf.Common.Extensions;
using DevelopmentInProgress.TradeView.Wpf.Common.Manager;
using DevelopmentInProgress.TradeView.Wpf.Common.Model;
using DevelopmentInProgress.TradeView.Wpf.Common.Services;
using DevelopmentInProgress.TradeView.Wpf.Common.ViewModel;
using DevelopmentInProgress.TradeView.Wpf.Controls.Messaging;
using DevelopmentInProgress.TradeView.Wpf.Host.Controller.Context;
using DevelopmentInProgress.TradeView.Wpf.Host.Controller.ViewModel;
using DevelopmentInProgress.TradeView.Wpf.Strategies.Enums;
using DevelopmentInProgress.TradeView.Wpf.Strategies.Events;
using DevelopmentInProgress.TradeView.Wpf.Strategies.Utility;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Net.WebSockets;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using CoreModel = DevelopmentInProgress.TradeView.Core.Model;
using CoreStrategy = DevelopmentInProgress.TradeView.Core.TradeStrategy;
namespace DevelopmentInProgress.TradeView.Wpf.Strategies.ViewModel
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types")]
public class StrategyRunnerViewModel : DocumentViewModel
{
private readonly IStrategyService strategyService;
private readonly IServerMonitorCache serverMonitorCache;
private readonly IStrategyAssemblyManager strategyAssemblyManager;
private readonly IHttpClientManager httpClientManager;
private readonly SemaphoreSlim commandVisibilitySemaphoreSlim = new SemaphoreSlim(1, 1);
private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
private Strategy strategy;
private ServerMonitor selectedServer;
private List<Symbol> symbols;
private bool canRun;
private bool canMonitor;
private bool isConnected;
private bool isConnecting;
private bool disposed;
private SocketClient socketClient;
private ObservableCollection<ServerMonitor> servers;
private AccountViewModel accountViewModel;
private SymbolsViewModel symbolsViewModel;
private StrategyParametersViewModel strategyParametersViewModel;
private StrategyDisplayViewModelBase StrategyDisplayViewModel;
private IDisposable symbolsSubscription;
private IDisposable accountSubscription;
private IDisposable parametersSubscription;
private IDisposable strategySubscription;
private IDisposable serverMonitorCacheSubscription;
public StrategyRunnerViewModel(
ViewModelContext viewModelContext,
AccountViewModel accountViewModel,
SymbolsViewModel symbolsViewModel,
StrategyParametersViewModel strategyParametersViewModel,
IStrategyService strategyService,
IServerMonitorCache serverMonitorCache,
IStrategyAssemblyManager strategyAssemblyManager,
IHttpClientManager httpClientManager)
: base(viewModelContext)
{
this.strategyService = strategyService;
this.serverMonitorCache = serverMonitorCache;
this.strategyAssemblyManager = strategyAssemblyManager;
this.httpClientManager = httpClientManager;
AccountViewModel = accountViewModel;
SymbolsViewModel = symbolsViewModel;
StrategyParametersViewModel = strategyParametersViewModel;
CanRun = false;
CanMonitor = false;
IsConnected = false;
IsConnecting = false;
Notifications = new ObservableCollection<Message>();
RunCommand = new ViewModelCommand(RunStrategy);
MonitorCommand = new ViewModelCommand(MonitorStrategy);
DisconnectCommand = new ViewModelCommand(Disconnect);
StopCommand = new ViewModelCommand(StopStrategy);
ClearNotificationsCommand = new ViewModelCommand(ClearNotifications);
ObserveSymbols();
ObserveAccount();
ObserveParameters();
ObserveServerMonitorCache();
}
public event EventHandler<StrategyDisplayEventArgs> OnStrategyDisplay;
public ICommand RunCommand { get; set; }
public ICommand MonitorCommand { get; set; }
public ICommand DisconnectCommand { get; set; }
public ICommand StopCommand { get; set; }
public ICommand ClearNotificationsCommand { get; set; }
public ObservableCollection<Message> Notifications { get; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "Servers must point to cached collection.")]
public ObservableCollection<ServerMonitor> Servers
{
get { return servers; }
set
{
if (servers != value)
{
servers = value;
OnPropertyChanged(nameof(Servers));
}
}
}
public ServerMonitor SelectedServer
{
get { return selectedServer; }
set
{
if (selectedServer != value)
{
selectedServer = value;
ResetCommandVisibility();
OnPropertyChanged(nameof(SelectedServer));
}
}
}
public AccountViewModel AccountViewModel
{
get { return accountViewModel; }
private set
{
if (accountViewModel != value)
{
accountViewModel = value;
OnPropertyChanged(nameof(AccountViewModel));
}
}
}
public SymbolsViewModel SymbolsViewModel
{
get { return symbolsViewModel; }
private set
{
if (symbolsViewModel != value)
{
symbolsViewModel = value;
OnPropertyChanged(nameof(SymbolsViewModel));
}
}
}
public StrategyParametersViewModel StrategyParametersViewModel
{
get { return strategyParametersViewModel; }
private set
{
if (strategyParametersViewModel != value)
{
strategyParametersViewModel = value;
OnPropertyChanged(nameof(StrategyParametersViewModel));
}
}
}
public bool CanRun
{
get { return canRun; }
set
{
if (canRun != value)
{
canRun = value;
OnPropertyChanged(nameof(CanRun));
}
}
}
public bool CanMonitor
{
get { return canMonitor; }
set
{
if (canMonitor != value)
{
canMonitor = value;
OnPropertyChanged(nameof(CanMonitor));
}
}
}
public bool IsConnected
{
get { return isConnected; }
set
{
if (isConnected != value)
{
isConnected = value;
if(StrategyParametersViewModel != null)
{
StrategyParametersViewModel.CanPushParameters = isConnected;
}
OnPropertyChanged(nameof(IsConnected));
}
}
}
public bool IsConnecting
{
get { return isConnecting; }
set
{
if (isConnecting != value)
{
isConnecting = value;
OnPropertyChanged(nameof(IsConnecting));
}
}
}
public Strategy Strategy
{
get { return strategy; }
set
{
if (strategy != value)
{
strategy = value;
OnPropertyChanged(nameof(Strategy));
}
}
}
protected async override void OnPublished(object data)
{
IsBusy = true;
try
{
Strategy = await strategyService.GetStrategy(Title).ConfigureAwait(true);
strategyAssemblyManager.Activate(Strategy, ViewModelContext.UiDispatcher, Logger);
StrategyDisplayViewModel = (StrategyDisplayViewModelBase)strategyAssemblyManager.StrategyDisplayViewModel;
ObserveStrategy();
RaiseStrategyDisplayEvent();
AccountViewModel.Dispatcher = ViewModelContext.UiDispatcher;
SymbolsViewModel.Dispatcher = ViewModelContext.UiDispatcher;
StrategyParametersViewModel.Dispatcher = ViewModelContext.UiDispatcher;
StrategyParametersViewModel.Strategy = Strategy;
var account = new Account(new CoreModel.AccountInfo { User = new CoreModel.User() });
if (Strategy.StrategySubscriptions.Any())
{
var strategySubscription = Strategy.StrategySubscriptions.First();
account.AccountName = strategySubscription.AccountName;
account.ApiKey = strategySubscription.ApiKey;
account.ApiSecret = strategySubscription.SecretKey;
account.ApiPassPhrase = strategySubscription.ApiPassPhrase;
account.Exchange = strategySubscription.Exchange;
}
GetServerMonitors();
await Task.WhenAll(SymbolsViewModel.GetStrategySymbols(Strategy), AccountViewModel.Login(account)).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.Log($"OnPublished {ex.Message}", Prism.Logging.Category.Exception, Prism.Logging.Priority.High);
ShowMessage(new Message { MessageType = MessageType.Error, Text = $"Strategy load error. Check configuration. {ex.Message}" });
}
finally
{
IsBusy = false;
}
}
private void GetServerMonitors()
{
try
{
Servers = serverMonitorCache.GetServerMonitors();
}
catch (Exception ex)
{
Logger.Log($"GetServerMonitors {ex.Message}", Prism.Logging.Category.Exception, Prism.Logging.Priority.High);
ShowMessage(new Message { MessageType = MessageType.Error, Text = $"Server load error. {ex.Message}" });
}
}
private async void RunStrategy(object param)
{
await RunAsync().ConfigureAwait(false);
}
private async void MonitorStrategy(object param)
{
await MonitorAsync().ConfigureAwait(false);
}
private async void Disconnect(object param)
{
await SetCommandVisibility(StrategyRunnerCommandVisibility.Connecting).ConfigureAwait(false);
await DisconnectSocketAsync().ConfigureAwait(false);
await SetCommandVisibility(StrategyRunnerCommandVisibility.ServerAvailable).ConfigureAwait(false);
}
private async void StopStrategy(object param)
{
await SetCommandVisibility(StrategyRunnerCommandVisibility.Connecting).ConfigureAwait(false);
var strategyParameters = new CoreStrategy.StrategyParameters { StrategyName = Strategy.Name };
var strategyParametersJson = JsonConvert.SerializeObject(strategyParameters);
await StopAsync(strategyParametersJson).ConfigureAwait(false);
await SetCommandVisibility(StrategyRunnerCommandVisibility.ServerAvailable).ConfigureAwait(false);
}
private void ClearNotifications(object param)
{
Notifications.Clear();
}
protected async override void OnDisposing()
{
if (disposed)
{
return;
}
await DisconnectSocketAsync(false).ConfigureAwait(true);
symbolsSubscription.Dispose();
accountSubscription.Dispose();
parametersSubscription.Dispose();
AccountViewModel.Dispose();
SymbolsViewModel.Dispose();
StrategyParametersViewModel.Dispose();
serverMonitorCacheSubscription.Dispose();
if (StrategyDisplayViewModel != null)
{
strategySubscription.Dispose();
StrategyDisplayViewModel.Dispose();
}
strategyAssemblyManager.Dispose();
commandVisibilitySemaphoreSlim.Dispose();
disposed = true;
}
private async Task DisconnectSocketAsync(bool writeNotification = true)
{
if (socketClient != null)
{
try
{
if (socketClient.State.Equals(WebSocketState.Open))
{
var clientMessage = new Socket.Messages.Message
{
SenderConnectionId = strategyAssemblyManager.Id,
Data = strategy.Name,
MessageType = Socket.Messages.MessageType.UnsubscribeFromChannel
};
await socketClient.SendMessageAsync(clientMessage).ConfigureAwait(true);
NotificationsAdd(new Message { MessageType = MessageType.Info, Text = $"{strategy.Name} disconnected" });
}
await DisposeSocketAsync(writeNotification).ConfigureAwait(true);
}
catch (Exception ex)
{
Logger.Log($"DisconnectSocketAsync {ex.Message}", Prism.Logging.Category.Exception, Prism.Logging.Priority.High);
if (writeNotification)
{
ViewModelContext.UiDispatcher.Invoke(() =>
{
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = $"Disconnect - {ex.Message}", TextVerbose = ex.ToString() });
});
}
}
}
}
private async Task<bool> IsStrategyRunningAsync()
{
HttpResponseMessage response = null;
try
{
var strategyParameters = new CoreStrategy.StrategyParameters { StrategyName = Strategy.Name };
var strategyParametersJson = JsonConvert.SerializeObject(strategyParameters);
response = await CoreStrategy.StrategyRunnerClient.PostAsync(httpClientManager.HttpClientInstance, new Uri($"{SelectedServer.Uri}isstrategyrunning"), strategyParametersJson, cancellationTokenSource.Token).ConfigureAwait(false);
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
return content == "YES";
}
else
{
ViewModelContext.UiDispatcher.Invoke(() =>
{
NotificationsAdd(
new Message
{
MessageType = response.StatusCode == System.Net.HttpStatusCode.OK ? MessageType.Info : MessageType.Error,
Text = response.StatusCode.ToString(),
TextVerbose = JsonConvert.SerializeObject(content, Formatting.Indented)
});
});
}
}
catch (Exception ex)
{
Logger.Log($"IsStrategyRunningAsync {ex}", Prism.Logging.Category.Exception, Prism.Logging.Priority.High);
}
finally
{
response.Content.Dispose();
response.Dispose();
}
return false;
}
private async Task DisposeSocketAsync(bool writeNotification = true)
{
try
{
if (socketClient != null)
{
await socketClient.DisposeAsync().ConfigureAwait(false);
}
}
catch (Exception ex)
{
Logger.Log($"DisposeSocketAsync {ex.Message}", Prism.Logging.Category.Exception, Prism.Logging.Priority.High);
if (writeNotification)
{
ViewModelContext.UiDispatcher.Invoke(() =>
{
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = $"Disconnect - {ex.Message}", TextVerbose = ex.ToString() });
});
}
}
finally
{
socketClient = null;
IsConnected = false;
}
}
private async Task RunAsync()
{
HttpResponseMessage response = null;
try
{
var result = await MonitorAsync(true).ConfigureAwait(false);
if (result)
{
var interfaceStrategy = Strategy.ToCoreStrategy();
interfaceStrategy.StartedBy = Environment.UserName;
var jsonContent = JsonConvert.SerializeObject(interfaceStrategy);
var dependencies = strategy.Dependencies.Select(d => d.File);
response = await CoreStrategy.StrategyRunnerClient.PostAsync(httpClientManager.HttpClientInstance, new Uri($"{SelectedServer.Uri}runstrategy"), jsonContent, dependencies, cancellationTokenSource.Token).ConfigureAwait(false);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
await SetCommandVisibility(StrategyRunnerCommandVisibility.ServerUnavailable).ConfigureAwait(false);
await DisconnectSocketAsync().ConfigureAwait(false);
}
else
{
await SetCommandVisibility(StrategyRunnerCommandVisibility.Connected).ConfigureAwait(false);
}
var content = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync().ConfigureAwait(false));
ViewModelContext.UiDispatcher.Invoke(() =>
{
NotificationsAdd(
new Message
{
MessageType = response.StatusCode == System.Net.HttpStatusCode.OK ? MessageType.Info : MessageType.Error,
Text = response.StatusCode.ToString(),
TextVerbose = JsonConvert.SerializeObject(content, Formatting.Indented)
});
});
}
}
catch (Exception ex)
{
Logger.Log($"RunAsync {ex.Message}", Prism.Logging.Category.Exception, Prism.Logging.Priority.High);
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = $"Run - {ex.Message}", TextVerbose = ex.ToString() });
await SetCommandVisibility(StrategyRunnerCommandVisibility.ServerUnavailable).ConfigureAwait(false);
await DisconnectSocketAsync().ConfigureAwait(false);
}
finally
{
response.Content.Dispose();
response.Dispose();
}
}
private async Task Update(string strategyParameters)
{
HttpResponseMessage response = null;
try
{
if (!IsConnected)
{
NotificationsAdd(new Message { MessageType = MessageType.Warn, Text = $"Not connected to running strategy"});
return;
}
response = await CoreStrategy.StrategyRunnerClient.PostAsync(httpClientManager.HttpClientInstance, new Uri($"{SelectedServer.Uri}updatestrategy"), strategyParameters, cancellationTokenSource.Token).ConfigureAwait(false);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
await SetCommandVisibility(StrategyRunnerCommandVisibility.ServerUnavailable).ConfigureAwait(false);
await DisconnectSocketAsync().ConfigureAwait(false);
}
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
var content = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync().ConfigureAwait(false));
ViewModelContext.UiDispatcher.Invoke(() =>
{
NotificationsAdd(
new Message
{
MessageType = response.StatusCode == System.Net.HttpStatusCode.OK ? MessageType.Info : MessageType.Error,
Text = response.StatusCode.ToString(),
TextVerbose = JsonConvert.SerializeObject(content, Formatting.Indented)
});
});
}
}
catch (Exception ex)
{
Logger.Log($"RunAsync {ex.Message}", Prism.Logging.Category.Exception, Prism.Logging.Priority.High);
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = $"Update - {ex.Message}", TextVerbose = ex.ToString() });
await SetCommandVisibility(StrategyRunnerCommandVisibility.ServerUnavailable).ConfigureAwait(false);
await DisconnectSocketAsync().ConfigureAwait(false);
}
finally
{
response?.Content.Dispose();
response?.Dispose();
}
}
private async Task StopAsync(string strategyParameters)
{
HttpResponseMessage response = null;
try
{
response = await CoreStrategy.StrategyRunnerClient.PostAsync(httpClientManager.HttpClientInstance, new Uri($"{SelectedServer.Uri}stopstrategy"), strategyParameters, cancellationTokenSource.Token).ConfigureAwait(false);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
var content = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync().ConfigureAwait(false));
ViewModelContext.UiDispatcher.Invoke(() =>
{
NotificationsAdd(
new Message
{
MessageType = response.StatusCode == System.Net.HttpStatusCode.OK ? MessageType.Info : MessageType.Error,
Text = response.StatusCode.ToString(),
TextVerbose = JsonConvert.SerializeObject(content, Formatting.Indented)
});
});
await DisconnectSocketAsync().ConfigureAwait(false);
}
else
{
await Task.Delay(500).ConfigureAwait(false);
}
}
catch (Exception ex)
{
Logger.Log($"StopAsync {ex.Message}", Prism.Logging.Category.Exception, Prism.Logging.Priority.High);
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = $"Stop - {ex.Message}", TextVerbose = ex.ToString() });
await SetCommandVisibility(StrategyRunnerCommandVisibility.ServerUnavailable).ConfigureAwait(false);
await DisconnectSocketAsync().ConfigureAwait(false);
}
finally
{
response?.Content.Dispose();
response?.Dispose();
}
}
private async Task<bool> MonitorAsync(bool isForRun = false)
{
if(IsConnected)
{
NotificationsAdd(new Message { MessageType = MessageType.Info, Text = $"Already connected to strategy", Timestamp = DateTime.Now });
return IsConnected;
}
await SetCommandVisibility(StrategyRunnerCommandVisibility.Connecting).ConfigureAwait(true);
Notifications.Clear();
if(string.IsNullOrWhiteSpace(strategyAssemblyManager.Id))
{
throw new Exception("StrategyAssemblyManager has not loaded the strategy assemblies.");
}
socketClient = new SocketClient(new Uri(SelectedServer.Uri, "notificationhub"), strategyAssemblyManager.Id);
socketClient.On("Connected", message =>
{
ViewModelContext.UiDispatcher.Invoke(() =>
{
NotificationsAdd(new Message { MessageType = MessageType.Info, Text = $"Connected - {message}", Timestamp = DateTime.Now });
});
});
socketClient.On("Notification", async (message) =>
{
await ViewModelContext.UiDispatcher.Invoke(async () =>
{
await OnStrategyNotificationAsync(message).ConfigureAwait(false);
}).ConfigureAwait(false);
});
socketClient.On("Trade", (message) =>
{
ViewModelContext.UiDispatcher.Invoke(async () =>
{
await OnTradeNotificationAsync(message).ConfigureAwait(false);
});
});
socketClient.On("OrderBook", (message) =>
{
ViewModelContext.UiDispatcher.Invoke(async () =>
{
await OnOrderBookNotificationAsync(message).ConfigureAwait(false);
});
});
socketClient.On("AccountInfo", (message) =>
{
ViewModelContext.UiDispatcher.Invoke(() =>
{
OnAccountNotification(message);
});
});
socketClient.On("Candlesticks", (message) =>
{
ViewModelContext.UiDispatcher.Invoke(async () =>
{
await OnCandlesticksNotificationAsync(message).ConfigureAwait(false);
});
});
socketClient.On("ParameterUpdate", (message) =>
{
ViewModelContext.UiDispatcher.Invoke(async () =>
{
await OnParameterUpdateNotificationAsync(message).ConfigureAwait(false);
});
});
socketClient.Closed += async (sender, args) =>
{
await ViewModelContext.UiDispatcher.Invoke(async () =>
{
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = $"socketClient.Closed", TextVerbose = args.ToString(), Timestamp = DateTime.Now });
await DisposeSocketAsync(false).ConfigureAwait(false);
}).ConfigureAwait(false);
};
socketClient.Error += async (sender, args) =>
{
var ex = args as Exception;
if(ex.InnerException is TaskCanceledException)
{
return;
}
await ViewModelContext.UiDispatcher.Invoke(async () =>
{
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = $"{args.Message}", TextVerbose = args.ToString(), Timestamp = DateTime.Now });
await DisposeSocketAsync(false).ConfigureAwait(false);
}).ConfigureAwait(false);
};
try
{
await socketClient.StartAsync(strategy.Name).ConfigureAwait(true);
StrategyDisplayViewModel.IsActive = true;
if (!isForRun)
{
await SetCommandVisibility(StrategyRunnerCommandVisibility.Connected).ConfigureAwait(false);
}
return true;
}
catch (Exception ex)
{
Logger.Log($"MonitorAsync {ex}", Prism.Logging.Category.Exception, Prism.Logging.Priority.High);
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = $"Monitor - {ex.Message}", TextVerbose=ex.ToString(), Timestamp = DateTime.Now });
await SetCommandVisibility(StrategyRunnerCommandVisibility.ServerUnavailable).ConfigureAwait(false);
await DisconnectSocketAsync().ConfigureAwait(false);
return false;
}
}
private async Task OnStrategyNotificationAsync(Socket.Messages.Message message)
{
try
{
var strategyNotifications = JsonConvert.DeserializeObject<List<TradeView.Core.TradeStrategy.StrategyNotification>>(message.Data);
foreach (var notification in strategyNotifications)
{
NotificationsAdd(notification.GetMessage());
if(notification.NotificationLevel.Equals(TradeView.Core.TradeStrategy.NotificationLevel.DisconnectClient))
{
await DisconnectSocketAsync().ConfigureAwait(false);
}
}
}
catch (Exception ex)
{
Logger.Log($"OnStrategyNotification {ex}", Prism.Logging.Category.Exception, Prism.Logging.Priority.High);
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = $"OnStrategyNotification - {ex.Message}", TextVerbose = ex.ToString() });
}
}
private async Task OnTradeNotificationAsync(Socket.Messages.Message message)
{
try
{
var strategyNotifications = JsonConvert.DeserializeObject<List<TradeView.Core.TradeStrategy.StrategyNotification>>(message.Data);
var orderedStrategyNotifications = strategyNotifications.OrderBy(n => n.Timestamp).ToList();
await StrategyDisplayViewModel.TradeNotificationsAsync(orderedStrategyNotifications).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.Log($"OnTradeNotification {ex}", Prism.Logging.Category.Exception, Prism.Logging.Priority.High);
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = $"OnTradeNotification - {ex.Message}", TextVerbose = ex.ToString() });
}
}
private async Task OnCandlesticksNotificationAsync(Socket.Messages.Message message)
{
try
{
var strategyNotifications = JsonConvert.DeserializeObject<List<TradeView.Core.TradeStrategy.StrategyNotification>>(message.Data);
var orderedStrategyNotifications = strategyNotifications.OrderBy(n => n.Timestamp).ToList();
await StrategyDisplayViewModel.CandlestickNotificationsAsync(orderedStrategyNotifications).ConfigureAwait(false);
}
catch(Exception ex)
{
Logger.Log($"OnCandlesticksNotification {ex}", Prism.Logging.Category.Exception, Prism.Logging.Priority.High);
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = $"OnCandlesticksNotification - {ex.Message}", TextVerbose = ex.ToString() });
}
}
private async Task OnParameterUpdateNotificationAsync(Socket.Messages.Message message)
{
try
{
var strategyNotifications = JsonConvert.DeserializeObject<List<TradeView.Core.TradeStrategy.StrategyNotification>>(message.Data);
var latestStrategyNotification = strategyNotifications.OrderBy(n => n.Timestamp).Last();
Strategy.Parameters = latestStrategyNotification.Message;
}
catch (Exception ex)
{
Logger.Log($"OnParameterUpdateNotificationAsync {ex}", Prism.Logging.Category.Exception, Prism.Logging.Priority.High);
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = $"OnParameterUpdateNotificationAsync - {ex.Message}", TextVerbose = ex.ToString() });
}
await Task.FromResult<object>(null).ConfigureAwait(false);
}
private async Task OnOrderBookNotificationAsync(Socket.Messages.Message message)
{
try
{
var strategyNotifications = JsonConvert.DeserializeObject<List<TradeView.Core.TradeStrategy.StrategyNotification>>(message.Data);
var orderedStrategyNotifications = strategyNotifications.OrderBy(n => n.Timestamp).ToList();
await StrategyDisplayViewModel.OrderNotificationsAsync(orderedStrategyNotifications).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.Log($"OnOrderBookNotification {ex}", Prism.Logging.Category.Exception, Prism.Logging.Priority.High);
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = $"OnOrderBookNotification - {ex.Message}", TextVerbose = ex.ToString() });
}
}
private void OnAccountNotification(Socket.Messages.Message message)
{
try
{
var accountBalances = AccountViewModel.AccountBalancesViewModel.Account.AccountInfo.Balances.ToList();
}
catch (Exception ex)
{
Logger.Log($"{message.MethodName} {ex}", Prism.Logging.Category.Exception, Prism.Logging.Priority.High);
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = $"OnAccountNotification - {ex.Message}", TextVerbose = ex.ToString() });
}
}
private void ObserveSymbols()
{
var symbolsObservable = Observable.FromEventPattern<StrategySymbolsEventArgs>(
eventHandler => SymbolsViewModel.OnSymbolsNotification += eventHandler,
eventHandler => SymbolsViewModel.OnSymbolsNotification -= eventHandler)
.Select(eventPattern => eventPattern.EventArgs);
symbolsSubscription = symbolsObservable.Subscribe(args =>
{
if (args.HasException)
{
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = args.Message, TextVerbose = args.Exception.ToString() });
}
else if (string.IsNullOrWhiteSpace(args.Message) && args.Value.Any())
{
symbols = args.Value;
StrategyDisplayViewModel.Symbols.AddRange(symbols);
}
else if (!string.IsNullOrWhiteSpace(args.Message))
{
NotificationsAdd(new Message { MessageType = MessageType.Info, Text = args.Message });
}
});
}
private void ObserveAccount()
{
var accountObservable = Observable.FromEventPattern<AccountEventArgs>(
eventHandler => AccountViewModel.OnAccountNotification += eventHandler,
eventHandler => AccountViewModel.OnAccountNotification -= eventHandler)
.Select(eventPattern => eventPattern.EventArgs);
accountSubscription = accountObservable.Subscribe(args =>
{
if (args.HasException)
{
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = args.Message, TextVerbose = args.Exception.ToString() });
}
else if (!string.IsNullOrWhiteSpace(args.Message))
{
NotificationsAdd(new Message { MessageType = MessageType.Info, Text = args.Message });
}
});
}
private void ObserveParameters()
{
var parametersObservable = Observable.FromEventPattern<StrategyEventArgs>(
eventHandler => StrategyParametersViewModel.OnStrategyParametersNotification += eventHandler,
eventHandler => StrategyParametersViewModel.OnStrategyParametersNotification -= eventHandler)
.Select(eventPattern => eventPattern.EventArgs);
parametersSubscription = parametersObservable.Subscribe(async args =>
{
if (args.HasException)
{
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = args.Message, TextVerbose = args.Exception.ToString() });
}
else
{
if (!string.IsNullOrWhiteSpace(args.Message))
{
NotificationsAdd(new Message { MessageType = MessageType.Info, Text = args.Message });
}
await Update(args.Value.Parameters).ConfigureAwait(false);
}
});
}
private void ObserveStrategy()
{
var strategyObservable = Observable.FromEventPattern<StrategyEventArgs>(
eventHandler => StrategyDisplayViewModel.OnStrategyNotification += eventHandler,
eventHandler => StrategyDisplayViewModel.OnStrategyNotification -= eventHandler)
.Select(eventPattern => eventPattern.EventArgs);
strategySubscription = strategyObservable.Subscribe(args =>
{
if (args.HasException)
{
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = args.Message, TextVerbose = args.Exception.ToString() });
}
else if (!string.IsNullOrWhiteSpace(args.Message))
{
NotificationsAdd(new Message { MessageType = MessageType.Info, Text = args.Message });
}
});
}
private void ObserveServerMonitorCache()
{
var serverMonitorCacheObservable = Observable.FromEventPattern<ServerMonitorCacheEventArgs>(
eventHandler => serverMonitorCache.ServerMonitorCacheNotification += eventHandler,
eventHandler => serverMonitorCache.ServerMonitorCacheNotification -= eventHandler)
.Select(eventPattern => eventPattern.EventArgs);
serverMonitorCacheSubscription = serverMonitorCacheObservable.Subscribe(args =>
{
if (args.HasException)
{
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = args.Message, TextVerbose = args.Exception.ToString() });
}
else if (!string.IsNullOrWhiteSpace(args.Message))
{
if(SelectedServer != null
&& args.Message.StartsWith(SelectedServer.Name, StringComparison.Ordinal))
{
ResetCommandVisibility();
}
}
});
}
private void NotificationsAdd(Message message)
{
var category = message.MessageType switch
{
MessageType.Error => Prism.Logging.Category.Exception,
MessageType.Warn => Prism.Logging.Category.Warn,
_ => Prism.Logging.Category.Info,
};
Logger.Log(message.Text, category, Prism.Logging.Priority.Low);
message.Text = $"{message.Timestamp:dd/MM/yyyy hh:mm:ss.fff tt} {message.Text}";
Notifications.Insert(0, message);
}
private void ResetCommandVisibility()
{
if (SelectedServer != null
&& SelectedServer.IsConnected)
{
SetCommandVisibility(StrategyRunnerCommandVisibility.ServerAvailable).FireAndForget();
return;
}
SetCommandVisibility(StrategyRunnerCommandVisibility.ServerUnavailable).FireAndForget();
}
private async Task SetCommandVisibility(StrategyRunnerCommandVisibility strategyRunnerCommandVisibility)
{
await commandVisibilitySemaphoreSlim.WaitAsync().ConfigureAwait(false);
try
{
if (strategyRunnerCommandVisibility.Equals(StrategyRunnerCommandVisibility.ServerAvailable)
&& ((!IsConnected && !IsConnecting)
|| (!IsConnected && SelectedServer.IsConnected)))
{
CanRun = false;
CanMonitor = false;
IsConnecting = true;
var isRunning = await IsStrategyRunningAsync().ConfigureAwait(false);
CanRun = !isRunning;
CanMonitor = isRunning;
IsConnecting = false;
}
else if (strategyRunnerCommandVisibility.Equals(StrategyRunnerCommandVisibility.Connected)
|| strategyRunnerCommandVisibility.Equals(StrategyRunnerCommandVisibility.Connecting))
{
CanRun = false;
CanMonitor = false;
IsConnecting = strategyRunnerCommandVisibility.Equals(StrategyRunnerCommandVisibility.Connecting);
IsConnected = strategyRunnerCommandVisibility.Equals(StrategyRunnerCommandVisibility.Connected);
}
else if (strategyRunnerCommandVisibility.Equals(StrategyRunnerCommandVisibility.ServerUnavailable))
{
CanRun = false;
CanMonitor = false;
IsConnecting = false;
IsConnected = false;
}
}
catch (Exception ex)
{
Logger.Log($"SetCommandVisibility {ex}", Prism.Logging.Category.Exception, Prism.Logging.Priority.High);
NotificationsAdd(new Message { MessageType = MessageType.Error, Text = $"SetCommandVisibility - {ex.Message}", TextVerbose = ex.ToString() });
await SetCommandVisibility(StrategyRunnerCommandVisibility.ServerUnavailable).ConfigureAwait(false);
}
finally
{
commandVisibilitySemaphoreSlim.Release();
}
}
private void RaiseStrategyDisplayEvent()
{
var onStrategyDisplay = OnStrategyDisplay;
onStrategyDisplay?.Invoke(this, new StrategyDisplayEventArgs { StrategyAssemblyManager = strategyAssemblyManager });
}
}
}
| 40.575926
| 244
| 0.569874
|
[
"Apache-2.0"
] |
CasparsTools/tradeview
|
src/DevelopmentInProgress.TradeView.Wpf.Strategies/ViewModel/StrategyRunnerViewModel.cs
| 43,824
|
C#
|
using RevolutionaryStuff.Core;
using Serilog;
using System.Net.Mail;
namespace GSA.UnliquidatedObligations.Web.Services
{
public class EmailServer : IEmailServer
{
private readonly SmtpClient EmailClient;
private readonly ILogger Log;
public EmailServer(SmtpClient emailClient, ILogger log)
{
EmailClient = emailClient;
Log = log.ForContext<EmailServer>();
}
public void SendEmail(string subject, string body, string bodyHtml, string recipient)
{
Requires.EmailAddress(recipient, nameof(recipient));
bodyHtml = StringHelpers.TrimOrNull(bodyHtml);
var mail = new MailMessage();
mail.To.Add(new MailAddress(recipient));
mail.Subject = subject;
mail.Body = bodyHtml ?? body;
mail.IsBodyHtml = bodyHtml != null;
if (EmailClient.Host == null)
{
Log.Error("Email Server not properly configured. Wont send {Subject} to {Recipient}", subject, recipient);
}
else
{
EmailClient.Send(mail);
}
}
}
}
| 31.282051
| 124
| 0.567213
|
[
"CC0-1.0"
] |
gaybro8777/FM-ULO
|
ULO/src/GSA.UnliquidatedObligations.Web/Services/EmailServer.cs
| 1,222
|
C#
|
using System;
using System.Xml.Serialization;
namespace Aop.Api.Domain
{
/// <summary>
/// InstAccountElementsDTO Data Structure.
/// </summary>
[Serializable]
public class InstAccountElementsDTO : AopObject
{
/// <summary>
/// 请款相关要素
/// </summary>
[XmlElement("advance_elements")]
public AdvanceElementsDTO AdvanceElements { get; set; }
/// <summary>
/// 机构id
/// </summary>
[XmlElement("inst_id")]
public string InstId { get; set; }
/// <summary>
/// 子卡户名
/// </summary>
[XmlElement("sub_account_name")]
public string SubAccountName { get; set; }
/// <summary>
/// 子户类型
/// </summary>
[XmlElement("sub_account_type")]
public string SubAccountType { get; set; }
}
}
| 23.243243
| 63
| 0.539535
|
[
"Apache-2.0"
] |
alipay/alipay-sdk-net
|
AlipaySDKNet.Standard/Domain/InstAccountElementsDTO.cs
| 892
|
C#
|
using CleanArchitecture.Application.Common.Exceptions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace CleanArchitecture.WebUI.Filters;
public class ApiExceptionFilterAttribute : ExceptionFilterAttribute
{
private readonly IDictionary<Type, Action<ExceptionContext>> _exceptionHandlers;
public ApiExceptionFilterAttribute()
{
// Register known exception types and handlers.
_exceptionHandlers = new Dictionary<Type, Action<ExceptionContext>>
{
{ typeof(ValidationException), HandleValidationException },
{ typeof(NotFoundException), HandleNotFoundException },
{ typeof(UnauthorizedAccessException), HandleUnauthorizedAccessException },
{ typeof(ForbiddenAccessException), HandleForbiddenAccessException },
};
}
public override void OnException(ExceptionContext context)
{
HandleException(context);
base.OnException(context);
}
private void HandleException(ExceptionContext context)
{
Type type = context.Exception.GetType();
if (_exceptionHandlers.ContainsKey(type))
{
_exceptionHandlers[type].Invoke(context);
return;
}
if (!context.ModelState.IsValid)
{
HandleInvalidModelStateException(context);
return;
}
HandleUnknownException(context);
}
private void HandleValidationException(ExceptionContext context)
{
var exception = (ValidationException)context.Exception;
var details = new ValidationProblemDetails(exception.Errors)
{
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1"
};
context.Result = new BadRequestObjectResult(details);
context.ExceptionHandled = true;
}
private void HandleInvalidModelStateException(ExceptionContext context)
{
var details = new ValidationProblemDetails(context.ModelState)
{
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1"
};
context.Result = new BadRequestObjectResult(details);
context.ExceptionHandled = true;
}
private void HandleNotFoundException(ExceptionContext context)
{
var exception = (NotFoundException)context.Exception;
var details = new ProblemDetails()
{
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.4",
Title = "The specified resource was not found.",
Detail = exception.Message
};
context.Result = new NotFoundObjectResult(details);
context.ExceptionHandled = true;
}
private void HandleUnauthorizedAccessException(ExceptionContext context)
{
var details = new ProblemDetails
{
Status = StatusCodes.Status401Unauthorized,
Title = "Unauthorized",
Type = "https://tools.ietf.org/html/rfc7235#section-3.1"
};
context.Result = new ObjectResult(details)
{
StatusCode = StatusCodes.Status401Unauthorized
};
context.ExceptionHandled = true;
}
private void HandleForbiddenAccessException(ExceptionContext context)
{
var details = new ProblemDetails
{
Status = StatusCodes.Status403Forbidden,
Title = "Forbidden",
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.3"
};
context.Result = new ObjectResult(details)
{
StatusCode = StatusCodes.Status403Forbidden
};
context.ExceptionHandled = true;
}
private void HandleUnknownException(ExceptionContext context)
{
var details = new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "An error occurred while processing your request.",
Type = "https://tools.ietf.org/html/rfc7231#section-6.6.1"
};
context.Result = new ObjectResult(details)
{
StatusCode = StatusCodes.Status500InternalServerError
};
context.ExceptionHandled = true;
}
}
| 29.41958
| 91
| 0.639648
|
[
"MIT"
] |
AamilShohail/Clean-Architecture-
|
src/WebUI/Filters/ApiExceptionFilterAttribute.cs
| 4,209
|
C#
|
using System;
using System.Collections.Generic;
using System.Net.Security;
using System.Security.Authentication;
using StackExchange.Redis.Extensions.Core.Abstractions;
using StackExchange.Redis.Extensions.Core.Implementations;
using StackExchange.Redis.Extensions.Core.Models;
using StackExchange.Redis.Profiling;
namespace StackExchange.Redis.Extensions.Core.Configuration
{
/// <summary>
/// The redis configuration
/// </summary>
public class RedisConfiguration
{
private ConfigurationOptions options;
private string keyPrefix;
private string password;
private bool allowAdmin;
private bool ssl;
private int connectTimeout = 5000;
private int syncTimeout = 1000;
private bool abortOnConnectFail;
private int database = 0;
private RedisHost[] hosts;
private ServerEnumerationStrategy serverEnumerationStrategy;
private uint maxValueLength;
private int poolSize = 5;
private string[] excludeCommands;
private string configurationChannel = null;
private string connectionString = null;
private string serviceName = null;
private SslProtocols? sslProtocols = null;
private Func<ProfilingSession> profilingSessionProvider;
/// <summary>
/// A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party; note
/// that this cannot be specified in the configuration-string.
/// </summary>
public event RemoteCertificateValidationCallback CertificateValidation;
/// <summary>
/// Gets or sets the servicename used in case of Sentinel.
/// </summary>
public string ServiceName
{
get => serviceName;
set
{
serviceName = value;
ResetConfigurationOptions();
}
}
/// <summary>
/// Gets a value indicating whether get a boolean value that indicates if the cluster is configured for sentinel or not
/// </summary>
public bool IsSentinelCluster => !string.IsNullOrEmpty(ServiceName);
/// <summary>
/// Gets or sets the connection string. In wins over property configuration.
/// </summary>
public SslProtocols? SslProtocols
{
get => sslProtocols;
set
{
sslProtocols = value;
ResetConfigurationOptions();
}
}
/// <summary>
/// Gets or sets the connection string. In wins over property configuration.
/// </summary>
public string ConnectionString
{
get => connectionString;
set
{
connectionString = value;
ResetConfigurationOptions();
}
}
/// <summary>
/// Gets or sets the channel to use for broadcasting and listening for configuration change notification.
/// </summary>
public string ConfigurationChannel
{
get => configurationChannel;
set
{
configurationChannel = value;
ResetConfigurationOptions();
}
}
/// <summary>
/// Gets or sets the key separation prefix used for all cache entries.
/// </summary>
public string KeyPrefix
{
get => keyPrefix;
set
{
keyPrefix = value;
ResetConfigurationOptions();
}
}
/// <summary>
/// Gets or sets the redis password.
/// </summary>
public string Password
{
get => password;
set
{
password = value;
ResetConfigurationOptions();
}
}
/// <summary>
/// Gets or sets a value indicating whether gets or sets whether admin operations should be allowed.
/// </summary>
public bool AllowAdmin
{
get => allowAdmin;
set
{
allowAdmin = value;
ResetConfigurationOptions();
}
}
/// <summary>
/// Gets or sets a value indicating whether specify if whether the connection should be encrypted.
/// </summary>
public bool Ssl
{
get => ssl;
set
{
ssl = value;
ResetConfigurationOptions();
}
}
/// <summary>
/// Gets or sets the time in milliseconds that should be allowed for connection (defaults to 5 seconds unless SyncTimeout is higher).
/// </summary>
public int ConnectTimeout
{
get => connectTimeout;
set
{
connectTimeout = value;
ResetConfigurationOptions();
}
}
/// <summary>
/// Gets or sets the time in milliseconds that the system should allow for synchronous operations (defaults to 5 seconds).
/// </summary>
public int SyncTimeout
{
get => syncTimeout;
set
{
syncTimeout = value;
ResetConfigurationOptions();
}
}
/// <summary>
/// Gets or sets a value indicating whether gets or sets whether connect/configuration timeouts should be explicitly notified via a TimeoutException.
/// </summary>
public bool AbortOnConnectFail
{
get => abortOnConnectFail;
set
{
abortOnConnectFail = value;
ResetConfigurationOptions();
}
}
/// <summary>
/// Gets or sets database Id.
/// </summary>
public int Database
{
get => database;
set
{
database = value;
ResetConfigurationOptions();
}
}
/// <summary>
/// Gets or sets the host of Redis Servers (The ips or names).
/// </summary>
public RedisHost[] Hosts
{
get => hosts;
set
{
hosts = value;
ResetConfigurationOptions();
}
}
/// <summary>
/// Gets or sets the strategy to use when executing server wide commands.
/// </summary>
public ServerEnumerationStrategy ServerEnumerationStrategy
{
get => serverEnumerationStrategy;
set
{
serverEnumerationStrategy = value;
ResetConfigurationOptions();
}
}
/// <summary>
/// Gets or sets maximal value length which can be set in database.
/// </summary>
public uint MaxValueLength
{
get => maxValueLength;
set
{
maxValueLength = value;
ResetConfigurationOptions();
}
}
/// <summary>
/// Gets or sets redis connections pool size.
/// </summary>
public int PoolSize
{
get => poolSize;
set
{
poolSize = value;
ResetConfigurationOptions();
}
}
/// <summary>
/// Gets or sets exclude commands.
/// </summary>
public string[] ExcludeCommands
{
get => excludeCommands;
set
{
excludeCommands = value;
ResetConfigurationOptions();
}
}
/// <summary>
/// Gets or sets redis Profiler to attach to ConnectionMultiplexer.
/// </summary>
public Func<ProfilingSession> ProfilingSessionProvider
{
get => profilingSessionProvider;
set
{
profilingSessionProvider = value;
ResetConfigurationOptions();
}
}
/// <summary>
/// Gets or sets the factory for <see cref="IStateAwareConnection"/> creation
/// </summary>
/// <returns>>If property is not set, default <see cref="IStateAwareConnection"/> will be resolved</returns>
/// <remarks>
/// Proprerty is optional.
/// Property should be assined by invocation code only once. (We are not doing additional checks in the property itself in order to prevent any possible issues during serialization)
/// </remarks>
public StateAwareConnectionResolver StateAwareConnectionFactory { get; set; } = (cm, logger) => new RedisCacheConnectionPoolManager.StateAwareConnection(cm, logger);
/// <summary>
/// Gets the Redis configuration options
/// </summary>
/// <value>An instanfe of <see cref="ConfigurationOptions" />.</value>
public ConfigurationOptions ConfigurationOptions
{
get
{
if (options == null)
{
ConfigurationOptions newOptions;
if (!string.IsNullOrEmpty(ConnectionString))
{
newOptions = ConfigurationOptions.Parse(ConnectionString);
}
else
{
newOptions = new ConfigurationOptions
{
Ssl = Ssl,
AllowAdmin = AllowAdmin,
Password = Password,
ConnectTimeout = ConnectTimeout,
SyncTimeout = SyncTimeout,
AbortOnConnectFail = AbortOnConnectFail,
ConfigurationChannel = ConfigurationChannel,
SslProtocols = sslProtocols,
ChannelPrefix = KeyPrefix,
};
if (IsSentinelCluster)
{
newOptions.ServiceName = ServiceName;
newOptions.CommandMap = CommandMap.Sentinel;
}
foreach (var redisHost in Hosts)
newOptions.EndPoints.Add(redisHost.Host, redisHost.Port);
}
if (ExcludeCommands != null)
{
newOptions.CommandMap = CommandMap.Create(
new HashSet<string>(ExcludeCommands),
available: false);
}
newOptions.CertificateValidation += CertificateValidation;
options = newOptions;
}
return options;
}
}
private void ResetConfigurationOptions()
{
// this is needed in order to cover this scenario
// https://github.com/imperugo/StackExchange.Redis.Extensions/issues/165
options = null;
}
}
}
| 31.541899
| 193
| 0.510361
|
[
"MIT"
] |
SunGram/StackExchange.Redis.Extensions
|
src/core/StackExchange.Redis.Extensions.Core/Configuration/RedisConfiguration.cs
| 11,294
|
C#
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Shouldly;
using Spect.Net.Assembler.SyntaxTree.Expressions;
using Spect.Net.Assembler.SyntaxTree.Statements;
namespace Spect.Net.Assembler.Test.Parser
{
[TestClass]
public class LoopTests : ParserTestBed
{
[TestMethod]
[DataRow(".endl")]
[DataRow("endl")]
[DataRow(".ENDL")]
[DataRow("ENDL")]
[DataRow(".lend")]
[DataRow("lend")]
[DataRow(".LEND")]
[DataRow("LEND")]
public void EndLoopParsingWorks(string source)
{
// --- Act
var visitor = Parse(source);
// --- Assert
visitor.Compilation.Lines.Count.ShouldBe(1);
visitor.Compilation.Lines[0].ShouldBeOfType<LoopEndStatement>();
}
[TestMethod]
[DataRow(".loop #3")]
[DataRow("loop 123")]
[DataRow(".LOOP #34")]
[DataRow("LOOP %1111")]
public void LoopParsingWorks(string source)
{
// --- Act
var visitor = Parse(source);
// --- Assert
visitor.Compilation.Lines.Count.ShouldBe(1);
var line = visitor.Compilation.Lines[0] as LoopStatement;
line.ShouldNotBeNull();
line.Expression.ShouldBeOfType<LiteralNode>();
}
[TestMethod]
[DataRow(".break")]
[DataRow("break")]
[DataRow(".BREAK")]
[DataRow("BREAK")]
public void BreakParsingWorks(string source)
{
// --- Act
var visitor = Parse(source);
// --- Assert
visitor.Compilation.Lines.Count.ShouldBe(1);
visitor.Compilation.Lines[0].ShouldBeOfType<BreakStatement>();
}
[TestMethod]
[DataRow(".continue")]
[DataRow("continue")]
[DataRow(".CONTINUE")]
[DataRow("CONTINUE")]
public void ContinueParsingWorks(string source)
{
// --- Act
var visitor = Parse(source);
// --- Assert
visitor.Compilation.Lines.Count.ShouldBe(1);
visitor.Compilation.Lines[0].ShouldBeOfType<ContinueStatement>();
}
}
}
| 28.5
| 77
| 0.54206
|
[
"MIT"
] |
Dotneteer/spectnetide
|
Tests/Spect.Net.Assembler.Test/Parser/LoopTests.cs
| 2,225
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace DISample
{
public class HomeController
{
private readonly IHelloService _helloService;
public HomeController(IHelloService helloService)
{
_helloService = helloService ?? throw new ArgumentNullException(nameof(helloService));
}
public string Index(string name)
{
//var helloService = new HelloService();
//return helloService.Greeting(name);
return _helloService.Greeting(name);
}
}
}
| 26.363636
| 98
| 0.643103
|
[
"MIT"
] |
CNinnovation/aspnetcorejun2018
|
foundations/DISample/DISample/HomeController.cs
| 582
|
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.Oci.Identity.Inputs
{
public sealed class AuthenticationPolicyPasswordPolicyArgs : Pulumi.ResourceArgs
{
/// <summary>
/// (Updatable) At least one lower case character required.
/// </summary>
[Input("isLowercaseCharactersRequired")]
public Input<bool>? IsLowercaseCharactersRequired { get; set; }
/// <summary>
/// (Updatable) At least one numeric character required.
/// </summary>
[Input("isNumericCharactersRequired")]
public Input<bool>? IsNumericCharactersRequired { get; set; }
/// <summary>
/// (Updatable) At least one special character required.
/// </summary>
[Input("isSpecialCharactersRequired")]
public Input<bool>? IsSpecialCharactersRequired { get; set; }
/// <summary>
/// (Updatable) At least one uppercase character required.
/// </summary>
[Input("isUppercaseCharactersRequired")]
public Input<bool>? IsUppercaseCharactersRequired { get; set; }
/// <summary>
/// (Updatable) User name is allowed to be part of the password.
/// </summary>
[Input("isUsernameContainmentAllowed")]
public Input<bool>? IsUsernameContainmentAllowed { get; set; }
/// <summary>
/// (Updatable) Minimum password length required.
/// </summary>
[Input("minimumPasswordLength")]
public Input<int>? MinimumPasswordLength { get; set; }
public AuthenticationPolicyPasswordPolicyArgs()
{
}
}
}
| 33.946429
| 88
| 0.635455
|
[
"ECL-2.0",
"Apache-2.0"
] |
EladGabay/pulumi-oci
|
sdk/dotnet/Identity/Inputs/AuthenticationPolicyPasswordPolicyArgs.cs
| 1,901
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BeholderBot.Tasks
{
internal class DistributeOverlords : GameplayTask
{
public override void Execute()
{
//send scouting unless it is dangerous. If it is dangerous, keep near spores
}
}
}
| 18.444444
| 79
| 0.75
|
[
"MIT"
] |
Dmitrii-Naumov/SC2-CSharpe-Starterk
|
BeholderBot/Tasks/DistributeOverlords.cs
| 334
|
C#
|
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Text;
using __m128 = System.Runtime.Intrinsics.Vector128<float>;
using static KleinSharp.Simd;
// ReSharper disable InconsistentNaming
// ReSharper disable ParameterHidesMember
namespace KleinSharp
{
/// <summary>
/// The `Branch` is both a line through the origin and
/// also the principal Branch of the logarithm of a rotor.
/// <br/>
/// It is represented as <c>a e₂₃ + b e₃₁ + c e₁₂</c>
/// <br/>
/// The rotor Branch will be most commonly constructed by taking the
/// logarithm of a normalized rotor. The Branch may then be linearly scaled
/// to adjust the "strength" of the rotor, and subsequently re-exponentiated
/// to create the adjusted rotor.
///
/// !!! example
///
/// Suppose we have a rotor <b>r</b> and we wish to produce a rotor
/// $\sqrt[4]{r}$ which performs a quarter of the rotation produced by
/// $r$. We can construct it like so:
///
/// ```cs
/// Branch b = r.Log();
/// Rotor r_4 = (0.25f * b).Exp();
/// ```
///
/// !!! note
///
/// The Branch of a rotor is technically a `line`, but because there are
/// no translational components, the Branch is given its own type for
/// efficiency.
/// </summary>
/// <remarks>
/// Klein provides three line classes: <see cref="Line"/>, <see cref="Branch"/>, and <see cref="IdealLine"/>.
///
/// The line class represents a full six-coordinate bivector.
///
/// The Branch contains three non-degenerate components (aka, a line through the origin).
///
/// The ideal line represents the line at infinity.
///
/// When the line is created as a meet of two planes or join of two points
/// (or carefully selected Plücker coordinates), it will be a Euclidean line
/// (factorisable as the meet of two vectors).
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
public readonly struct Branch : IEquatable<Branch>
{
public readonly __m128 P1;
/// <summary>
/// Construct the Branch as the following multivector:
/// <br/>
/// <c>a e₂₃ + b e₃₁ + c e₁₂</c>
/// <br/>
/// To convince yourself this is a line through the origin, remember that
/// such a line can be generated using the geometric product of two planes
/// through the origin.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Branch(float a, float b, float c)
{
P1 = _mm_set_ps(c, b, a, 0f);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Branch(__m128 xmm)
{
P1 = xmm;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Deconstruct(out float e23, out float e31, out float e12)
{
e23 = this.e23;
e31 = this.e31;
e12 = this.e12;
}
public float e12 => P1.GetElement(3);
public float e21 => -e12;
public float Z => e12;
public float e31 => P1.GetElement(2);
public float e13 => -e31;
public float Y => e12;
public float e23 => P1.GetElement(1);
public float e32 => -e23;
public float X => e23;
/// <summary>
/// If a line is constructed as the regressive product (join) of
/// two points, the squared norm provided here is the squared
/// distance between the two points (provided the points are
/// normalized). Returns $d^2 + e^2 + f^2$.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public float SquaredNorm()
{
var dp = Detail.hi_dp(P1, P1);
return _mm_store_ss(dp);
}
/// <summary>
/// Returns the square root of the quantity produced by `squared_norm`.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float Norm()
{
return MathF.Sqrt(SquaredNorm());
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static __m128 Normalized(__m128 p)
{
__m128 inv = Detail.rsqrt_nr1(Detail.hi_dp_bc(p, p));
return _mm_mul_ps(p, inv);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Branch Normalized() => new Branch(Normalized(P1));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static __m128 Inverse(__m128 p)
{
__m128 inv = Detail.rsqrt_nr1(Detail.hi_dp_bc(p, p));
p = _mm_mul_ps(p, inv);
p = _mm_mul_ps(p, inv);
p = _mm_xor_ps(_mm_set_ps(-0f, -0f, -0f, 0f), p);
return p;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Branch Inverse() => new Branch(Inverse(P1));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Branch operator +(Branch a, Branch b)
{
return new Branch(_mm_add_ps(a.P1, b.P1));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Line operator +(Branch a, Line b)
{
return new Line(_mm_add_ps(a.P1, b.P1), b.P2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Line operator +(Line a, Branch b)
{
return new Line(_mm_add_ps(a.P1, b.P1), a.P2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Line operator +(Branch a, IdealLine b)
{
return new Line(a.P1, b.P2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Line operator +(IdealLine a, Branch b)
{
return new Line(b.P1, a.P2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Branch operator -(Branch a, Branch b)
{
return new Branch(_mm_sub_ps(a.P1, b.P1));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Line operator -(Branch a, Line b)
{
return new Line(_mm_sub_ps(a.P1, b.P1), b.P2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Line operator -(Line a, Branch b)
{
return new Line(_mm_sub_ps(a.P1, b.P1), a.P2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Line operator -(Branch a, IdealLine b)
{
return new Line(a.P1, b.P2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Line operator -(IdealLine a, Branch b)
{
return new Line(b.P1, a.P2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Branch operator *(Branch b, float s)
{
return new Branch(_mm_mul_ps(b.P1, _mm_set1_ps(s)));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Branch operator *(float s, Branch b)
{
return new Branch(_mm_mul_ps(b.P1, _mm_set1_ps(s)));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Branch operator /(Branch b, float s)
{
return new Branch(_mm_mul_ps(b.P1, Detail.rcp_nr1(_mm_set1_ps(s))));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Branch operator -(Branch b)
{
return new Branch(_mm_xor_ps(b.P1, _mm_set1_ps(-0f)));
}
/// <summary>
/// Reversion operator
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Branch operator ~(Branch b)
{
__m128 flip = _mm_set_ps(-0f, -0f, -0f, 0f);
return new Branch(_mm_xor_ps(b.P1, flip));
}
/// <summary>
/// TODO: Document!
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static IdealLine operator !(Branch b)
{
return new IdealLine(b.P1);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Dual operator ^(Branch a, IdealLine b)
{
return new Dual(0, _mm_store_ss(Detail.hi_dp_ss(a.P1, b.P2)));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Point operator ^(Branch b, Plane a)
{
return a ^ b;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Dual operator ^(Branch b, Line a)
{
return a ^ b;
}
/// <summary>
/// Generate a Rotor $r$ such that $\widetilde{\sqrt{r}}$ takes Branch $b$ to Branch $a$.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static Rotor operator *(Branch a, Branch b)
{
return new Rotor(Detail.gp11(a.P1, b.P1));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Rotor operator /(Branch a, Branch b)
{
return a * b.Inverse();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Plane operator &(Branch b, Point a)
{
return a & b;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Equals(Branch other)
{
return P1.Equals(other.P1);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override bool Equals(object? obj)
{
return obj is Branch other && Equals(other);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode()
{
return P1.GetHashCode();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Branch left, Branch right)
{
return left.Equals(right);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Branch left, Branch right)
{
return !left.Equals(right);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator Line(Branch b)
{
return new Line(b);
}
public override string ToString()
{
return new StringBuilder(64)
.AppendElement(e12, "e₁₂")
.AppendElement(e31, "e₃₁")
.AppendElement(e23, "e₂₃")
.ZeroWhenEmpty();
}
}
}
| 28.63964
| 111
| 0.663206
|
[
"MIT"
] |
Ziriax/KleinSharp
|
KleinSharp/Source/Branch.cs
| 9,576
|
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;
using System.Collections.Generic;
using System.Data.Common;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal;
using Microsoft.EntityFrameworkCore.Storage;
namespace Microsoft.EntityFrameworkCore.Query.Internal
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public class QueryingEnumerable<T> : IEnumerable<T>
{
private readonly RelationalQueryContext _relationalQueryContext;
private readonly ShaperCommandContext _shaperCommandContext;
private readonly IShaper<T> _shaper;
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public QueryingEnumerable(
[NotNull] RelationalQueryContext relationalQueryContext,
[NotNull] ShaperCommandContext shaperCommandContext,
[NotNull] IShaper<T> shaper)
{
_relationalQueryContext = relationalQueryContext;
_shaperCommandContext = shaperCommandContext;
_shaper = shaper;
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public virtual IEnumerator<T> GetEnumerator() => new Enumerator(this);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
private sealed class Enumerator : IEnumerator<T>, IBufferable
{
private readonly RelationalQueryContext _relationalQueryContext;
private readonly ShaperCommandContext _shaperCommandContext;
private readonly IShaper<T> _shaper;
private readonly Func<DbContext, bool, bool> _bufferlessMoveNext;
private RelationalDataReader _dataReader;
private Queue<ValueBuffer> _buffer;
private DbDataReader _dbDataReader;
private IRelationalValueBufferFactory _valueBufferFactory;
private IExecutionStrategy _executionStrategy;
private bool _disposed;
public Enumerator(QueryingEnumerable<T> queryingEnumerable)
{
_shaperCommandContext = queryingEnumerable._shaperCommandContext;
_valueBufferFactory = _shaperCommandContext.ValueBufferFactory;
_relationalQueryContext = queryingEnumerable._relationalQueryContext;
_shaper = queryingEnumerable._shaper;
_bufferlessMoveNext = BufferlessMoveNext;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (_buffer == null)
{
if (_executionStrategy == null)
{
_executionStrategy = _relationalQueryContext.ExecutionStrategyFactory.Create();
}
return _executionStrategy.Execute(_executionStrategy.RetriesOnFailure, _bufferlessMoveNext, null);
}
if (_buffer.Count > 0)
{
Current = _shaper.Shape(_relationalQueryContext, _buffer.Dequeue());
return true;
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool BufferlessMoveNext(DbContext _, bool buffer)
{
if (_dataReader == null)
{
_relationalQueryContext.Connection.Open();
try
{
var relationalCommand
= _shaperCommandContext
.GetRelationalCommand(_relationalQueryContext.ParameterValues);
_relationalQueryContext.Connection.RegisterBufferable(this);
_dataReader
= relationalCommand.ExecuteReader(
_relationalQueryContext.Connection,
_relationalQueryContext.ParameterValues);
}
catch
{
// If failure happens creating the data reader, then it won't be available to
// handle closing the connection, so do it explicitly here to preserve ref counting.
_relationalQueryContext.Connection.Close();
throw;
}
_dbDataReader = _dataReader.DbDataReader;
_shaperCommandContext.NotifyReaderCreated(_dbDataReader);
_valueBufferFactory = _shaperCommandContext.ValueBufferFactory;
}
var hasNext = _dataReader.Read();
Current
= hasNext
? _shaper.Shape(_relationalQueryContext, _valueBufferFactory.Create(_dbDataReader))
: default;
if (buffer)
{
BufferAll();
}
return hasNext;
}
public T Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get;
private set;
}
public void BufferAll()
{
if (_buffer == null
&& _dataReader != null)
{
_buffer = new Queue<ValueBuffer>();
using (_dataReader)
{
while (_dataReader.Read())
{
_buffer.Enqueue(_valueBufferFactory.Create(_dbDataReader));
}
}
_relationalQueryContext.Connection?.Close();
_dataReader = null;
_dbDataReader = null;
}
}
public async Task BufferAllAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (_buffer == null
&& _dataReader != null)
{
_buffer = new Queue<ValueBuffer>();
using (_dataReader)
{
while (await _dataReader.ReadAsync(cancellationToken))
{
_buffer.Enqueue(_valueBufferFactory.Create(_dbDataReader));
}
}
_relationalQueryContext.Connection?.Close();
_dataReader = null;
_dbDataReader = null;
}
}
object IEnumerator.Current => Current;
public void Dispose()
{
if (!_disposed)
{
if (_dataReader != null)
{
_dataReader.Dispose();
_dataReader = null;
_dbDataReader = null;
_buffer = null;
_relationalQueryContext.Connection?.Close();
}
_relationalQueryContext.Connection?.UnregisterBufferable(this);
_disposed = true;
}
}
public void Reset() => throw new NotImplementedException();
}
}
}
| 36.789238
| 118
| 0.537786
|
[
"Apache-2.0"
] |
ahsonkhan/EntityFrameworkCore
|
src/EFCore.Relational/Query/Internal/QueryingEnumerable.cs
| 8,204
|
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.AddressableAssets.Settings;
using UnityEngine.PlayerLoop;
namespace AIR.AddressableRegister.Editor
{
[InitializeOnLoad]
public class AddressableRegisterPostProcessor
{
private static readonly AddressableRegisterTranscriber Author =
new AddressableRegisterTranscriber();
private static readonly AddressableRegisterLocator Finder =
new AddressableRegisterLocator();
private static readonly Dictionary<string, FileSystemWatcher> Watchers =
new Dictionary<string, FileSystemWatcher>();
private static readonly Queue<Action> ReAuthorActions
= new Queue<Action>();
static AddressableRegisterPostProcessor()
{
WatchAddressableChanges();
EditorApplication.update += Update;
}
private static void Update()
{
while (ReAuthorActions.Any())
ReAuthorActions.Dequeue()?.Invoke();
}
private static void WatchAddressableChanges()
{
Watchers.Clear();
string filter = $"t:{nameof(AddressableAssetGroup)}";
var addressableAssetIds = AssetDatabase.FindAssets(filter);
foreach (var assetId in addressableAssetIds) {
var assetPath = AssetDatabase.GUIDToAssetPath(assetId);
var fileInfo = new FileInfo(assetPath);
if (fileInfo.Directory == null) continue;
var fullPath = fileInfo.FullName;
if (Watchers.ContainsKey(fullPath)) continue;
var watcher = new FileSystemWatcher {
EnableRaisingEvents = true,
Path = Path.GetDirectoryName(fullPath),
Filter = Path.GetFileName(fullPath),
};
watcher.Changed += QueueReAuthor;
// watcher.Renamed += QueueReAuthor;
// watcher.Deleted += QueueReAuthor;
Watchers.Add(fullPath, watcher);
}
}
private static void QueueReAuthor(object sender, FileSystemEventArgs e)
{
var addressableRegisterPath = Finder.FindOutputFile();
ReAuthorActions.Enqueue(() => Author.WriteAddressableRegisterTo(addressableRegisterPath));
}
}
}
| 35.130435
| 102
| 0.62005
|
[
"MIT"
] |
AnImaginedReality/AddressableRegister.Package
|
Editor/AddressableRegisterPostProcessor.cs
| 2,424
|
C#
|
using System;
using System.Threading.Tasks;
namespace Company.Desktop.Framework.Mvvm.Interactivity
{
public interface IActivateable : IDisposable
{
Task ActivateAsync(IActivationContext context);
IObservable<IActivationContext> WhenActivated { get; }
}
}
| 22
| 56
| 0.799242
|
[
"Apache-2.0"
] |
taori/Amusoft.VisualStudio.Extensions
|
templateSources/WpfApplication/Company.Desktop.Framework.Mvvm/Interactivity/IActivateable.cs
| 266
|
C#
|
using System;
using DotNetRuServer.Comon.BL.Extensions;
using DotNetRuServer.Meetups.BL.Entities;
using DotNetRuServer.Meetups.BL.Models;
namespace DotNetRuServer.Meetups.BL.Extensions
{
public static class VenueExtensions
{
public static VenueVm EnsureIsValid(this VenueVm venue)
{
// todo: implement full validation
if (string.IsNullOrWhiteSpace(venue.Name)) throw new FormatException(nameof(venue.Name));
if (string.IsNullOrWhiteSpace(venue.Address)) throw new FormatException(nameof(venue.Address));
if (venue.City != venue.Id.GetCity()) throw new FormatException(nameof(venue.City));
return venue;
}
public static VenueVm ToVm(this Venue venue)
{
return new VenueVm
{
Id = venue.ExportId,
City = venue.City,
Name = venue.Name,
Address = venue.Address,
MapUrl = venue.MapUrl
};
}
public static Venue Extend(this Venue original, VenueVm venue)
{
return new Venue
{
Id = original.Id,
ExportId = venue.Id,
Name = venue.Name,
City = venue.City,
Address = venue.Address,
MapUrl = venue.MapUrl
};
}
}
}
| 29.145833
| 107
| 0.555397
|
[
"MIT"
] |
b-a-x/Server
|
DotNetRuServer.Meetups.BL/Extensions/VenueExtensions.cs
| 1,399
|
C#
|
using System;
namespace NBehave.Hooks
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Field)]
public class BeforeStepAttribute : HookAttribute { }
}
| 25.142857
| 71
| 0.75
|
[
"BSD-3-Clause"
] |
MorganPersson/NBehave
|
src/NBehave/Hooks/BeforeStepAttribute.cs
| 176
|
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Easy14_Coding_Language
{
class UNUSED_VariableCode_SettingVar
{
/*
████████╗██╗░░██╗██╗░██████╗ ██╗░██████╗ ██╗░░░██╗███╗░░██╗██╗░░░██╗░██████╗███████╗██████╗░██╗
╚══██╔══╝██║░░██║██║██╔════╝ ██║██╔════╝ ██║░░░██║████╗░██║██║░░░██║██╔════╝██╔════╝██╔══██╗██║
░░░██║░░░███████║██║╚█████╗░ ██║╚█████╗░ ██║░░░██║██╔██╗██║██║░░░██║╚█████╗░█████╗░░██║░░██║██║
░░░██║░░░██╔══██║██║░╚═══██╗ ██║░╚═══██╗ ██║░░░██║██║╚████║██║░░░██║░╚═══██╗██╔══╝░░██║░░██║╚═╝
░░░██║░░░██║░░██║██║██████╔╝ ██║██████╔╝ ╚██████╔╝██║░╚███║╚██████╔╝██████╔╝███████╗██████╔╝██╗
░░░╚═╝░░░╚═╝░░╚═╝╚═╝╚═════╝░ ╚═╝╚═════╝░ ░╚═════╝░╚═╝░░╚══╝░╚═════╝░╚═════╝░╚══════╝╚═════╝░╚═╝
Sorry but this function is unused till i can fix bugs for it!
*/
Program prog = new Program();
private string endOfStatementCode_;
public string endOfStatementCode
{
get { return endOfStatementCode_; }
set { endOfStatementCode_ = value; }
}
public void interperate(string code_part, string[] lines, string varName)
{
string code_part_unedited = code_part;
code_part = code_part.TrimStart();
code_part = code_part.Substring(3);
code_part = code_part.TrimStart();
//code_part = code_part.Substring(0, code_part.Length - 1);
if (code_part.StartsWith("Console.input(")) {
code_part.Replace("Console.input(", "");
code_part.Substring(0, code_part.Length - 1);
Console.Write(">");
string ohGodmyBrainIsHurting = Console.ReadLine();
string[] files = Directory.GetFiles(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
+ @$"\EASY14_Variables_TEMP"
);
string var_file = null;
foreach (string file in files)
{
if (file.Substring(file.LastIndexOf(@"\")).Replace(@"\", "").Replace(".txt", "") == varName)
{
var_file = file;
}
}
File.WriteAllText(var_file, ohGodmyBrainIsHurting);
}
}
}
}
| 41.610169
| 112
| 0.385336
|
[
"MIT"
] |
Mervinpais/Easy14_Programing_language
|
Functions/UNUSEDVariableCode_SettingVar.cs
| 3,619
|
C#
|
namespace P05_DateModifier
{
using System;
public class DateDifference
{
public static void Main()
{
string firstDate = Console.ReadLine();
string secondDate = Console.ReadLine();
var diff = new DateModifier();
Console.WriteLine(diff.FindDifference(firstDate, secondDate));
}
}
}
| 20.666667
| 74
| 0.583333
|
[
"MIT"
] |
MertYumer/C-Fundamentals---January-2019
|
C# Advanced - January 2019/06. Defining Classess - Exercises/P05-DateModifier/DateDifference.cs
| 374
|
C#
|
namespace Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview
{
using Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="OperationListResultAutoGenerated" />
/// </summary>
public partial class OperationListResultAutoGeneratedTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="OperationListResultAutoGenerated"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="OperationListResultAutoGenerated" /> type, otherwise <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="OperationListResultAutoGenerated" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="OperationListResultAutoGenerated" />.</param>
/// <returns>
/// an instance of <see cref="OperationListResultAutoGenerated" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IOperationListResultAutoGenerated ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IOperationListResultAutoGenerated).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return OperationListResultAutoGenerated.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return OperationListResultAutoGenerated.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return OperationListResultAutoGenerated.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
}
| 52.950704
| 251
| 0.594494
|
[
"MIT"
] |
3quanfeng/azure-powershell
|
src/PostgreSql/generated/api/Models/Api20200214Preview/OperationListResultAutoGenerated.TypeConverter.cs
| 7,378
|
C#
|
using System;
using System.Xml.Linq;
namespace TT.HttpClient.Weixin.WeixiinResult.TenPay
{
/// <summary>
/// 统一支付接口在return_code 和result_code 都为SUCCESS 的时候有返回详细信息
/// </summary>
public class UnifiedorderResult : Result
{
///// <summary>
///// 子商户公众账号ID
///// </summary>
//public string sub_appid { get; set; }
///// <summary>
///// 子商户号
///// </summary>
//public string sub_mch_id { get; set; }
public UnifiedorderResult(string resultXml)
: base(resultXml)
{
if (IsReturnCodeSuccess())
{
device_info = GetXmlValue("device_info") ?? "";
//sub_appid = GetXmlValue("sub_appid") ?? "";
//sub_mch_id = GetXmlValue("sub_mch_id") ?? "";
if (IsResultCodeSuccess())
{
trade_type = GetXmlValue("trade_type") ?? "";
prepay_id = GetXmlValue("prepay_id") ?? "";
code_url = GetXmlValue("code_url") ?? "";
mweb_url = GetXmlValue("mweb_url") ?? "";
}
}
}
public UnifiedorderResult(XDocument xml)
: base(xml)
{
if (IsReturnCodeSuccess())
{
device_info = GetXmlValue("device_info") ?? "";
//sub_appid = GetXmlValue("sub_appid") ?? "";
//sub_mch_id = GetXmlValue("sub_mch_id") ?? "";
if (IsResultCodeSuccess())
{
trade_type = GetXmlValue("trade_type") ?? "";
prepay_id = GetXmlValue("prepay_id") ?? "";
code_url = GetXmlValue("code_url") ?? "";
mweb_url = GetXmlValue("mweb_url") ?? "";
}
TimeStamp = Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds).ToString();
}
}
/// <summary>
/// 微信支付分配的终端设备号
/// </summary>
public string device_info { get; set; }
/// <summary>
/// 交易类型:JSAPI、NATIVE、APP
/// </summary>
public string trade_type { get; set; }
/// <summary>
/// 微信生成的预支付ID,用于后续接口调用中使用
/// </summary>
public string prepay_id { get; set; }
/// <summary>
/// trade_type为NATIVE时有返回,此参数可直接生成二维码展示出来进行扫码支付
/// </summary>
public string code_url { get; set; }
/// <summary>
/// 在H5支付时返回
/// </summary>
public string mweb_url { get; set; }
public string TimeStamp { get; }
public string PaySign { get; set; }
}
}
| 30.422222
| 126
| 0.473338
|
[
"MIT"
] |
18789073256/SoMall
|
backEnd/modules/TT.HttpClient.Weixin/WeixiinResult/TenPay/UnifiedorderResult.cs
| 2,944
|
C#
|
using System;
using System.Collections;
using System.Collections.Generic;
using _local.Scripts;
using MyNamespace;
using UnityEngine;
using UnityEngine.Experimental.Rendering.Universal;
using Random = UnityEngine.Random;
namespace firewalk
{
public class EnemyAI : MonoBehaviour
{
[Header("Settings")]
[Tooltip("Red circle. Without torch")]
public float playerDetectionDistanceWithoutTorch = 8f;
[Tooltip("White circle.With lit torch")]
public float playerDetectionDistanceWithTorchLit = 10f;
public float walkingSpeed = 1.0f;
[Tooltip("Yellow circle. Tune this to actual attack range trigger collider or less")]
public float attackRange = 1.0f;
// public bool changeVelocity;
public float attackTimeOut = 0.5f;
public float minPatrolDistance = 5f;
[Tooltip("Blue circle. Tune this to actual attack range trigger collider or less")]
public float maxPatrolDistance = 15f;
public float patrolPointReachAccuracy = 1f;
public float stuckTimeOutSeconds = 10f;
public EnemyState state { get; private set; }
[Header("Links to scene objects")]
public Animator characterAnimator;
public SpriteRenderer frontSprite;
public SpriteRenderer backSprite;
public SpriteRenderer attackSprite;
public ShadowCaster2D shadowRight;
public ShadowCaster2D shadowLeft;
// private Vector3 shadowOriginalScale;
private Rigidbody2D rb;
private Vector2 moveDirection;
private float timeBeforeEvasion;
private float timeBeforeAttack;
private float timeBeforeConsideringStuck;
private PlayerController player;
private LivingBeing playerLivingBeing;
private Vector2 lastPatrolPoint;
private Vector2 spawnPoint;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
state = EnemyState.Idle;
player = PlayerController.instance;
playerLivingBeing = player.GetComponent<LivingBeing>();
//save spawn point, it will be used to return after patrolling
spawnPoint = transform.position;
lastPatrolPoint = Vector2.zero;
// shadowOriginalScale = shadow.transform.localScale;
}
private void Update()
{
AdvanceTimers();
}
void AdvanceTimers()
{
if (timeBeforeAttack > 0)
{
timeBeforeAttack -= Time.deltaTime;
}
if (timeBeforeConsideringStuck > 0)
{
timeBeforeConsideringStuck -= Time.deltaTime;
}
//TODO: stuck timer for situations when stuck in obstacles?
}
void FixedUpdate()
{
if (PlayerInAttackRange && playerLivingBeing.IsAlive())
{
TryToAttack();
state = EnemyState.Attacking;
}
else if (SeesPlayer && playerLivingBeing.IsAlive())
{
MoveTowardsPoint(player.transform.position);
state = EnemyState.Chasing;
//reset patrol point to randomize movement whan enemy looses playerr
lastPatrolPoint = Vector2.zero;
}
else if (lastPatrolPoint == Vector2.zero)
{
//special case - enemy has not yet moved to any patrol point, so select a new one
SelectNewPatrolPoint();
MoveTowardsPoint(lastPatrolPoint);
state = EnemyState.Patrolling;
}
else if (ReachedPatrolPoint)
{
//reached patrol point, select new one
SelectNewPatrolPoint();
MoveTowardsPoint(lastPatrolPoint);
state = EnemyState.Patrolling;
}
else
{
if (timeBeforeConsideringStuck < 0)
{
//consider stuck, find another patrol point
SelectNewPatrolPoint();
}
//still moving towards patrol point
MoveTowardsPoint(lastPatrolPoint);
state = EnemyState.Patrolling;
}
UpdateAnimationDirection();
; //TODO: refactor to reduce if-else
}
/*
* Checks attack timeout (cooldown) and attacks if it can
*/
void TryToAttack()
{
if (timeBeforeAttack <= 0)
{
Attack();
timeBeforeAttack = attackTimeOut;
}
}
void Attack()
{
print("Enemy attacks");
characterAnimator.SetTrigger("attack");
}
/*
* Must be called from animation
*/
public void OnEvasionEnded()
{
//just here so the animator won't crash if shared with player
}
public bool SeesPlayer
{
get
{
float distanceToDetect;
if (player.torchIsLit)
{
distanceToDetect = playerDetectionDistanceWithTorchLit;
}
else
{
distanceToDetect = playerDetectionDistanceWithoutTorch;
}
bool withinDistance = Vector2.Distance(transform.position, player.transform.position) <= distanceToDetect;
if (withinDistance)
{
//cast a ray to player and see if it hits wall or player first
// Vector2 dir = (player.transform.position - transform.position).normalized;
//
// int layerMask = LayerMask.GetMask("Player", "Obstacle");
//
// if (Physics2D.Raycast(transform.position, dir, Mathf.Infinity, layerMask).collider.tag == "Player")
// {
// return true;
// }
//not casting the ray, we assume player is always seem
//TODO: cast the ray if layer does not have lit torch?
//TODO: reduce detection range if player does not have lit torch?
return true;
}
return false;
}
}
/*
* Sets random patrol point around spawn location
*/
public void SelectNewPatrolPoint()
{
int xSign = Random.value > 0.5 ? 1 : -1;
int ySign = Random.value > 0.5 ? 1 : -1;
lastPatrolPoint = new Vector2(spawnPoint.x + xSign * Random.Range(minPatrolDistance, maxPatrolDistance),
spawnPoint.y + ySign*Random.Range(minPatrolDistance, maxPatrolDistance));
//reset stuck timer
timeBeforeConsideringStuck = stuckTimeOutSeconds;
}
public bool ReachedPatrolPoint
{
get
{
bool withinDistance = Vector2.Distance(transform.position, lastPatrolPoint) <= patrolPointReachAccuracy;
return withinDistance;
}
}
public bool PlayerInAttackRange
{
get
{
return Vector2.Distance(transform.position, player.transform.position) <= attackRange;
}
}
public void MoveTowardsPoint(Vector2 targetPoint)
{
moveDirection = (targetPoint - (Vector2)transform.position).normalized;
rb.velocity = moveDirection * walkingSpeed;
//TODO: change to vector 2?
characterAnimator.SetBool("moving", true);
}
void OnDrawGizmosSelected()
{
// Draw a yellow sphere at the transform's position
// to show attack range
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, attackRange);
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, playerDetectionDistanceWithoutTorch);
Gizmos.color = Color.white;
Gizmos.DrawWireSphere(transform.position, playerDetectionDistanceWithTorchLit);
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere(transform.position, maxPatrolDistance);
}
public void StopMovement()
{
rb.velocity=Vector2.zero;
}
public void UpdateAnimationDirection()
{
if (moveDirection.x>0)
{
frontSprite.flipX = false;
backSprite.flipX = false;
attackSprite.flipX = false;
shadowLeft.castsShadows=false;
shadowRight.castsShadows=true;
}
else if (moveDirection.x < 0) //we don;t update it if it's 0 to face the same direction he walked
{
frontSprite.flipX = true;
backSprite.flipX = true;
attackSprite.flipX = true;
shadowLeft.castsShadows=true;
shadowRight.castsShadows=false;
}
if (moveDirection.y > 0)
{
frontSprite.enabled = false;
backSprite.enabled = true;
}
else if (moveDirection.y < 0)
{
frontSprite.enabled = true;
backSprite.enabled = false;
}
}
}
public enum EnemyState
{
Idle = 1,
Patrolling = 2,
Chasing = 3,
Attacking = 4
}
}
| 31
| 122
| 0.520075
|
[
"MIT"
] |
DataGreed/LD46
|
LDJam46/Assets/_local/Scripts/EnemyAI.cs
| 10,137
|
C#
|
using System;
/*
* С помощью какой клавиши можно перевести редактор vi в режим
* ввода команд?
*/
namespace step_3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Esc");
}
}
}
| 15.055556
| 64
| 0.523985
|
[
"Unlicense"
] |
tshemake/Software-Development
|
stepik/762/30070/step_3/Program.cs
| 332
|
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#if FEATURE_CONFIGURATION
using System;
using System.Configuration;
using AnyPrefix.Microsoft.Scripting.Utils;
namespace AnyPrefix.Microsoft.Scripting.Hosting.Configuration {
// <language names="IronPython;Python;py" extensions=".py" type="AQTN" displayName="IronPython v2">
// <option name="foo" value="bar" />
// </language>
public class LanguageElement : ConfigurationElement {
private const string _Names = "names";
private const string _Extensions = "extensions";
private const string _Type = "type";
private const string _DisplayName = "displayName";
private static ConfigurationPropertyCollection _Properties = new ConfigurationPropertyCollection {
new ConfigurationProperty(_Names, typeof(string), null),
new ConfigurationProperty(_Extensions, typeof(string), null),
new ConfigurationProperty(_Type, typeof(string), null, ConfigurationPropertyOptions.IsRequired),
new ConfigurationProperty(_DisplayName, typeof(string), null)
};
protected override ConfigurationPropertyCollection Properties => _Properties;
public string Names {
get => (string)this[_Names];
set => this[_Names] = value;
}
public string Extensions {
get => (string)this[_Extensions];
set => this[_Extensions] = value;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
public string Type {
get => (string)this[_Type];
set => this[_Type] = value;
}
public string DisplayName {
get => (string)this[_DisplayName];
set => this[_DisplayName] = value;
}
public string[] GetNamesArray() => Split(Names);
public string[] GetExtensionsArray() => Split(Extensions);
private static string[] Split(string str) =>
str != null
? str.Split(new[] {';', ','}, StringSplitOptions.RemoveEmptyEntries)
: ArrayUtils.EmptyStrings;
}
}
#endif
| 36.734375
| 125
| 0.650362
|
[
"MIT"
] |
shuice/IronPython_UWP
|
ironpython2/Src/DLR/Src/Microsoft.Scripting/Hosting/Configuration/LanguageElement.cs
| 2,353
|
C#
|
using UnityEngine.TestTools.Graphics;
public class GlobalGraphicsTestSettings : GraphicsTestSettings
{
public int WaitFrames = 0;
public GlobalGraphicsTestSettings()
{
ImageComparisonSettings.TargetWidth = 1920;
ImageComparisonSettings.TargetHeight = 1080;
ImageComparisonSettings.AverageCorrectnessThreshold = 0.0015f;
ImageComparisonSettings.PerPixelCorrectnessThreshold = 0.00015f;
}
}
| 29.266667
| 72
| 0.758542
|
[
"MIT"
] |
Ariions/PT_Application_Tests
|
Assets/Tests/PlayModeTests/UniversalGraphicsTestSettings.cs
| 439
|
C#
|
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// Zip
/// </summary>
[DataContract]
public partial class Zip : IEquatable<Zip>, IValidatableObject
{
public Zip()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="Zip" /> class.
/// </summary>
/// <param name="AnchorAllowWhiteSpaceInCharacters">AnchorAllowWhiteSpaceInCharacters.</param>
/// <param name="AnchorAllowWhiteSpaceInCharactersMetadata">AnchorAllowWhiteSpaceInCharactersMetadata.</param>
/// <param name="AnchorCaseSensitive">When set to **true**, the anchor string does not consider case when matching strings in the document. The default value is **true**..</param>
/// <param name="AnchorCaseSensitiveMetadata">AnchorCaseSensitiveMetadata.</param>
/// <param name="AnchorHorizontalAlignment">Specifies the alignment of anchor tabs with anchor strings. Possible values are **left** or **right**. The default value is **left**..</param>
/// <param name="AnchorHorizontalAlignmentMetadata">AnchorHorizontalAlignmentMetadata.</param>
/// <param name="AnchorIgnoreIfNotPresent">When set to **true**, this tab is ignored if anchorString is not found in the document..</param>
/// <param name="AnchorIgnoreIfNotPresentMetadata">AnchorIgnoreIfNotPresentMetadata.</param>
/// <param name="AnchorMatchWholeWord">When set to **true**, the anchor string in this tab matches whole words only (strings embedded in other strings are ignored.) The default value is **true**..</param>
/// <param name="AnchorMatchWholeWordMetadata">AnchorMatchWholeWordMetadata.</param>
/// <param name="AnchorString">Anchor text information for a radio button..</param>
/// <param name="AnchorStringMetadata">AnchorStringMetadata.</param>
/// <param name="AnchorTabProcessorVersion">AnchorTabProcessorVersion.</param>
/// <param name="AnchorTabProcessorVersionMetadata">AnchorTabProcessorVersionMetadata.</param>
/// <param name="AnchorUnits">Specifies units of the X and Y offset. Units could be pixels, millimeters, centimeters, or inches..</param>
/// <param name="AnchorUnitsMetadata">AnchorUnitsMetadata.</param>
/// <param name="AnchorXOffset">Specifies the X axis location of the tab, in anchorUnits, relative to the anchorString..</param>
/// <param name="AnchorXOffsetMetadata">AnchorXOffsetMetadata.</param>
/// <param name="AnchorYOffset">Specifies the Y axis location of the tab, in anchorUnits, relative to the anchorString..</param>
/// <param name="AnchorYOffsetMetadata">AnchorYOffsetMetadata.</param>
/// <param name="Bold">When set to **true**, the information in the tab is bold..</param>
/// <param name="BoldMetadata">BoldMetadata.</param>
/// <param name="ConcealValueOnDocument">When set to **true**, the field appears normally while the recipient is adding or modifying the information in the field, but the data is not visible (the characters are hidden by asterisks) to any other signer or the sender. When an envelope is completed the information is available to the sender through the Form Data link in the DocuSign Console. This setting applies only to text boxes and does not affect list boxes, radio buttons, or check boxes..</param>
/// <param name="ConcealValueOnDocumentMetadata">ConcealValueOnDocumentMetadata.</param>
/// <param name="ConditionalParentLabel">For conditional fields this is the TabLabel of the parent tab that controls this tab's visibility..</param>
/// <param name="ConditionalParentLabelMetadata">ConditionalParentLabelMetadata.</param>
/// <param name="ConditionalParentValue">For conditional fields, this is the value of the parent tab that controls the tab's visibility. If the parent tab is a Checkbox, Radio button, Optional Signature, or Optional Initial use \"on\" as the value to show that the parent tab is active. .</param>
/// <param name="ConditionalParentValueMetadata">ConditionalParentValueMetadata.</param>
/// <param name="CustomTabId">The DocuSign generated custom tab ID for the custom tab to be applied. This can only be used when adding new tabs for a recipient. When used, the new tab inherits all the custom tab properties..</param>
/// <param name="CustomTabIdMetadata">CustomTabIdMetadata.</param>
/// <param name="DisableAutoSize">When set to **true**, disables the auto sizing of single line text boxes in the signing screen when the signer enters data. If disabled users will only be able enter as much data as the text box can hold. By default this is false. This property only affects single line text boxes..</param>
/// <param name="DisableAutoSizeMetadata">DisableAutoSizeMetadata.</param>
/// <param name="DocumentId">Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute..</param>
/// <param name="DocumentIdMetadata">DocumentIdMetadata.</param>
/// <param name="ErrorDetails">ErrorDetails.</param>
/// <param name="Font">The font to be used for the tab value. Supported Fonts: Arial, Arial, ArialNarrow, Calibri, CourierNew, Garamond, Georgia, Helvetica, LucidaConsole, Tahoma, TimesNewRoman, Trebuchet, Verdana, MSGothic, MSMincho, Default..</param>
/// <param name="FontColor">The font color used for the information in the tab. Possible values are: Black, BrightBlue, BrightRed, DarkGreen, DarkRed, Gold, Green, NavyBlue, Purple, or White..</param>
/// <param name="FontColorMetadata">FontColorMetadata.</param>
/// <param name="FontMetadata">FontMetadata.</param>
/// <param name="FontSize">The font size used for the information in the tab. Possible values are: Size7, Size8, Size9, Size10, Size11, Size12, Size14, Size16, Size18, Size20, Size22, Size24, Size26, Size28, Size36, Size48, or Size72..</param>
/// <param name="FontSizeMetadata">FontSizeMetadata.</param>
/// <param name="FormOrder">FormOrder.</param>
/// <param name="FormOrderMetadata">FormOrderMetadata.</param>
/// <param name="FormPageLabel">FormPageLabel.</param>
/// <param name="FormPageLabelMetadata">FormPageLabelMetadata.</param>
/// <param name="FormPageNumber">FormPageNumber.</param>
/// <param name="FormPageNumberMetadata">FormPageNumberMetadata.</param>
/// <param name="Height">Height of the tab in pixels..</param>
/// <param name="HeightMetadata">HeightMetadata.</param>
/// <param name="Italic">When set to **true**, the information in the tab is italic..</param>
/// <param name="ItalicMetadata">ItalicMetadata.</param>
/// <param name="LocalePolicy">LocalePolicy.</param>
/// <param name="Locked">When set to **true**, the signer cannot change the data of the custom tab..</param>
/// <param name="LockedMetadata">LockedMetadata.</param>
/// <param name="MaxLength">An optional value that describes the maximum length of the property when the property is a string..</param>
/// <param name="MaxLengthMetadata">MaxLengthMetadata.</param>
/// <param name="MergeField">MergeField.</param>
/// <param name="MergeFieldXml">MergeFieldXml.</param>
/// <param name="Name">Name.</param>
/// <param name="NameMetadata">NameMetadata.</param>
/// <param name="OriginalValue">The initial value of the tab when it was sent to the recipient. .</param>
/// <param name="OriginalValueMetadata">OriginalValueMetadata.</param>
/// <param name="PageNumber">Specifies the page number on which the tab is located..</param>
/// <param name="PageNumberMetadata">PageNumberMetadata.</param>
/// <param name="RecipientId">Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document..</param>
/// <param name="RecipientIdGuid">RecipientIdGuid.</param>
/// <param name="RecipientIdGuidMetadata">RecipientIdGuidMetadata.</param>
/// <param name="RecipientIdMetadata">RecipientIdMetadata.</param>
/// <param name="RequireAll">When set to **true** and shared is true, information must be entered in this field to complete the envelope. .</param>
/// <param name="RequireAllMetadata">RequireAllMetadata.</param>
/// <param name="Required">When set to **true**, the signer is required to fill out this tab.</param>
/// <param name="RequiredMetadata">RequiredMetadata.</param>
/// <param name="RequireInitialOnSharedChange">Optional element for field markup. When set to **true**, the signer is required to initial when they modify a shared field..</param>
/// <param name="RequireInitialOnSharedChangeMetadata">RequireInitialOnSharedChangeMetadata.</param>
/// <param name="SenderRequired">When set to **true**, the sender must populate the tab before an envelope can be sent using the template. This value tab can only be changed by modifying (PUT) the template. Tabs with a `senderRequired` value of true cannot be deleted from an envelope..</param>
/// <param name="SenderRequiredMetadata">SenderRequiredMetadata.</param>
/// <param name="Shared">When set to **true**, this custom tab is shared..</param>
/// <param name="SharedMetadata">SharedMetadata.</param>
/// <param name="SmartContractInformation">SmartContractInformation.</param>
/// <param name="Status">Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later..</param>
/// <param name="StatusMetadata">StatusMetadata.</param>
/// <param name="TabGroupLabels">TabGroupLabels.</param>
/// <param name="TabGroupLabelsMetadata">TabGroupLabelsMetadata.</param>
/// <param name="TabId">The unique identifier for the tab. The tabid can be retrieved with the [ML:GET call]. .</param>
/// <param name="TabIdMetadata">TabIdMetadata.</param>
/// <param name="TabLabel">The label string associated with the tab..</param>
/// <param name="TabLabelMetadata">TabLabelMetadata.</param>
/// <param name="TabOrder">TabOrder.</param>
/// <param name="TabOrderMetadata">TabOrderMetadata.</param>
/// <param name="TabType">TabType.</param>
/// <param name="TabTypeMetadata">TabTypeMetadata.</param>
/// <param name="TemplateLocked">When set to **true**, the sender cannot change any attributes of the recipient. Used only when working with template recipients. .</param>
/// <param name="TemplateLockedMetadata">TemplateLockedMetadata.</param>
/// <param name="TemplateRequired">When set to **true**, the sender may not remove the recipient. Used only when working with template recipients..</param>
/// <param name="TemplateRequiredMetadata">TemplateRequiredMetadata.</param>
/// <param name="Tooltip">Tooltip.</param>
/// <param name="ToolTipMetadata">ToolTipMetadata.</param>
/// <param name="Underline">When set to **true**, the information in the tab is underlined..</param>
/// <param name="UnderlineMetadata">UnderlineMetadata.</param>
/// <param name="UseDash4">UseDash4.</param>
/// <param name="UseDash4Metadata">UseDash4Metadata.</param>
/// <param name="ValidationMessage">The message displayed if the custom tab fails input validation (either custom of embedded)..</param>
/// <param name="ValidationMessageMetadata">ValidationMessageMetadata.</param>
/// <param name="ValidationPattern">A regular expression used to validate input for the tab..</param>
/// <param name="ValidationPatternMetadata">ValidationPatternMetadata.</param>
/// <param name="Value">Specifies the value of the tab. .</param>
/// <param name="ValueMetadata">ValueMetadata.</param>
/// <param name="Width">Width of the tab in pixels..</param>
/// <param name="WidthMetadata">WidthMetadata.</param>
/// <param name="XPosition">This indicates the horizontal offset of the object on the page. DocuSign uses 72 DPI when determining position..</param>
/// <param name="XPositionMetadata">XPositionMetadata.</param>
/// <param name="YPosition">This indicates the vertical offset of the object on the page. DocuSign uses 72 DPI when determining position..</param>
/// <param name="YPositionMetadata">YPositionMetadata.</param>
public Zip(string AnchorAllowWhiteSpaceInCharacters = default(string), PropertyMetadata AnchorAllowWhiteSpaceInCharactersMetadata = default(PropertyMetadata), string AnchorCaseSensitive = default(string), PropertyMetadata AnchorCaseSensitiveMetadata = default(PropertyMetadata), string AnchorHorizontalAlignment = default(string), PropertyMetadata AnchorHorizontalAlignmentMetadata = default(PropertyMetadata), string AnchorIgnoreIfNotPresent = default(string), PropertyMetadata AnchorIgnoreIfNotPresentMetadata = default(PropertyMetadata), string AnchorMatchWholeWord = default(string), PropertyMetadata AnchorMatchWholeWordMetadata = default(PropertyMetadata), string AnchorString = default(string), PropertyMetadata AnchorStringMetadata = default(PropertyMetadata), string AnchorTabProcessorVersion = default(string), PropertyMetadata AnchorTabProcessorVersionMetadata = default(PropertyMetadata), string AnchorUnits = default(string), PropertyMetadata AnchorUnitsMetadata = default(PropertyMetadata), string AnchorXOffset = default(string), PropertyMetadata AnchorXOffsetMetadata = default(PropertyMetadata), string AnchorYOffset = default(string), PropertyMetadata AnchorYOffsetMetadata = default(PropertyMetadata), string Bold = default(string), PropertyMetadata BoldMetadata = default(PropertyMetadata), string ConcealValueOnDocument = default(string), PropertyMetadata ConcealValueOnDocumentMetadata = default(PropertyMetadata), string ConditionalParentLabel = default(string), PropertyMetadata ConditionalParentLabelMetadata = default(PropertyMetadata), string ConditionalParentValue = default(string), PropertyMetadata ConditionalParentValueMetadata = default(PropertyMetadata), string CustomTabId = default(string), PropertyMetadata CustomTabIdMetadata = default(PropertyMetadata), string DisableAutoSize = default(string), PropertyMetadata DisableAutoSizeMetadata = default(PropertyMetadata), string DocumentId = default(string), PropertyMetadata DocumentIdMetadata = default(PropertyMetadata), ErrorDetails ErrorDetails = default(ErrorDetails), string Font = default(string), string FontColor = default(string), PropertyMetadata FontColorMetadata = default(PropertyMetadata), PropertyMetadata FontMetadata = default(PropertyMetadata), string FontSize = default(string), PropertyMetadata FontSizeMetadata = default(PropertyMetadata), string FormOrder = default(string), PropertyMetadata FormOrderMetadata = default(PropertyMetadata), string FormPageLabel = default(string), PropertyMetadata FormPageLabelMetadata = default(PropertyMetadata), string FormPageNumber = default(string), PropertyMetadata FormPageNumberMetadata = default(PropertyMetadata), string Height = default(string), PropertyMetadata HeightMetadata = default(PropertyMetadata), string Italic = default(string), PropertyMetadata ItalicMetadata = default(PropertyMetadata), LocalePolicyTab LocalePolicy = default(LocalePolicyTab), string Locked = default(string), PropertyMetadata LockedMetadata = default(PropertyMetadata), string MaxLength = default(string), PropertyMetadata MaxLengthMetadata = default(PropertyMetadata), MergeField MergeField = default(MergeField), string MergeFieldXml = default(string), string Name = default(string), PropertyMetadata NameMetadata = default(PropertyMetadata), string OriginalValue = default(string), PropertyMetadata OriginalValueMetadata = default(PropertyMetadata), string PageNumber = default(string), PropertyMetadata PageNumberMetadata = default(PropertyMetadata), string RecipientId = default(string), string RecipientIdGuid = default(string), PropertyMetadata RecipientIdGuidMetadata = default(PropertyMetadata), PropertyMetadata RecipientIdMetadata = default(PropertyMetadata), string RequireAll = default(string), PropertyMetadata RequireAllMetadata = default(PropertyMetadata), string Required = default(string), PropertyMetadata RequiredMetadata = default(PropertyMetadata), string RequireInitialOnSharedChange = default(string), PropertyMetadata RequireInitialOnSharedChangeMetadata = default(PropertyMetadata), string SenderRequired = default(string), PropertyMetadata SenderRequiredMetadata = default(PropertyMetadata), string Shared = default(string), PropertyMetadata SharedMetadata = default(PropertyMetadata), SmartContractInformation SmartContractInformation = default(SmartContractInformation), string Status = default(string), PropertyMetadata StatusMetadata = default(PropertyMetadata), List<string> TabGroupLabels = default(List<string>), PropertyMetadata TabGroupLabelsMetadata = default(PropertyMetadata), string TabId = default(string), PropertyMetadata TabIdMetadata = default(PropertyMetadata), string TabLabel = default(string), PropertyMetadata TabLabelMetadata = default(PropertyMetadata), string TabOrder = default(string), PropertyMetadata TabOrderMetadata = default(PropertyMetadata), string TabType = default(string), PropertyMetadata TabTypeMetadata = default(PropertyMetadata), string TemplateLocked = default(string), PropertyMetadata TemplateLockedMetadata = default(PropertyMetadata), string TemplateRequired = default(string), PropertyMetadata TemplateRequiredMetadata = default(PropertyMetadata), string Tooltip = default(string), PropertyMetadata ToolTipMetadata = default(PropertyMetadata), string Underline = default(string), PropertyMetadata UnderlineMetadata = default(PropertyMetadata), string UseDash4 = default(string), PropertyMetadata UseDash4Metadata = default(PropertyMetadata), string ValidationMessage = default(string), PropertyMetadata ValidationMessageMetadata = default(PropertyMetadata), string ValidationPattern = default(string), PropertyMetadata ValidationPatternMetadata = default(PropertyMetadata), string Value = default(string), PropertyMetadata ValueMetadata = default(PropertyMetadata), string Width = default(string), PropertyMetadata WidthMetadata = default(PropertyMetadata), string XPosition = default(string), PropertyMetadata XPositionMetadata = default(PropertyMetadata), string YPosition = default(string), PropertyMetadata YPositionMetadata = default(PropertyMetadata))
{
this.AnchorAllowWhiteSpaceInCharacters = AnchorAllowWhiteSpaceInCharacters;
this.AnchorAllowWhiteSpaceInCharactersMetadata = AnchorAllowWhiteSpaceInCharactersMetadata;
this.AnchorCaseSensitive = AnchorCaseSensitive;
this.AnchorCaseSensitiveMetadata = AnchorCaseSensitiveMetadata;
this.AnchorHorizontalAlignment = AnchorHorizontalAlignment;
this.AnchorHorizontalAlignmentMetadata = AnchorHorizontalAlignmentMetadata;
this.AnchorIgnoreIfNotPresent = AnchorIgnoreIfNotPresent;
this.AnchorIgnoreIfNotPresentMetadata = AnchorIgnoreIfNotPresentMetadata;
this.AnchorMatchWholeWord = AnchorMatchWholeWord;
this.AnchorMatchWholeWordMetadata = AnchorMatchWholeWordMetadata;
this.AnchorString = AnchorString;
this.AnchorStringMetadata = AnchorStringMetadata;
this.AnchorTabProcessorVersion = AnchorTabProcessorVersion;
this.AnchorTabProcessorVersionMetadata = AnchorTabProcessorVersionMetadata;
this.AnchorUnits = AnchorUnits;
this.AnchorUnitsMetadata = AnchorUnitsMetadata;
this.AnchorXOffset = AnchorXOffset;
this.AnchorXOffsetMetadata = AnchorXOffsetMetadata;
this.AnchorYOffset = AnchorYOffset;
this.AnchorYOffsetMetadata = AnchorYOffsetMetadata;
this.Bold = Bold;
this.BoldMetadata = BoldMetadata;
this.ConcealValueOnDocument = ConcealValueOnDocument;
this.ConcealValueOnDocumentMetadata = ConcealValueOnDocumentMetadata;
this.ConditionalParentLabel = ConditionalParentLabel;
this.ConditionalParentLabelMetadata = ConditionalParentLabelMetadata;
this.ConditionalParentValue = ConditionalParentValue;
this.ConditionalParentValueMetadata = ConditionalParentValueMetadata;
this.CustomTabId = CustomTabId;
this.CustomTabIdMetadata = CustomTabIdMetadata;
this.DisableAutoSize = DisableAutoSize;
this.DisableAutoSizeMetadata = DisableAutoSizeMetadata;
this.DocumentId = DocumentId;
this.DocumentIdMetadata = DocumentIdMetadata;
this.ErrorDetails = ErrorDetails;
this.Font = Font;
this.FontColor = FontColor;
this.FontColorMetadata = FontColorMetadata;
this.FontMetadata = FontMetadata;
this.FontSize = FontSize;
this.FontSizeMetadata = FontSizeMetadata;
this.FormOrder = FormOrder;
this.FormOrderMetadata = FormOrderMetadata;
this.FormPageLabel = FormPageLabel;
this.FormPageLabelMetadata = FormPageLabelMetadata;
this.FormPageNumber = FormPageNumber;
this.FormPageNumberMetadata = FormPageNumberMetadata;
this.Height = Height;
this.HeightMetadata = HeightMetadata;
this.Italic = Italic;
this.ItalicMetadata = ItalicMetadata;
this.LocalePolicy = LocalePolicy;
this.Locked = Locked;
this.LockedMetadata = LockedMetadata;
this.MaxLength = MaxLength;
this.MaxLengthMetadata = MaxLengthMetadata;
this.MergeField = MergeField;
this.MergeFieldXml = MergeFieldXml;
this.Name = Name;
this.NameMetadata = NameMetadata;
this.OriginalValue = OriginalValue;
this.OriginalValueMetadata = OriginalValueMetadata;
this.PageNumber = PageNumber;
this.PageNumberMetadata = PageNumberMetadata;
this.RecipientId = RecipientId;
this.RecipientIdGuid = RecipientIdGuid;
this.RecipientIdGuidMetadata = RecipientIdGuidMetadata;
this.RecipientIdMetadata = RecipientIdMetadata;
this.RequireAll = RequireAll;
this.RequireAllMetadata = RequireAllMetadata;
this.Required = Required;
this.RequiredMetadata = RequiredMetadata;
this.RequireInitialOnSharedChange = RequireInitialOnSharedChange;
this.RequireInitialOnSharedChangeMetadata = RequireInitialOnSharedChangeMetadata;
this.SenderRequired = SenderRequired;
this.SenderRequiredMetadata = SenderRequiredMetadata;
this.Shared = Shared;
this.SharedMetadata = SharedMetadata;
this.SmartContractInformation = SmartContractInformation;
this.Status = Status;
this.StatusMetadata = StatusMetadata;
this.TabGroupLabels = TabGroupLabels;
this.TabGroupLabelsMetadata = TabGroupLabelsMetadata;
this.TabId = TabId;
this.TabIdMetadata = TabIdMetadata;
this.TabLabel = TabLabel;
this.TabLabelMetadata = TabLabelMetadata;
this.TabOrder = TabOrder;
this.TabOrderMetadata = TabOrderMetadata;
this.TabType = TabType;
this.TabTypeMetadata = TabTypeMetadata;
this.TemplateLocked = TemplateLocked;
this.TemplateLockedMetadata = TemplateLockedMetadata;
this.TemplateRequired = TemplateRequired;
this.TemplateRequiredMetadata = TemplateRequiredMetadata;
this.Tooltip = Tooltip;
this.ToolTipMetadata = ToolTipMetadata;
this.Underline = Underline;
this.UnderlineMetadata = UnderlineMetadata;
this.UseDash4 = UseDash4;
this.UseDash4Metadata = UseDash4Metadata;
this.ValidationMessage = ValidationMessage;
this.ValidationMessageMetadata = ValidationMessageMetadata;
this.ValidationPattern = ValidationPattern;
this.ValidationPatternMetadata = ValidationPatternMetadata;
this.Value = Value;
this.ValueMetadata = ValueMetadata;
this.Width = Width;
this.WidthMetadata = WidthMetadata;
this.XPosition = XPosition;
this.XPositionMetadata = XPositionMetadata;
this.YPosition = YPosition;
this.YPositionMetadata = YPositionMetadata;
}
/// <summary>
/// Gets or Sets AnchorAllowWhiteSpaceInCharacters
/// </summary>
[DataMember(Name="anchorAllowWhiteSpaceInCharacters", EmitDefaultValue=false)]
public string AnchorAllowWhiteSpaceInCharacters { get; set; }
/// <summary>
/// Gets or Sets AnchorAllowWhiteSpaceInCharactersMetadata
/// </summary>
[DataMember(Name="anchorAllowWhiteSpaceInCharactersMetadata", EmitDefaultValue=false)]
public PropertyMetadata AnchorAllowWhiteSpaceInCharactersMetadata { get; set; }
/// <summary>
/// When set to **true**, the anchor string does not consider case when matching strings in the document. The default value is **true**.
/// </summary>
/// <value>When set to **true**, the anchor string does not consider case when matching strings in the document. The default value is **true**.</value>
[DataMember(Name="anchorCaseSensitive", EmitDefaultValue=false)]
public string AnchorCaseSensitive { get; set; }
/// <summary>
/// Gets or Sets AnchorCaseSensitiveMetadata
/// </summary>
[DataMember(Name="anchorCaseSensitiveMetadata", EmitDefaultValue=false)]
public PropertyMetadata AnchorCaseSensitiveMetadata { get; set; }
/// <summary>
/// Specifies the alignment of anchor tabs with anchor strings. Possible values are **left** or **right**. The default value is **left**.
/// </summary>
/// <value>Specifies the alignment of anchor tabs with anchor strings. Possible values are **left** or **right**. The default value is **left**.</value>
[DataMember(Name="anchorHorizontalAlignment", EmitDefaultValue=false)]
public string AnchorHorizontalAlignment { get; set; }
/// <summary>
/// Gets or Sets AnchorHorizontalAlignmentMetadata
/// </summary>
[DataMember(Name="anchorHorizontalAlignmentMetadata", EmitDefaultValue=false)]
public PropertyMetadata AnchorHorizontalAlignmentMetadata { get; set; }
/// <summary>
/// When set to **true**, this tab is ignored if anchorString is not found in the document.
/// </summary>
/// <value>When set to **true**, this tab is ignored if anchorString is not found in the document.</value>
[DataMember(Name="anchorIgnoreIfNotPresent", EmitDefaultValue=false)]
public string AnchorIgnoreIfNotPresent { get; set; }
/// <summary>
/// Gets or Sets AnchorIgnoreIfNotPresentMetadata
/// </summary>
[DataMember(Name="anchorIgnoreIfNotPresentMetadata", EmitDefaultValue=false)]
public PropertyMetadata AnchorIgnoreIfNotPresentMetadata { get; set; }
/// <summary>
/// When set to **true**, the anchor string in this tab matches whole words only (strings embedded in other strings are ignored.) The default value is **true**.
/// </summary>
/// <value>When set to **true**, the anchor string in this tab matches whole words only (strings embedded in other strings are ignored.) The default value is **true**.</value>
[DataMember(Name="anchorMatchWholeWord", EmitDefaultValue=false)]
public string AnchorMatchWholeWord { get; set; }
/// <summary>
/// Gets or Sets AnchorMatchWholeWordMetadata
/// </summary>
[DataMember(Name="anchorMatchWholeWordMetadata", EmitDefaultValue=false)]
public PropertyMetadata AnchorMatchWholeWordMetadata { get; set; }
/// <summary>
/// Anchor text information for a radio button.
/// </summary>
/// <value>Anchor text information for a radio button.</value>
[DataMember(Name="anchorString", EmitDefaultValue=false)]
public string AnchorString { get; set; }
/// <summary>
/// Gets or Sets AnchorStringMetadata
/// </summary>
[DataMember(Name="anchorStringMetadata", EmitDefaultValue=false)]
public PropertyMetadata AnchorStringMetadata { get; set; }
/// <summary>
/// Gets or Sets AnchorTabProcessorVersion
/// </summary>
[DataMember(Name="anchorTabProcessorVersion", EmitDefaultValue=false)]
public string AnchorTabProcessorVersion { get; set; }
/// <summary>
/// Gets or Sets AnchorTabProcessorVersionMetadata
/// </summary>
[DataMember(Name="anchorTabProcessorVersionMetadata", EmitDefaultValue=false)]
public PropertyMetadata AnchorTabProcessorVersionMetadata { get; set; }
/// <summary>
/// Specifies units of the X and Y offset. Units could be pixels, millimeters, centimeters, or inches.
/// </summary>
/// <value>Specifies units of the X and Y offset. Units could be pixels, millimeters, centimeters, or inches.</value>
[DataMember(Name="anchorUnits", EmitDefaultValue=false)]
public string AnchorUnits { get; set; }
/// <summary>
/// Gets or Sets AnchorUnitsMetadata
/// </summary>
[DataMember(Name="anchorUnitsMetadata", EmitDefaultValue=false)]
public PropertyMetadata AnchorUnitsMetadata { get; set; }
/// <summary>
/// Specifies the X axis location of the tab, in anchorUnits, relative to the anchorString.
/// </summary>
/// <value>Specifies the X axis location of the tab, in anchorUnits, relative to the anchorString.</value>
[DataMember(Name="anchorXOffset", EmitDefaultValue=false)]
public string AnchorXOffset { get; set; }
/// <summary>
/// Gets or Sets AnchorXOffsetMetadata
/// </summary>
[DataMember(Name="anchorXOffsetMetadata", EmitDefaultValue=false)]
public PropertyMetadata AnchorXOffsetMetadata { get; set; }
/// <summary>
/// Specifies the Y axis location of the tab, in anchorUnits, relative to the anchorString.
/// </summary>
/// <value>Specifies the Y axis location of the tab, in anchorUnits, relative to the anchorString.</value>
[DataMember(Name="anchorYOffset", EmitDefaultValue=false)]
public string AnchorYOffset { get; set; }
/// <summary>
/// Gets or Sets AnchorYOffsetMetadata
/// </summary>
[DataMember(Name="anchorYOffsetMetadata", EmitDefaultValue=false)]
public PropertyMetadata AnchorYOffsetMetadata { get; set; }
/// <summary>
/// When set to **true**, the information in the tab is bold.
/// </summary>
/// <value>When set to **true**, the information in the tab is bold.</value>
[DataMember(Name="bold", EmitDefaultValue=false)]
public string Bold { get; set; }
/// <summary>
/// Gets or Sets BoldMetadata
/// </summary>
[DataMember(Name="boldMetadata", EmitDefaultValue=false)]
public PropertyMetadata BoldMetadata { get; set; }
/// <summary>
/// When set to **true**, the field appears normally while the recipient is adding or modifying the information in the field, but the data is not visible (the characters are hidden by asterisks) to any other signer or the sender. When an envelope is completed the information is available to the sender through the Form Data link in the DocuSign Console. This setting applies only to text boxes and does not affect list boxes, radio buttons, or check boxes.
/// </summary>
/// <value>When set to **true**, the field appears normally while the recipient is adding or modifying the information in the field, but the data is not visible (the characters are hidden by asterisks) to any other signer or the sender. When an envelope is completed the information is available to the sender through the Form Data link in the DocuSign Console. This setting applies only to text boxes and does not affect list boxes, radio buttons, or check boxes.</value>
[DataMember(Name="concealValueOnDocument", EmitDefaultValue=false)]
public string ConcealValueOnDocument { get; set; }
/// <summary>
/// Gets or Sets ConcealValueOnDocumentMetadata
/// </summary>
[DataMember(Name="concealValueOnDocumentMetadata", EmitDefaultValue=false)]
public PropertyMetadata ConcealValueOnDocumentMetadata { get; set; }
/// <summary>
/// For conditional fields this is the TabLabel of the parent tab that controls this tab's visibility.
/// </summary>
/// <value>For conditional fields this is the TabLabel of the parent tab that controls this tab's visibility.</value>
[DataMember(Name="conditionalParentLabel", EmitDefaultValue=false)]
public string ConditionalParentLabel { get; set; }
/// <summary>
/// Gets or Sets ConditionalParentLabelMetadata
/// </summary>
[DataMember(Name="conditionalParentLabelMetadata", EmitDefaultValue=false)]
public PropertyMetadata ConditionalParentLabelMetadata { get; set; }
/// <summary>
/// For conditional fields, this is the value of the parent tab that controls the tab's visibility. If the parent tab is a Checkbox, Radio button, Optional Signature, or Optional Initial use \"on\" as the value to show that the parent tab is active.
/// </summary>
/// <value>For conditional fields, this is the value of the parent tab that controls the tab's visibility. If the parent tab is a Checkbox, Radio button, Optional Signature, or Optional Initial use \"on\" as the value to show that the parent tab is active. </value>
[DataMember(Name="conditionalParentValue", EmitDefaultValue=false)]
public string ConditionalParentValue { get; set; }
/// <summary>
/// Gets or Sets ConditionalParentValueMetadata
/// </summary>
[DataMember(Name="conditionalParentValueMetadata", EmitDefaultValue=false)]
public PropertyMetadata ConditionalParentValueMetadata { get; set; }
/// <summary>
/// The DocuSign generated custom tab ID for the custom tab to be applied. This can only be used when adding new tabs for a recipient. When used, the new tab inherits all the custom tab properties.
/// </summary>
/// <value>The DocuSign generated custom tab ID for the custom tab to be applied. This can only be used when adding new tabs for a recipient. When used, the new tab inherits all the custom tab properties.</value>
[DataMember(Name="customTabId", EmitDefaultValue=false)]
public string CustomTabId { get; set; }
/// <summary>
/// Gets or Sets CustomTabIdMetadata
/// </summary>
[DataMember(Name="customTabIdMetadata", EmitDefaultValue=false)]
public PropertyMetadata CustomTabIdMetadata { get; set; }
/// <summary>
/// When set to **true**, disables the auto sizing of single line text boxes in the signing screen when the signer enters data. If disabled users will only be able enter as much data as the text box can hold. By default this is false. This property only affects single line text boxes.
/// </summary>
/// <value>When set to **true**, disables the auto sizing of single line text boxes in the signing screen when the signer enters data. If disabled users will only be able enter as much data as the text box can hold. By default this is false. This property only affects single line text boxes.</value>
[DataMember(Name="disableAutoSize", EmitDefaultValue=false)]
public string DisableAutoSize { get; set; }
/// <summary>
/// Gets or Sets DisableAutoSizeMetadata
/// </summary>
[DataMember(Name="disableAutoSizeMetadata", EmitDefaultValue=false)]
public PropertyMetadata DisableAutoSizeMetadata { get; set; }
/// <summary>
/// Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute.
/// </summary>
/// <value>Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute.</value>
[DataMember(Name="documentId", EmitDefaultValue=false)]
public string DocumentId { get; set; }
/// <summary>
/// Gets or Sets DocumentIdMetadata
/// </summary>
[DataMember(Name="documentIdMetadata", EmitDefaultValue=false)]
public PropertyMetadata DocumentIdMetadata { get; set; }
/// <summary>
/// Gets or Sets ErrorDetails
/// </summary>
[DataMember(Name="errorDetails", EmitDefaultValue=false)]
public ErrorDetails ErrorDetails { get; set; }
/// <summary>
/// The font to be used for the tab value. Supported Fonts: Arial, Arial, ArialNarrow, Calibri, CourierNew, Garamond, Georgia, Helvetica, LucidaConsole, Tahoma, TimesNewRoman, Trebuchet, Verdana, MSGothic, MSMincho, Default.
/// </summary>
/// <value>The font to be used for the tab value. Supported Fonts: Arial, Arial, ArialNarrow, Calibri, CourierNew, Garamond, Georgia, Helvetica, LucidaConsole, Tahoma, TimesNewRoman, Trebuchet, Verdana, MSGothic, MSMincho, Default.</value>
[DataMember(Name="font", EmitDefaultValue=false)]
public string Font { get; set; }
/// <summary>
/// The font color used for the information in the tab. Possible values are: Black, BrightBlue, BrightRed, DarkGreen, DarkRed, Gold, Green, NavyBlue, Purple, or White.
/// </summary>
/// <value>The font color used for the information in the tab. Possible values are: Black, BrightBlue, BrightRed, DarkGreen, DarkRed, Gold, Green, NavyBlue, Purple, or White.</value>
[DataMember(Name="fontColor", EmitDefaultValue=false)]
public string FontColor { get; set; }
/// <summary>
/// Gets or Sets FontColorMetadata
/// </summary>
[DataMember(Name="fontColorMetadata", EmitDefaultValue=false)]
public PropertyMetadata FontColorMetadata { get; set; }
/// <summary>
/// Gets or Sets FontMetadata
/// </summary>
[DataMember(Name="fontMetadata", EmitDefaultValue=false)]
public PropertyMetadata FontMetadata { get; set; }
/// <summary>
/// The font size used for the information in the tab. Possible values are: Size7, Size8, Size9, Size10, Size11, Size12, Size14, Size16, Size18, Size20, Size22, Size24, Size26, Size28, Size36, Size48, or Size72.
/// </summary>
/// <value>The font size used for the information in the tab. Possible values are: Size7, Size8, Size9, Size10, Size11, Size12, Size14, Size16, Size18, Size20, Size22, Size24, Size26, Size28, Size36, Size48, or Size72.</value>
[DataMember(Name="fontSize", EmitDefaultValue=false)]
public string FontSize { get; set; }
/// <summary>
/// Gets or Sets FontSizeMetadata
/// </summary>
[DataMember(Name="fontSizeMetadata", EmitDefaultValue=false)]
public PropertyMetadata FontSizeMetadata { get; set; }
/// <summary>
/// Gets or Sets FormOrder
/// </summary>
[DataMember(Name="formOrder", EmitDefaultValue=false)]
public string FormOrder { get; set; }
/// <summary>
/// Gets or Sets FormOrderMetadata
/// </summary>
[DataMember(Name="formOrderMetadata", EmitDefaultValue=false)]
public PropertyMetadata FormOrderMetadata { get; set; }
/// <summary>
/// Gets or Sets FormPageLabel
/// </summary>
[DataMember(Name="formPageLabel", EmitDefaultValue=false)]
public string FormPageLabel { get; set; }
/// <summary>
/// Gets or Sets FormPageLabelMetadata
/// </summary>
[DataMember(Name="formPageLabelMetadata", EmitDefaultValue=false)]
public PropertyMetadata FormPageLabelMetadata { get; set; }
/// <summary>
/// Gets or Sets FormPageNumber
/// </summary>
[DataMember(Name="formPageNumber", EmitDefaultValue=false)]
public string FormPageNumber { get; set; }
/// <summary>
/// Gets or Sets FormPageNumberMetadata
/// </summary>
[DataMember(Name="formPageNumberMetadata", EmitDefaultValue=false)]
public PropertyMetadata FormPageNumberMetadata { get; set; }
/// <summary>
/// Height of the tab in pixels.
/// </summary>
/// <value>Height of the tab in pixels.</value>
[DataMember(Name="height", EmitDefaultValue=false)]
public string Height { get; set; }
/// <summary>
/// Gets or Sets HeightMetadata
/// </summary>
[DataMember(Name="heightMetadata", EmitDefaultValue=false)]
public PropertyMetadata HeightMetadata { get; set; }
/// <summary>
/// When set to **true**, the information in the tab is italic.
/// </summary>
/// <value>When set to **true**, the information in the tab is italic.</value>
[DataMember(Name="italic", EmitDefaultValue=false)]
public string Italic { get; set; }
/// <summary>
/// Gets or Sets ItalicMetadata
/// </summary>
[DataMember(Name="italicMetadata", EmitDefaultValue=false)]
public PropertyMetadata ItalicMetadata { get; set; }
/// <summary>
/// Gets or Sets LocalePolicy
/// </summary>
[DataMember(Name="localePolicy", EmitDefaultValue=false)]
public LocalePolicyTab LocalePolicy { get; set; }
/// <summary>
/// When set to **true**, the signer cannot change the data of the custom tab.
/// </summary>
/// <value>When set to **true**, the signer cannot change the data of the custom tab.</value>
[DataMember(Name="locked", EmitDefaultValue=false)]
public string Locked { get; set; }
/// <summary>
/// Gets or Sets LockedMetadata
/// </summary>
[DataMember(Name="lockedMetadata", EmitDefaultValue=false)]
public PropertyMetadata LockedMetadata { get; set; }
/// <summary>
/// An optional value that describes the maximum length of the property when the property is a string.
/// </summary>
/// <value>An optional value that describes the maximum length of the property when the property is a string.</value>
[DataMember(Name="maxLength", EmitDefaultValue=false)]
public string MaxLength { get; set; }
/// <summary>
/// Gets or Sets MaxLengthMetadata
/// </summary>
[DataMember(Name="maxLengthMetadata", EmitDefaultValue=false)]
public PropertyMetadata MaxLengthMetadata { get; set; }
/// <summary>
/// Gets or Sets MergeField
/// </summary>
[DataMember(Name="mergeField", EmitDefaultValue=false)]
public MergeField MergeField { get; set; }
/// <summary>
/// Gets or Sets MergeFieldXml
/// </summary>
[DataMember(Name="mergeFieldXml", EmitDefaultValue=false)]
public string MergeFieldXml { get; set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets NameMetadata
/// </summary>
[DataMember(Name="nameMetadata", EmitDefaultValue=false)]
public PropertyMetadata NameMetadata { get; set; }
/// <summary>
/// The initial value of the tab when it was sent to the recipient.
/// </summary>
/// <value>The initial value of the tab when it was sent to the recipient. </value>
[DataMember(Name="originalValue", EmitDefaultValue=false)]
public string OriginalValue { get; set; }
/// <summary>
/// Gets or Sets OriginalValueMetadata
/// </summary>
[DataMember(Name="originalValueMetadata", EmitDefaultValue=false)]
public PropertyMetadata OriginalValueMetadata { get; set; }
/// <summary>
/// Specifies the page number on which the tab is located.
/// </summary>
/// <value>Specifies the page number on which the tab is located.</value>
[DataMember(Name="pageNumber", EmitDefaultValue=false)]
public string PageNumber { get; set; }
/// <summary>
/// Gets or Sets PageNumberMetadata
/// </summary>
[DataMember(Name="pageNumberMetadata", EmitDefaultValue=false)]
public PropertyMetadata PageNumberMetadata { get; set; }
/// <summary>
/// Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document.
/// </summary>
/// <value>Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document.</value>
[DataMember(Name="recipientId", EmitDefaultValue=false)]
public string RecipientId { get; set; }
/// <summary>
/// Gets or Sets RecipientIdGuid
/// </summary>
[DataMember(Name="recipientIdGuid", EmitDefaultValue=false)]
public string RecipientIdGuid { get; set; }
/// <summary>
/// Gets or Sets RecipientIdGuidMetadata
/// </summary>
[DataMember(Name="recipientIdGuidMetadata", EmitDefaultValue=false)]
public PropertyMetadata RecipientIdGuidMetadata { get; set; }
/// <summary>
/// Gets or Sets RecipientIdMetadata
/// </summary>
[DataMember(Name="recipientIdMetadata", EmitDefaultValue=false)]
public PropertyMetadata RecipientIdMetadata { get; set; }
/// <summary>
/// When set to **true** and shared is true, information must be entered in this field to complete the envelope.
/// </summary>
/// <value>When set to **true** and shared is true, information must be entered in this field to complete the envelope. </value>
[DataMember(Name="requireAll", EmitDefaultValue=false)]
public string RequireAll { get; set; }
/// <summary>
/// Gets or Sets RequireAllMetadata
/// </summary>
[DataMember(Name="requireAllMetadata", EmitDefaultValue=false)]
public PropertyMetadata RequireAllMetadata { get; set; }
/// <summary>
/// When set to **true**, the signer is required to fill out this tab
/// </summary>
/// <value>When set to **true**, the signer is required to fill out this tab</value>
[DataMember(Name="required", EmitDefaultValue=false)]
public string Required { get; set; }
/// <summary>
/// Gets or Sets RequiredMetadata
/// </summary>
[DataMember(Name="requiredMetadata", EmitDefaultValue=false)]
public PropertyMetadata RequiredMetadata { get; set; }
/// <summary>
/// Optional element for field markup. When set to **true**, the signer is required to initial when they modify a shared field.
/// </summary>
/// <value>Optional element for field markup. When set to **true**, the signer is required to initial when they modify a shared field.</value>
[DataMember(Name="requireInitialOnSharedChange", EmitDefaultValue=false)]
public string RequireInitialOnSharedChange { get; set; }
/// <summary>
/// Gets or Sets RequireInitialOnSharedChangeMetadata
/// </summary>
[DataMember(Name="requireInitialOnSharedChangeMetadata", EmitDefaultValue=false)]
public PropertyMetadata RequireInitialOnSharedChangeMetadata { get; set; }
/// <summary>
/// When set to **true**, the sender must populate the tab before an envelope can be sent using the template. This value tab can only be changed by modifying (PUT) the template. Tabs with a `senderRequired` value of true cannot be deleted from an envelope.
/// </summary>
/// <value>When set to **true**, the sender must populate the tab before an envelope can be sent using the template. This value tab can only be changed by modifying (PUT) the template. Tabs with a `senderRequired` value of true cannot be deleted from an envelope.</value>
[DataMember(Name="senderRequired", EmitDefaultValue=false)]
public string SenderRequired { get; set; }
/// <summary>
/// Gets or Sets SenderRequiredMetadata
/// </summary>
[DataMember(Name="senderRequiredMetadata", EmitDefaultValue=false)]
public PropertyMetadata SenderRequiredMetadata { get; set; }
/// <summary>
/// When set to **true**, this custom tab is shared.
/// </summary>
/// <value>When set to **true**, this custom tab is shared.</value>
[DataMember(Name="shared", EmitDefaultValue=false)]
public string Shared { get; set; }
/// <summary>
/// Gets or Sets SharedMetadata
/// </summary>
[DataMember(Name="sharedMetadata", EmitDefaultValue=false)]
public PropertyMetadata SharedMetadata { get; set; }
/// <summary>
/// Gets or Sets SmartContractInformation
/// </summary>
[DataMember(Name="smartContractInformation", EmitDefaultValue=false)]
public SmartContractInformation SmartContractInformation { get; set; }
/// <summary>
/// Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later.
/// </summary>
/// <value>Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later.</value>
[DataMember(Name="status", EmitDefaultValue=false)]
public string Status { get; set; }
/// <summary>
/// Gets or Sets StatusMetadata
/// </summary>
[DataMember(Name="statusMetadata", EmitDefaultValue=false)]
public PropertyMetadata StatusMetadata { get; set; }
/// <summary>
/// Gets or Sets TabGroupLabels
/// </summary>
[DataMember(Name="tabGroupLabels", EmitDefaultValue=false)]
public List<string> TabGroupLabels { get; set; }
/// <summary>
/// Gets or Sets TabGroupLabelsMetadata
/// </summary>
[DataMember(Name="tabGroupLabelsMetadata", EmitDefaultValue=false)]
public PropertyMetadata TabGroupLabelsMetadata { get; set; }
/// <summary>
/// The unique identifier for the tab. The tabid can be retrieved with the [ML:GET call].
/// </summary>
/// <value>The unique identifier for the tab. The tabid can be retrieved with the [ML:GET call]. </value>
[DataMember(Name="tabId", EmitDefaultValue=false)]
public string TabId { get; set; }
/// <summary>
/// Gets or Sets TabIdMetadata
/// </summary>
[DataMember(Name="tabIdMetadata", EmitDefaultValue=false)]
public PropertyMetadata TabIdMetadata { get; set; }
/// <summary>
/// The label string associated with the tab.
/// </summary>
/// <value>The label string associated with the tab.</value>
[DataMember(Name="tabLabel", EmitDefaultValue=false)]
public string TabLabel { get; set; }
/// <summary>
/// Gets or Sets TabLabelMetadata
/// </summary>
[DataMember(Name="tabLabelMetadata", EmitDefaultValue=false)]
public PropertyMetadata TabLabelMetadata { get; set; }
/// <summary>
/// Gets or Sets TabOrder
/// </summary>
[DataMember(Name="tabOrder", EmitDefaultValue=false)]
public string TabOrder { get; set; }
/// <summary>
/// Gets or Sets TabOrderMetadata
/// </summary>
[DataMember(Name="tabOrderMetadata", EmitDefaultValue=false)]
public PropertyMetadata TabOrderMetadata { get; set; }
/// <summary>
/// Gets or Sets TabType
/// </summary>
[DataMember(Name="tabType", EmitDefaultValue=false)]
public string TabType { get; set; }
/// <summary>
/// Gets or Sets TabTypeMetadata
/// </summary>
[DataMember(Name="tabTypeMetadata", EmitDefaultValue=false)]
public PropertyMetadata TabTypeMetadata { get; set; }
/// <summary>
/// When set to **true**, the sender cannot change any attributes of the recipient. Used only when working with template recipients.
/// </summary>
/// <value>When set to **true**, the sender cannot change any attributes of the recipient. Used only when working with template recipients. </value>
[DataMember(Name="templateLocked", EmitDefaultValue=false)]
public string TemplateLocked { get; set; }
/// <summary>
/// Gets or Sets TemplateLockedMetadata
/// </summary>
[DataMember(Name="templateLockedMetadata", EmitDefaultValue=false)]
public PropertyMetadata TemplateLockedMetadata { get; set; }
/// <summary>
/// When set to **true**, the sender may not remove the recipient. Used only when working with template recipients.
/// </summary>
/// <value>When set to **true**, the sender may not remove the recipient. Used only when working with template recipients.</value>
[DataMember(Name="templateRequired", EmitDefaultValue=false)]
public string TemplateRequired { get; set; }
/// <summary>
/// Gets or Sets TemplateRequiredMetadata
/// </summary>
[DataMember(Name="templateRequiredMetadata", EmitDefaultValue=false)]
public PropertyMetadata TemplateRequiredMetadata { get; set; }
/// <summary>
/// Gets or Sets Tooltip
/// </summary>
[DataMember(Name="tooltip", EmitDefaultValue=false)]
public string Tooltip { get; set; }
/// <summary>
/// Gets or Sets ToolTipMetadata
/// </summary>
[DataMember(Name="toolTipMetadata", EmitDefaultValue=false)]
public PropertyMetadata ToolTipMetadata { get; set; }
/// <summary>
/// When set to **true**, the information in the tab is underlined.
/// </summary>
/// <value>When set to **true**, the information in the tab is underlined.</value>
[DataMember(Name="underline", EmitDefaultValue=false)]
public string Underline { get; set; }
/// <summary>
/// Gets or Sets UnderlineMetadata
/// </summary>
[DataMember(Name="underlineMetadata", EmitDefaultValue=false)]
public PropertyMetadata UnderlineMetadata { get; set; }
/// <summary>
/// Gets or Sets UseDash4
/// </summary>
[DataMember(Name="useDash4", EmitDefaultValue=false)]
public string UseDash4 { get; set; }
/// <summary>
/// Gets or Sets UseDash4Metadata
/// </summary>
[DataMember(Name="useDash4Metadata", EmitDefaultValue=false)]
public PropertyMetadata UseDash4Metadata { get; set; }
/// <summary>
/// The message displayed if the custom tab fails input validation (either custom of embedded).
/// </summary>
/// <value>The message displayed if the custom tab fails input validation (either custom of embedded).</value>
[DataMember(Name="validationMessage", EmitDefaultValue=false)]
public string ValidationMessage { get; set; }
/// <summary>
/// Gets or Sets ValidationMessageMetadata
/// </summary>
[DataMember(Name="validationMessageMetadata", EmitDefaultValue=false)]
public PropertyMetadata ValidationMessageMetadata { get; set; }
/// <summary>
/// A regular expression used to validate input for the tab.
/// </summary>
/// <value>A regular expression used to validate input for the tab.</value>
[DataMember(Name="validationPattern", EmitDefaultValue=false)]
public string ValidationPattern { get; set; }
/// <summary>
/// Gets or Sets ValidationPatternMetadata
/// </summary>
[DataMember(Name="validationPatternMetadata", EmitDefaultValue=false)]
public PropertyMetadata ValidationPatternMetadata { get; set; }
/// <summary>
/// Specifies the value of the tab.
/// </summary>
/// <value>Specifies the value of the tab. </value>
[DataMember(Name="value", EmitDefaultValue=false)]
public string Value { get; set; }
/// <summary>
/// Gets or Sets ValueMetadata
/// </summary>
[DataMember(Name="valueMetadata", EmitDefaultValue=false)]
public PropertyMetadata ValueMetadata { get; set; }
/// <summary>
/// Width of the tab in pixels.
/// </summary>
/// <value>Width of the tab in pixels.</value>
[DataMember(Name="width", EmitDefaultValue=false)]
public string Width { get; set; }
/// <summary>
/// Gets or Sets WidthMetadata
/// </summary>
[DataMember(Name="widthMetadata", EmitDefaultValue=false)]
public PropertyMetadata WidthMetadata { get; set; }
/// <summary>
/// This indicates the horizontal offset of the object on the page. DocuSign uses 72 DPI when determining position.
/// </summary>
/// <value>This indicates the horizontal offset of the object on the page. DocuSign uses 72 DPI when determining position.</value>
[DataMember(Name="xPosition", EmitDefaultValue=false)]
public string XPosition { get; set; }
/// <summary>
/// Gets or Sets XPositionMetadata
/// </summary>
[DataMember(Name="xPositionMetadata", EmitDefaultValue=false)]
public PropertyMetadata XPositionMetadata { get; set; }
/// <summary>
/// This indicates the vertical offset of the object on the page. DocuSign uses 72 DPI when determining position.
/// </summary>
/// <value>This indicates the vertical offset of the object on the page. DocuSign uses 72 DPI when determining position.</value>
[DataMember(Name="yPosition", EmitDefaultValue=false)]
public string YPosition { get; set; }
/// <summary>
/// Gets or Sets YPositionMetadata
/// </summary>
[DataMember(Name="yPositionMetadata", EmitDefaultValue=false)]
public PropertyMetadata YPositionMetadata { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Zip {\n");
sb.Append(" AnchorAllowWhiteSpaceInCharacters: ").Append(AnchorAllowWhiteSpaceInCharacters).Append("\n");
sb.Append(" AnchorAllowWhiteSpaceInCharactersMetadata: ").Append(AnchorAllowWhiteSpaceInCharactersMetadata).Append("\n");
sb.Append(" AnchorCaseSensitive: ").Append(AnchorCaseSensitive).Append("\n");
sb.Append(" AnchorCaseSensitiveMetadata: ").Append(AnchorCaseSensitiveMetadata).Append("\n");
sb.Append(" AnchorHorizontalAlignment: ").Append(AnchorHorizontalAlignment).Append("\n");
sb.Append(" AnchorHorizontalAlignmentMetadata: ").Append(AnchorHorizontalAlignmentMetadata).Append("\n");
sb.Append(" AnchorIgnoreIfNotPresent: ").Append(AnchorIgnoreIfNotPresent).Append("\n");
sb.Append(" AnchorIgnoreIfNotPresentMetadata: ").Append(AnchorIgnoreIfNotPresentMetadata).Append("\n");
sb.Append(" AnchorMatchWholeWord: ").Append(AnchorMatchWholeWord).Append("\n");
sb.Append(" AnchorMatchWholeWordMetadata: ").Append(AnchorMatchWholeWordMetadata).Append("\n");
sb.Append(" AnchorString: ").Append(AnchorString).Append("\n");
sb.Append(" AnchorStringMetadata: ").Append(AnchorStringMetadata).Append("\n");
sb.Append(" AnchorTabProcessorVersion: ").Append(AnchorTabProcessorVersion).Append("\n");
sb.Append(" AnchorTabProcessorVersionMetadata: ").Append(AnchorTabProcessorVersionMetadata).Append("\n");
sb.Append(" AnchorUnits: ").Append(AnchorUnits).Append("\n");
sb.Append(" AnchorUnitsMetadata: ").Append(AnchorUnitsMetadata).Append("\n");
sb.Append(" AnchorXOffset: ").Append(AnchorXOffset).Append("\n");
sb.Append(" AnchorXOffsetMetadata: ").Append(AnchorXOffsetMetadata).Append("\n");
sb.Append(" AnchorYOffset: ").Append(AnchorYOffset).Append("\n");
sb.Append(" AnchorYOffsetMetadata: ").Append(AnchorYOffsetMetadata).Append("\n");
sb.Append(" Bold: ").Append(Bold).Append("\n");
sb.Append(" BoldMetadata: ").Append(BoldMetadata).Append("\n");
sb.Append(" ConcealValueOnDocument: ").Append(ConcealValueOnDocument).Append("\n");
sb.Append(" ConcealValueOnDocumentMetadata: ").Append(ConcealValueOnDocumentMetadata).Append("\n");
sb.Append(" ConditionalParentLabel: ").Append(ConditionalParentLabel).Append("\n");
sb.Append(" ConditionalParentLabelMetadata: ").Append(ConditionalParentLabelMetadata).Append("\n");
sb.Append(" ConditionalParentValue: ").Append(ConditionalParentValue).Append("\n");
sb.Append(" ConditionalParentValueMetadata: ").Append(ConditionalParentValueMetadata).Append("\n");
sb.Append(" CustomTabId: ").Append(CustomTabId).Append("\n");
sb.Append(" CustomTabIdMetadata: ").Append(CustomTabIdMetadata).Append("\n");
sb.Append(" DisableAutoSize: ").Append(DisableAutoSize).Append("\n");
sb.Append(" DisableAutoSizeMetadata: ").Append(DisableAutoSizeMetadata).Append("\n");
sb.Append(" DocumentId: ").Append(DocumentId).Append("\n");
sb.Append(" DocumentIdMetadata: ").Append(DocumentIdMetadata).Append("\n");
sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n");
sb.Append(" Font: ").Append(Font).Append("\n");
sb.Append(" FontColor: ").Append(FontColor).Append("\n");
sb.Append(" FontColorMetadata: ").Append(FontColorMetadata).Append("\n");
sb.Append(" FontMetadata: ").Append(FontMetadata).Append("\n");
sb.Append(" FontSize: ").Append(FontSize).Append("\n");
sb.Append(" FontSizeMetadata: ").Append(FontSizeMetadata).Append("\n");
sb.Append(" FormOrder: ").Append(FormOrder).Append("\n");
sb.Append(" FormOrderMetadata: ").Append(FormOrderMetadata).Append("\n");
sb.Append(" FormPageLabel: ").Append(FormPageLabel).Append("\n");
sb.Append(" FormPageLabelMetadata: ").Append(FormPageLabelMetadata).Append("\n");
sb.Append(" FormPageNumber: ").Append(FormPageNumber).Append("\n");
sb.Append(" FormPageNumberMetadata: ").Append(FormPageNumberMetadata).Append("\n");
sb.Append(" Height: ").Append(Height).Append("\n");
sb.Append(" HeightMetadata: ").Append(HeightMetadata).Append("\n");
sb.Append(" Italic: ").Append(Italic).Append("\n");
sb.Append(" ItalicMetadata: ").Append(ItalicMetadata).Append("\n");
sb.Append(" LocalePolicy: ").Append(LocalePolicy).Append("\n");
sb.Append(" Locked: ").Append(Locked).Append("\n");
sb.Append(" LockedMetadata: ").Append(LockedMetadata).Append("\n");
sb.Append(" MaxLength: ").Append(MaxLength).Append("\n");
sb.Append(" MaxLengthMetadata: ").Append(MaxLengthMetadata).Append("\n");
sb.Append(" MergeField: ").Append(MergeField).Append("\n");
sb.Append(" MergeFieldXml: ").Append(MergeFieldXml).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" NameMetadata: ").Append(NameMetadata).Append("\n");
sb.Append(" OriginalValue: ").Append(OriginalValue).Append("\n");
sb.Append(" OriginalValueMetadata: ").Append(OriginalValueMetadata).Append("\n");
sb.Append(" PageNumber: ").Append(PageNumber).Append("\n");
sb.Append(" PageNumberMetadata: ").Append(PageNumberMetadata).Append("\n");
sb.Append(" RecipientId: ").Append(RecipientId).Append("\n");
sb.Append(" RecipientIdGuid: ").Append(RecipientIdGuid).Append("\n");
sb.Append(" RecipientIdGuidMetadata: ").Append(RecipientIdGuidMetadata).Append("\n");
sb.Append(" RecipientIdMetadata: ").Append(RecipientIdMetadata).Append("\n");
sb.Append(" RequireAll: ").Append(RequireAll).Append("\n");
sb.Append(" RequireAllMetadata: ").Append(RequireAllMetadata).Append("\n");
sb.Append(" Required: ").Append(Required).Append("\n");
sb.Append(" RequiredMetadata: ").Append(RequiredMetadata).Append("\n");
sb.Append(" RequireInitialOnSharedChange: ").Append(RequireInitialOnSharedChange).Append("\n");
sb.Append(" RequireInitialOnSharedChangeMetadata: ").Append(RequireInitialOnSharedChangeMetadata).Append("\n");
sb.Append(" SenderRequired: ").Append(SenderRequired).Append("\n");
sb.Append(" SenderRequiredMetadata: ").Append(SenderRequiredMetadata).Append("\n");
sb.Append(" Shared: ").Append(Shared).Append("\n");
sb.Append(" SharedMetadata: ").Append(SharedMetadata).Append("\n");
sb.Append(" SmartContractInformation: ").Append(SmartContractInformation).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" StatusMetadata: ").Append(StatusMetadata).Append("\n");
sb.Append(" TabGroupLabels: ").Append(TabGroupLabels).Append("\n");
sb.Append(" TabGroupLabelsMetadata: ").Append(TabGroupLabelsMetadata).Append("\n");
sb.Append(" TabId: ").Append(TabId).Append("\n");
sb.Append(" TabIdMetadata: ").Append(TabIdMetadata).Append("\n");
sb.Append(" TabLabel: ").Append(TabLabel).Append("\n");
sb.Append(" TabLabelMetadata: ").Append(TabLabelMetadata).Append("\n");
sb.Append(" TabOrder: ").Append(TabOrder).Append("\n");
sb.Append(" TabOrderMetadata: ").Append(TabOrderMetadata).Append("\n");
sb.Append(" TabType: ").Append(TabType).Append("\n");
sb.Append(" TabTypeMetadata: ").Append(TabTypeMetadata).Append("\n");
sb.Append(" TemplateLocked: ").Append(TemplateLocked).Append("\n");
sb.Append(" TemplateLockedMetadata: ").Append(TemplateLockedMetadata).Append("\n");
sb.Append(" TemplateRequired: ").Append(TemplateRequired).Append("\n");
sb.Append(" TemplateRequiredMetadata: ").Append(TemplateRequiredMetadata).Append("\n");
sb.Append(" Tooltip: ").Append(Tooltip).Append("\n");
sb.Append(" ToolTipMetadata: ").Append(ToolTipMetadata).Append("\n");
sb.Append(" Underline: ").Append(Underline).Append("\n");
sb.Append(" UnderlineMetadata: ").Append(UnderlineMetadata).Append("\n");
sb.Append(" UseDash4: ").Append(UseDash4).Append("\n");
sb.Append(" UseDash4Metadata: ").Append(UseDash4Metadata).Append("\n");
sb.Append(" ValidationMessage: ").Append(ValidationMessage).Append("\n");
sb.Append(" ValidationMessageMetadata: ").Append(ValidationMessageMetadata).Append("\n");
sb.Append(" ValidationPattern: ").Append(ValidationPattern).Append("\n");
sb.Append(" ValidationPatternMetadata: ").Append(ValidationPatternMetadata).Append("\n");
sb.Append(" Value: ").Append(Value).Append("\n");
sb.Append(" ValueMetadata: ").Append(ValueMetadata).Append("\n");
sb.Append(" Width: ").Append(Width).Append("\n");
sb.Append(" WidthMetadata: ").Append(WidthMetadata).Append("\n");
sb.Append(" XPosition: ").Append(XPosition).Append("\n");
sb.Append(" XPositionMetadata: ").Append(XPositionMetadata).Append("\n");
sb.Append(" YPosition: ").Append(YPosition).Append("\n");
sb.Append(" YPositionMetadata: ").Append(YPositionMetadata).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as Zip);
}
/// <summary>
/// Returns true if Zip instances are equal
/// </summary>
/// <param name="other">Instance of Zip to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Zip other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.AnchorAllowWhiteSpaceInCharacters == other.AnchorAllowWhiteSpaceInCharacters ||
this.AnchorAllowWhiteSpaceInCharacters != null &&
this.AnchorAllowWhiteSpaceInCharacters.Equals(other.AnchorAllowWhiteSpaceInCharacters)
) &&
(
this.AnchorAllowWhiteSpaceInCharactersMetadata == other.AnchorAllowWhiteSpaceInCharactersMetadata ||
this.AnchorAllowWhiteSpaceInCharactersMetadata != null &&
this.AnchorAllowWhiteSpaceInCharactersMetadata.Equals(other.AnchorAllowWhiteSpaceInCharactersMetadata)
) &&
(
this.AnchorCaseSensitive == other.AnchorCaseSensitive ||
this.AnchorCaseSensitive != null &&
this.AnchorCaseSensitive.Equals(other.AnchorCaseSensitive)
) &&
(
this.AnchorCaseSensitiveMetadata == other.AnchorCaseSensitiveMetadata ||
this.AnchorCaseSensitiveMetadata != null &&
this.AnchorCaseSensitiveMetadata.Equals(other.AnchorCaseSensitiveMetadata)
) &&
(
this.AnchorHorizontalAlignment == other.AnchorHorizontalAlignment ||
this.AnchorHorizontalAlignment != null &&
this.AnchorHorizontalAlignment.Equals(other.AnchorHorizontalAlignment)
) &&
(
this.AnchorHorizontalAlignmentMetadata == other.AnchorHorizontalAlignmentMetadata ||
this.AnchorHorizontalAlignmentMetadata != null &&
this.AnchorHorizontalAlignmentMetadata.Equals(other.AnchorHorizontalAlignmentMetadata)
) &&
(
this.AnchorIgnoreIfNotPresent == other.AnchorIgnoreIfNotPresent ||
this.AnchorIgnoreIfNotPresent != null &&
this.AnchorIgnoreIfNotPresent.Equals(other.AnchorIgnoreIfNotPresent)
) &&
(
this.AnchorIgnoreIfNotPresentMetadata == other.AnchorIgnoreIfNotPresentMetadata ||
this.AnchorIgnoreIfNotPresentMetadata != null &&
this.AnchorIgnoreIfNotPresentMetadata.Equals(other.AnchorIgnoreIfNotPresentMetadata)
) &&
(
this.AnchorMatchWholeWord == other.AnchorMatchWholeWord ||
this.AnchorMatchWholeWord != null &&
this.AnchorMatchWholeWord.Equals(other.AnchorMatchWholeWord)
) &&
(
this.AnchorMatchWholeWordMetadata == other.AnchorMatchWholeWordMetadata ||
this.AnchorMatchWholeWordMetadata != null &&
this.AnchorMatchWholeWordMetadata.Equals(other.AnchorMatchWholeWordMetadata)
) &&
(
this.AnchorString == other.AnchorString ||
this.AnchorString != null &&
this.AnchorString.Equals(other.AnchorString)
) &&
(
this.AnchorStringMetadata == other.AnchorStringMetadata ||
this.AnchorStringMetadata != null &&
this.AnchorStringMetadata.Equals(other.AnchorStringMetadata)
) &&
(
this.AnchorTabProcessorVersion == other.AnchorTabProcessorVersion ||
this.AnchorTabProcessorVersion != null &&
this.AnchorTabProcessorVersion.Equals(other.AnchorTabProcessorVersion)
) &&
(
this.AnchorTabProcessorVersionMetadata == other.AnchorTabProcessorVersionMetadata ||
this.AnchorTabProcessorVersionMetadata != null &&
this.AnchorTabProcessorVersionMetadata.Equals(other.AnchorTabProcessorVersionMetadata)
) &&
(
this.AnchorUnits == other.AnchorUnits ||
this.AnchorUnits != null &&
this.AnchorUnits.Equals(other.AnchorUnits)
) &&
(
this.AnchorUnitsMetadata == other.AnchorUnitsMetadata ||
this.AnchorUnitsMetadata != null &&
this.AnchorUnitsMetadata.Equals(other.AnchorUnitsMetadata)
) &&
(
this.AnchorXOffset == other.AnchorXOffset ||
this.AnchorXOffset != null &&
this.AnchorXOffset.Equals(other.AnchorXOffset)
) &&
(
this.AnchorXOffsetMetadata == other.AnchorXOffsetMetadata ||
this.AnchorXOffsetMetadata != null &&
this.AnchorXOffsetMetadata.Equals(other.AnchorXOffsetMetadata)
) &&
(
this.AnchorYOffset == other.AnchorYOffset ||
this.AnchorYOffset != null &&
this.AnchorYOffset.Equals(other.AnchorYOffset)
) &&
(
this.AnchorYOffsetMetadata == other.AnchorYOffsetMetadata ||
this.AnchorYOffsetMetadata != null &&
this.AnchorYOffsetMetadata.Equals(other.AnchorYOffsetMetadata)
) &&
(
this.Bold == other.Bold ||
this.Bold != null &&
this.Bold.Equals(other.Bold)
) &&
(
this.BoldMetadata == other.BoldMetadata ||
this.BoldMetadata != null &&
this.BoldMetadata.Equals(other.BoldMetadata)
) &&
(
this.ConcealValueOnDocument == other.ConcealValueOnDocument ||
this.ConcealValueOnDocument != null &&
this.ConcealValueOnDocument.Equals(other.ConcealValueOnDocument)
) &&
(
this.ConcealValueOnDocumentMetadata == other.ConcealValueOnDocumentMetadata ||
this.ConcealValueOnDocumentMetadata != null &&
this.ConcealValueOnDocumentMetadata.Equals(other.ConcealValueOnDocumentMetadata)
) &&
(
this.ConditionalParentLabel == other.ConditionalParentLabel ||
this.ConditionalParentLabel != null &&
this.ConditionalParentLabel.Equals(other.ConditionalParentLabel)
) &&
(
this.ConditionalParentLabelMetadata == other.ConditionalParentLabelMetadata ||
this.ConditionalParentLabelMetadata != null &&
this.ConditionalParentLabelMetadata.Equals(other.ConditionalParentLabelMetadata)
) &&
(
this.ConditionalParentValue == other.ConditionalParentValue ||
this.ConditionalParentValue != null &&
this.ConditionalParentValue.Equals(other.ConditionalParentValue)
) &&
(
this.ConditionalParentValueMetadata == other.ConditionalParentValueMetadata ||
this.ConditionalParentValueMetadata != null &&
this.ConditionalParentValueMetadata.Equals(other.ConditionalParentValueMetadata)
) &&
(
this.CustomTabId == other.CustomTabId ||
this.CustomTabId != null &&
this.CustomTabId.Equals(other.CustomTabId)
) &&
(
this.CustomTabIdMetadata == other.CustomTabIdMetadata ||
this.CustomTabIdMetadata != null &&
this.CustomTabIdMetadata.Equals(other.CustomTabIdMetadata)
) &&
(
this.DisableAutoSize == other.DisableAutoSize ||
this.DisableAutoSize != null &&
this.DisableAutoSize.Equals(other.DisableAutoSize)
) &&
(
this.DisableAutoSizeMetadata == other.DisableAutoSizeMetadata ||
this.DisableAutoSizeMetadata != null &&
this.DisableAutoSizeMetadata.Equals(other.DisableAutoSizeMetadata)
) &&
(
this.DocumentId == other.DocumentId ||
this.DocumentId != null &&
this.DocumentId.Equals(other.DocumentId)
) &&
(
this.DocumentIdMetadata == other.DocumentIdMetadata ||
this.DocumentIdMetadata != null &&
this.DocumentIdMetadata.Equals(other.DocumentIdMetadata)
) &&
(
this.ErrorDetails == other.ErrorDetails ||
this.ErrorDetails != null &&
this.ErrorDetails.Equals(other.ErrorDetails)
) &&
(
this.Font == other.Font ||
this.Font != null &&
this.Font.Equals(other.Font)
) &&
(
this.FontColor == other.FontColor ||
this.FontColor != null &&
this.FontColor.Equals(other.FontColor)
) &&
(
this.FontColorMetadata == other.FontColorMetadata ||
this.FontColorMetadata != null &&
this.FontColorMetadata.Equals(other.FontColorMetadata)
) &&
(
this.FontMetadata == other.FontMetadata ||
this.FontMetadata != null &&
this.FontMetadata.Equals(other.FontMetadata)
) &&
(
this.FontSize == other.FontSize ||
this.FontSize != null &&
this.FontSize.Equals(other.FontSize)
) &&
(
this.FontSizeMetadata == other.FontSizeMetadata ||
this.FontSizeMetadata != null &&
this.FontSizeMetadata.Equals(other.FontSizeMetadata)
) &&
(
this.FormOrder == other.FormOrder ||
this.FormOrder != null &&
this.FormOrder.Equals(other.FormOrder)
) &&
(
this.FormOrderMetadata == other.FormOrderMetadata ||
this.FormOrderMetadata != null &&
this.FormOrderMetadata.Equals(other.FormOrderMetadata)
) &&
(
this.FormPageLabel == other.FormPageLabel ||
this.FormPageLabel != null &&
this.FormPageLabel.Equals(other.FormPageLabel)
) &&
(
this.FormPageLabelMetadata == other.FormPageLabelMetadata ||
this.FormPageLabelMetadata != null &&
this.FormPageLabelMetadata.Equals(other.FormPageLabelMetadata)
) &&
(
this.FormPageNumber == other.FormPageNumber ||
this.FormPageNumber != null &&
this.FormPageNumber.Equals(other.FormPageNumber)
) &&
(
this.FormPageNumberMetadata == other.FormPageNumberMetadata ||
this.FormPageNumberMetadata != null &&
this.FormPageNumberMetadata.Equals(other.FormPageNumberMetadata)
) &&
(
this.Height == other.Height ||
this.Height != null &&
this.Height.Equals(other.Height)
) &&
(
this.HeightMetadata == other.HeightMetadata ||
this.HeightMetadata != null &&
this.HeightMetadata.Equals(other.HeightMetadata)
) &&
(
this.Italic == other.Italic ||
this.Italic != null &&
this.Italic.Equals(other.Italic)
) &&
(
this.ItalicMetadata == other.ItalicMetadata ||
this.ItalicMetadata != null &&
this.ItalicMetadata.Equals(other.ItalicMetadata)
) &&
(
this.LocalePolicy == other.LocalePolicy ||
this.LocalePolicy != null &&
this.LocalePolicy.Equals(other.LocalePolicy)
) &&
(
this.Locked == other.Locked ||
this.Locked != null &&
this.Locked.Equals(other.Locked)
) &&
(
this.LockedMetadata == other.LockedMetadata ||
this.LockedMetadata != null &&
this.LockedMetadata.Equals(other.LockedMetadata)
) &&
(
this.MaxLength == other.MaxLength ||
this.MaxLength != null &&
this.MaxLength.Equals(other.MaxLength)
) &&
(
this.MaxLengthMetadata == other.MaxLengthMetadata ||
this.MaxLengthMetadata != null &&
this.MaxLengthMetadata.Equals(other.MaxLengthMetadata)
) &&
(
this.MergeField == other.MergeField ||
this.MergeField != null &&
this.MergeField.Equals(other.MergeField)
) &&
(
this.MergeFieldXml == other.MergeFieldXml ||
this.MergeFieldXml != null &&
this.MergeFieldXml.Equals(other.MergeFieldXml)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.NameMetadata == other.NameMetadata ||
this.NameMetadata != null &&
this.NameMetadata.Equals(other.NameMetadata)
) &&
(
this.OriginalValue == other.OriginalValue ||
this.OriginalValue != null &&
this.OriginalValue.Equals(other.OriginalValue)
) &&
(
this.OriginalValueMetadata == other.OriginalValueMetadata ||
this.OriginalValueMetadata != null &&
this.OriginalValueMetadata.Equals(other.OriginalValueMetadata)
) &&
(
this.PageNumber == other.PageNumber ||
this.PageNumber != null &&
this.PageNumber.Equals(other.PageNumber)
) &&
(
this.PageNumberMetadata == other.PageNumberMetadata ||
this.PageNumberMetadata != null &&
this.PageNumberMetadata.Equals(other.PageNumberMetadata)
) &&
(
this.RecipientId == other.RecipientId ||
this.RecipientId != null &&
this.RecipientId.Equals(other.RecipientId)
) &&
(
this.RecipientIdGuid == other.RecipientIdGuid ||
this.RecipientIdGuid != null &&
this.RecipientIdGuid.Equals(other.RecipientIdGuid)
) &&
(
this.RecipientIdGuidMetadata == other.RecipientIdGuidMetadata ||
this.RecipientIdGuidMetadata != null &&
this.RecipientIdGuidMetadata.Equals(other.RecipientIdGuidMetadata)
) &&
(
this.RecipientIdMetadata == other.RecipientIdMetadata ||
this.RecipientIdMetadata != null &&
this.RecipientIdMetadata.Equals(other.RecipientIdMetadata)
) &&
(
this.RequireAll == other.RequireAll ||
this.RequireAll != null &&
this.RequireAll.Equals(other.RequireAll)
) &&
(
this.RequireAllMetadata == other.RequireAllMetadata ||
this.RequireAllMetadata != null &&
this.RequireAllMetadata.Equals(other.RequireAllMetadata)
) &&
(
this.Required == other.Required ||
this.Required != null &&
this.Required.Equals(other.Required)
) &&
(
this.RequiredMetadata == other.RequiredMetadata ||
this.RequiredMetadata != null &&
this.RequiredMetadata.Equals(other.RequiredMetadata)
) &&
(
this.RequireInitialOnSharedChange == other.RequireInitialOnSharedChange ||
this.RequireInitialOnSharedChange != null &&
this.RequireInitialOnSharedChange.Equals(other.RequireInitialOnSharedChange)
) &&
(
this.RequireInitialOnSharedChangeMetadata == other.RequireInitialOnSharedChangeMetadata ||
this.RequireInitialOnSharedChangeMetadata != null &&
this.RequireInitialOnSharedChangeMetadata.Equals(other.RequireInitialOnSharedChangeMetadata)
) &&
(
this.SenderRequired == other.SenderRequired ||
this.SenderRequired != null &&
this.SenderRequired.Equals(other.SenderRequired)
) &&
(
this.SenderRequiredMetadata == other.SenderRequiredMetadata ||
this.SenderRequiredMetadata != null &&
this.SenderRequiredMetadata.Equals(other.SenderRequiredMetadata)
) &&
(
this.Shared == other.Shared ||
this.Shared != null &&
this.Shared.Equals(other.Shared)
) &&
(
this.SharedMetadata == other.SharedMetadata ||
this.SharedMetadata != null &&
this.SharedMetadata.Equals(other.SharedMetadata)
) &&
(
this.SmartContractInformation == other.SmartContractInformation ||
this.SmartContractInformation != null &&
this.SmartContractInformation.Equals(other.SmartContractInformation)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.StatusMetadata == other.StatusMetadata ||
this.StatusMetadata != null &&
this.StatusMetadata.Equals(other.StatusMetadata)
) &&
(
this.TabGroupLabels == other.TabGroupLabels ||
this.TabGroupLabels != null &&
this.TabGroupLabels.SequenceEqual(other.TabGroupLabels)
) &&
(
this.TabGroupLabelsMetadata == other.TabGroupLabelsMetadata ||
this.TabGroupLabelsMetadata != null &&
this.TabGroupLabelsMetadata.Equals(other.TabGroupLabelsMetadata)
) &&
(
this.TabId == other.TabId ||
this.TabId != null &&
this.TabId.Equals(other.TabId)
) &&
(
this.TabIdMetadata == other.TabIdMetadata ||
this.TabIdMetadata != null &&
this.TabIdMetadata.Equals(other.TabIdMetadata)
) &&
(
this.TabLabel == other.TabLabel ||
this.TabLabel != null &&
this.TabLabel.Equals(other.TabLabel)
) &&
(
this.TabLabelMetadata == other.TabLabelMetadata ||
this.TabLabelMetadata != null &&
this.TabLabelMetadata.Equals(other.TabLabelMetadata)
) &&
(
this.TabOrder == other.TabOrder ||
this.TabOrder != null &&
this.TabOrder.Equals(other.TabOrder)
) &&
(
this.TabOrderMetadata == other.TabOrderMetadata ||
this.TabOrderMetadata != null &&
this.TabOrderMetadata.Equals(other.TabOrderMetadata)
) &&
(
this.TabType == other.TabType ||
this.TabType != null &&
this.TabType.Equals(other.TabType)
) &&
(
this.TabTypeMetadata == other.TabTypeMetadata ||
this.TabTypeMetadata != null &&
this.TabTypeMetadata.Equals(other.TabTypeMetadata)
) &&
(
this.TemplateLocked == other.TemplateLocked ||
this.TemplateLocked != null &&
this.TemplateLocked.Equals(other.TemplateLocked)
) &&
(
this.TemplateLockedMetadata == other.TemplateLockedMetadata ||
this.TemplateLockedMetadata != null &&
this.TemplateLockedMetadata.Equals(other.TemplateLockedMetadata)
) &&
(
this.TemplateRequired == other.TemplateRequired ||
this.TemplateRequired != null &&
this.TemplateRequired.Equals(other.TemplateRequired)
) &&
(
this.TemplateRequiredMetadata == other.TemplateRequiredMetadata ||
this.TemplateRequiredMetadata != null &&
this.TemplateRequiredMetadata.Equals(other.TemplateRequiredMetadata)
) &&
(
this.Tooltip == other.Tooltip ||
this.Tooltip != null &&
this.Tooltip.Equals(other.Tooltip)
) &&
(
this.ToolTipMetadata == other.ToolTipMetadata ||
this.ToolTipMetadata != null &&
this.ToolTipMetadata.Equals(other.ToolTipMetadata)
) &&
(
this.Underline == other.Underline ||
this.Underline != null &&
this.Underline.Equals(other.Underline)
) &&
(
this.UnderlineMetadata == other.UnderlineMetadata ||
this.UnderlineMetadata != null &&
this.UnderlineMetadata.Equals(other.UnderlineMetadata)
) &&
(
this.UseDash4 == other.UseDash4 ||
this.UseDash4 != null &&
this.UseDash4.Equals(other.UseDash4)
) &&
(
this.UseDash4Metadata == other.UseDash4Metadata ||
this.UseDash4Metadata != null &&
this.UseDash4Metadata.Equals(other.UseDash4Metadata)
) &&
(
this.ValidationMessage == other.ValidationMessage ||
this.ValidationMessage != null &&
this.ValidationMessage.Equals(other.ValidationMessage)
) &&
(
this.ValidationMessageMetadata == other.ValidationMessageMetadata ||
this.ValidationMessageMetadata != null &&
this.ValidationMessageMetadata.Equals(other.ValidationMessageMetadata)
) &&
(
this.ValidationPattern == other.ValidationPattern ||
this.ValidationPattern != null &&
this.ValidationPattern.Equals(other.ValidationPattern)
) &&
(
this.ValidationPatternMetadata == other.ValidationPatternMetadata ||
this.ValidationPatternMetadata != null &&
this.ValidationPatternMetadata.Equals(other.ValidationPatternMetadata)
) &&
(
this.Value == other.Value ||
this.Value != null &&
this.Value.Equals(other.Value)
) &&
(
this.ValueMetadata == other.ValueMetadata ||
this.ValueMetadata != null &&
this.ValueMetadata.Equals(other.ValueMetadata)
) &&
(
this.Width == other.Width ||
this.Width != null &&
this.Width.Equals(other.Width)
) &&
(
this.WidthMetadata == other.WidthMetadata ||
this.WidthMetadata != null &&
this.WidthMetadata.Equals(other.WidthMetadata)
) &&
(
this.XPosition == other.XPosition ||
this.XPosition != null &&
this.XPosition.Equals(other.XPosition)
) &&
(
this.XPositionMetadata == other.XPositionMetadata ||
this.XPositionMetadata != null &&
this.XPositionMetadata.Equals(other.XPositionMetadata)
) &&
(
this.YPosition == other.YPosition ||
this.YPosition != null &&
this.YPosition.Equals(other.YPosition)
) &&
(
this.YPositionMetadata == other.YPositionMetadata ||
this.YPositionMetadata != null &&
this.YPositionMetadata.Equals(other.YPositionMetadata)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.AnchorAllowWhiteSpaceInCharacters != null)
hash = hash * 59 + this.AnchorAllowWhiteSpaceInCharacters.GetHashCode();
if (this.AnchorAllowWhiteSpaceInCharactersMetadata != null)
hash = hash * 59 + this.AnchorAllowWhiteSpaceInCharactersMetadata.GetHashCode();
if (this.AnchorCaseSensitive != null)
hash = hash * 59 + this.AnchorCaseSensitive.GetHashCode();
if (this.AnchorCaseSensitiveMetadata != null)
hash = hash * 59 + this.AnchorCaseSensitiveMetadata.GetHashCode();
if (this.AnchorHorizontalAlignment != null)
hash = hash * 59 + this.AnchorHorizontalAlignment.GetHashCode();
if (this.AnchorHorizontalAlignmentMetadata != null)
hash = hash * 59 + this.AnchorHorizontalAlignmentMetadata.GetHashCode();
if (this.AnchorIgnoreIfNotPresent != null)
hash = hash * 59 + this.AnchorIgnoreIfNotPresent.GetHashCode();
if (this.AnchorIgnoreIfNotPresentMetadata != null)
hash = hash * 59 + this.AnchorIgnoreIfNotPresentMetadata.GetHashCode();
if (this.AnchorMatchWholeWord != null)
hash = hash * 59 + this.AnchorMatchWholeWord.GetHashCode();
if (this.AnchorMatchWholeWordMetadata != null)
hash = hash * 59 + this.AnchorMatchWholeWordMetadata.GetHashCode();
if (this.AnchorString != null)
hash = hash * 59 + this.AnchorString.GetHashCode();
if (this.AnchorStringMetadata != null)
hash = hash * 59 + this.AnchorStringMetadata.GetHashCode();
if (this.AnchorTabProcessorVersion != null)
hash = hash * 59 + this.AnchorTabProcessorVersion.GetHashCode();
if (this.AnchorTabProcessorVersionMetadata != null)
hash = hash * 59 + this.AnchorTabProcessorVersionMetadata.GetHashCode();
if (this.AnchorUnits != null)
hash = hash * 59 + this.AnchorUnits.GetHashCode();
if (this.AnchorUnitsMetadata != null)
hash = hash * 59 + this.AnchorUnitsMetadata.GetHashCode();
if (this.AnchorXOffset != null)
hash = hash * 59 + this.AnchorXOffset.GetHashCode();
if (this.AnchorXOffsetMetadata != null)
hash = hash * 59 + this.AnchorXOffsetMetadata.GetHashCode();
if (this.AnchorYOffset != null)
hash = hash * 59 + this.AnchorYOffset.GetHashCode();
if (this.AnchorYOffsetMetadata != null)
hash = hash * 59 + this.AnchorYOffsetMetadata.GetHashCode();
if (this.Bold != null)
hash = hash * 59 + this.Bold.GetHashCode();
if (this.BoldMetadata != null)
hash = hash * 59 + this.BoldMetadata.GetHashCode();
if (this.ConcealValueOnDocument != null)
hash = hash * 59 + this.ConcealValueOnDocument.GetHashCode();
if (this.ConcealValueOnDocumentMetadata != null)
hash = hash * 59 + this.ConcealValueOnDocumentMetadata.GetHashCode();
if (this.ConditionalParentLabel != null)
hash = hash * 59 + this.ConditionalParentLabel.GetHashCode();
if (this.ConditionalParentLabelMetadata != null)
hash = hash * 59 + this.ConditionalParentLabelMetadata.GetHashCode();
if (this.ConditionalParentValue != null)
hash = hash * 59 + this.ConditionalParentValue.GetHashCode();
if (this.ConditionalParentValueMetadata != null)
hash = hash * 59 + this.ConditionalParentValueMetadata.GetHashCode();
if (this.CustomTabId != null)
hash = hash * 59 + this.CustomTabId.GetHashCode();
if (this.CustomTabIdMetadata != null)
hash = hash * 59 + this.CustomTabIdMetadata.GetHashCode();
if (this.DisableAutoSize != null)
hash = hash * 59 + this.DisableAutoSize.GetHashCode();
if (this.DisableAutoSizeMetadata != null)
hash = hash * 59 + this.DisableAutoSizeMetadata.GetHashCode();
if (this.DocumentId != null)
hash = hash * 59 + this.DocumentId.GetHashCode();
if (this.DocumentIdMetadata != null)
hash = hash * 59 + this.DocumentIdMetadata.GetHashCode();
if (this.ErrorDetails != null)
hash = hash * 59 + this.ErrorDetails.GetHashCode();
if (this.Font != null)
hash = hash * 59 + this.Font.GetHashCode();
if (this.FontColor != null)
hash = hash * 59 + this.FontColor.GetHashCode();
if (this.FontColorMetadata != null)
hash = hash * 59 + this.FontColorMetadata.GetHashCode();
if (this.FontMetadata != null)
hash = hash * 59 + this.FontMetadata.GetHashCode();
if (this.FontSize != null)
hash = hash * 59 + this.FontSize.GetHashCode();
if (this.FontSizeMetadata != null)
hash = hash * 59 + this.FontSizeMetadata.GetHashCode();
if (this.FormOrder != null)
hash = hash * 59 + this.FormOrder.GetHashCode();
if (this.FormOrderMetadata != null)
hash = hash * 59 + this.FormOrderMetadata.GetHashCode();
if (this.FormPageLabel != null)
hash = hash * 59 + this.FormPageLabel.GetHashCode();
if (this.FormPageLabelMetadata != null)
hash = hash * 59 + this.FormPageLabelMetadata.GetHashCode();
if (this.FormPageNumber != null)
hash = hash * 59 + this.FormPageNumber.GetHashCode();
if (this.FormPageNumberMetadata != null)
hash = hash * 59 + this.FormPageNumberMetadata.GetHashCode();
if (this.Height != null)
hash = hash * 59 + this.Height.GetHashCode();
if (this.HeightMetadata != null)
hash = hash * 59 + this.HeightMetadata.GetHashCode();
if (this.Italic != null)
hash = hash * 59 + this.Italic.GetHashCode();
if (this.ItalicMetadata != null)
hash = hash * 59 + this.ItalicMetadata.GetHashCode();
if (this.LocalePolicy != null)
hash = hash * 59 + this.LocalePolicy.GetHashCode();
if (this.Locked != null)
hash = hash * 59 + this.Locked.GetHashCode();
if (this.LockedMetadata != null)
hash = hash * 59 + this.LockedMetadata.GetHashCode();
if (this.MaxLength != null)
hash = hash * 59 + this.MaxLength.GetHashCode();
if (this.MaxLengthMetadata != null)
hash = hash * 59 + this.MaxLengthMetadata.GetHashCode();
if (this.MergeField != null)
hash = hash * 59 + this.MergeField.GetHashCode();
if (this.MergeFieldXml != null)
hash = hash * 59 + this.MergeFieldXml.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.NameMetadata != null)
hash = hash * 59 + this.NameMetadata.GetHashCode();
if (this.OriginalValue != null)
hash = hash * 59 + this.OriginalValue.GetHashCode();
if (this.OriginalValueMetadata != null)
hash = hash * 59 + this.OriginalValueMetadata.GetHashCode();
if (this.PageNumber != null)
hash = hash * 59 + this.PageNumber.GetHashCode();
if (this.PageNumberMetadata != null)
hash = hash * 59 + this.PageNumberMetadata.GetHashCode();
if (this.RecipientId != null)
hash = hash * 59 + this.RecipientId.GetHashCode();
if (this.RecipientIdGuid != null)
hash = hash * 59 + this.RecipientIdGuid.GetHashCode();
if (this.RecipientIdGuidMetadata != null)
hash = hash * 59 + this.RecipientIdGuidMetadata.GetHashCode();
if (this.RecipientIdMetadata != null)
hash = hash * 59 + this.RecipientIdMetadata.GetHashCode();
if (this.RequireAll != null)
hash = hash * 59 + this.RequireAll.GetHashCode();
if (this.RequireAllMetadata != null)
hash = hash * 59 + this.RequireAllMetadata.GetHashCode();
if (this.Required != null)
hash = hash * 59 + this.Required.GetHashCode();
if (this.RequiredMetadata != null)
hash = hash * 59 + this.RequiredMetadata.GetHashCode();
if (this.RequireInitialOnSharedChange != null)
hash = hash * 59 + this.RequireInitialOnSharedChange.GetHashCode();
if (this.RequireInitialOnSharedChangeMetadata != null)
hash = hash * 59 + this.RequireInitialOnSharedChangeMetadata.GetHashCode();
if (this.SenderRequired != null)
hash = hash * 59 + this.SenderRequired.GetHashCode();
if (this.SenderRequiredMetadata != null)
hash = hash * 59 + this.SenderRequiredMetadata.GetHashCode();
if (this.Shared != null)
hash = hash * 59 + this.Shared.GetHashCode();
if (this.SharedMetadata != null)
hash = hash * 59 + this.SharedMetadata.GetHashCode();
if (this.SmartContractInformation != null)
hash = hash * 59 + this.SmartContractInformation.GetHashCode();
if (this.Status != null)
hash = hash * 59 + this.Status.GetHashCode();
if (this.StatusMetadata != null)
hash = hash * 59 + this.StatusMetadata.GetHashCode();
if (this.TabGroupLabels != null)
hash = hash * 59 + this.TabGroupLabels.GetHashCode();
if (this.TabGroupLabelsMetadata != null)
hash = hash * 59 + this.TabGroupLabelsMetadata.GetHashCode();
if (this.TabId != null)
hash = hash * 59 + this.TabId.GetHashCode();
if (this.TabIdMetadata != null)
hash = hash * 59 + this.TabIdMetadata.GetHashCode();
if (this.TabLabel != null)
hash = hash * 59 + this.TabLabel.GetHashCode();
if (this.TabLabelMetadata != null)
hash = hash * 59 + this.TabLabelMetadata.GetHashCode();
if (this.TabOrder != null)
hash = hash * 59 + this.TabOrder.GetHashCode();
if (this.TabOrderMetadata != null)
hash = hash * 59 + this.TabOrderMetadata.GetHashCode();
if (this.TabType != null)
hash = hash * 59 + this.TabType.GetHashCode();
if (this.TabTypeMetadata != null)
hash = hash * 59 + this.TabTypeMetadata.GetHashCode();
if (this.TemplateLocked != null)
hash = hash * 59 + this.TemplateLocked.GetHashCode();
if (this.TemplateLockedMetadata != null)
hash = hash * 59 + this.TemplateLockedMetadata.GetHashCode();
if (this.TemplateRequired != null)
hash = hash * 59 + this.TemplateRequired.GetHashCode();
if (this.TemplateRequiredMetadata != null)
hash = hash * 59 + this.TemplateRequiredMetadata.GetHashCode();
if (this.Tooltip != null)
hash = hash * 59 + this.Tooltip.GetHashCode();
if (this.ToolTipMetadata != null)
hash = hash * 59 + this.ToolTipMetadata.GetHashCode();
if (this.Underline != null)
hash = hash * 59 + this.Underline.GetHashCode();
if (this.UnderlineMetadata != null)
hash = hash * 59 + this.UnderlineMetadata.GetHashCode();
if (this.UseDash4 != null)
hash = hash * 59 + this.UseDash4.GetHashCode();
if (this.UseDash4Metadata != null)
hash = hash * 59 + this.UseDash4Metadata.GetHashCode();
if (this.ValidationMessage != null)
hash = hash * 59 + this.ValidationMessage.GetHashCode();
if (this.ValidationMessageMetadata != null)
hash = hash * 59 + this.ValidationMessageMetadata.GetHashCode();
if (this.ValidationPattern != null)
hash = hash * 59 + this.ValidationPattern.GetHashCode();
if (this.ValidationPatternMetadata != null)
hash = hash * 59 + this.ValidationPatternMetadata.GetHashCode();
if (this.Value != null)
hash = hash * 59 + this.Value.GetHashCode();
if (this.ValueMetadata != null)
hash = hash * 59 + this.ValueMetadata.GetHashCode();
if (this.Width != null)
hash = hash * 59 + this.Width.GetHashCode();
if (this.WidthMetadata != null)
hash = hash * 59 + this.WidthMetadata.GetHashCode();
if (this.XPosition != null)
hash = hash * 59 + this.XPosition.GetHashCode();
if (this.XPositionMetadata != null)
hash = hash * 59 + this.XPositionMetadata.GetHashCode();
if (this.YPosition != null)
hash = hash * 59 + this.YPosition.GetHashCode();
if (this.YPositionMetadata != null)
hash = hash * 59 + this.YPositionMetadata.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 61.309356
| 6,074
| 0.603576
|
[
"MIT"
] |
frikke/docusign-csharp-client
|
sdk/src/DocuSign.eSign/Model/Zip.cs
| 113,361
|
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("spmeta2.demo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("spmeta2.demo")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ebebe8e0-dbcb-482c-8547-940e7c9a1e6c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.756757
| 84
| 0.743737
|
[
"MIT"
] |
sergeisnitko/spday2018-pnp-spmeta2-demo
|
SPMeta2/spmeta2.core/Properties/AssemblyInfo.cs
| 1,400
|
C#
|
using FluentValidation;
namespace Gear.DynamicReporting.ProjectManagement.Domain.ReportFilters.Commands.AddUserReportActivityStatuses
{
public class AddUserReportActivityStatusesCommandValidator<TUserIdType> : AbstractValidator<AddUserReportActivityStatusesCommand<TUserIdType>>
{
public AddUserReportActivityStatusesCommandValidator()
{
RuleFor(x => x.UserId)
.NotEmpty();
RuleFor(x => x.ReportId)
.NotEmpty();
RuleFor(x => x.ActivityStatuses)
.NotEmpty();
}
}
}
| 29.4
| 146
| 0.656463
|
[
"MIT"
] |
indrivo/bizon360_pm
|
IndrivoPM/Gear.DynamicReporting.ProjectManagement/Domain/ReportFilters/Commands/AddUserReportActivityStatuses/AddUserReportActivityStatusesCommandValidator.cs
| 590
|
C#
|
using System;
using System.Threading.Tasks;
using AppInsights.EnterpriseTelemetry;
using System.Collections.Generic;
using AppInsights.EnterpriseTelemetry.Context;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.FeatureFlighting.Common.Caching;
namespace Microsoft.FeatureFlighting.Caching
{
public class InMemoryCache : ICache
{
private readonly IMemoryCache _memoryCache;
private readonly string _tenant;
private readonly ILogger _logger;
public InMemoryCache(IMemoryCache memoryCache, string tenant, ILogger logger)
{
_memoryCache = memoryCache;
_tenant = tenant;
_logger = logger;
}
public Task<List<string>> GetList(string key, string correlationId, string transactionId)
{
key = GetTenantKey(key);
// NOTE: Get calls are not logged to avoid too much logging
_memoryCache.TryGetValue(key, out List<string> cachedValues);
if (cachedValues != null)
return Task.FromResult(cachedValues);
return Task.FromResult<List<string>>(null);
}
public Task SetList(string key, List<string> values, string correlationId, string transactionId, int relativeExpirationMins = -1)
{
key = GetTenantKey(key);
var dependencyContext = new DependencyContext(CacheLogContext.GetMetadata("InMemory", "SET_LIST", key));
dependencyContext.AddProperty("Relative Expiration", relativeExpirationMins.ToString());
if (relativeExpirationMins > 0)
_memoryCache.Set(key, values, TimeSpan.FromMinutes(relativeExpirationMins));
else
_memoryCache.Set(key, values);
dependencyContext.CompleteDependency();
_logger.Log(dependencyContext);
return Task.CompletedTask;
}
public Task Delete(string key, string correlationId, string transactionId)
{
key = GetTenantKey(key);
var dependencyContext = new DependencyContext(CacheLogContext.GetMetadata("InMemory", "DELETE", key));
_memoryCache.Remove(key);
dependencyContext.CompleteDependency();
_logger.Log(dependencyContext);
return Task.CompletedTask;
}
private string GetTenantKey(string key) =>
$"{_tenant}_{key}";
}
}
| 37.9375
| 137
| 0.650741
|
[
"MIT"
] |
microsoft/FeatureFlightingManagement
|
src/service/Cache/InMemoryCache.cs
| 2,430
|
C#
|
namespace Bike.Ast
{
using System.Collections.Generic;
public partial class ArrayLiteral : ExprNode
{
public readonly List<ExprNode> Expressions = new List<ExprNode>();
public bool IsRange;
}
}
| 20.727273
| 74
| 0.666667
|
[
"MIT"
] |
buunguyen/bike
|
src/Bike/Ast/Literals/ArrayLiteral.cs
| 230
|
C#
|
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EntityCollectionWithReferencesRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type DeviceRegisteredOwnersCollectionWithReferencesRequest.
/// </summary>
public partial class DeviceRegisteredOwnersCollectionWithReferencesRequest : BaseRequest, IDeviceRegisteredOwnersCollectionWithReferencesRequest
{
/// <summary>
/// Constructs a new DeviceRegisteredOwnersCollectionWithReferencesRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public DeviceRegisteredOwnersCollectionWithReferencesRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IDeviceRegisteredOwnersCollectionWithReferencesPage> GetAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.GET;
var response = await this.SendAsync<DeviceRegisteredOwnersCollectionWithReferencesResponse>(null, cancellationToken).ConfigureAwait(false);
if (response?.Value?.CurrentPage != null)
{
response.Value.InitializeNextPageRequest(this.Client, response.NextLink);
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
return response.Value;
}
return null;
}
/// <summary>
/// Gets the collection page and returns a <see cref="GraphResponse{DeviceRegisteredOwnersCollectionWithReferencesResponse}"/> object.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse{DeviceRegisteredOwnersCollectionWithReferencesResponse}"/> object.</returns>
public System.Threading.Tasks.Task<GraphResponse<DeviceRegisteredOwnersCollectionWithReferencesResponse>> GetResponseAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.GET;
return this.SendAsyncWithGraphResponse<DeviceRegisteredOwnersCollectionWithReferencesResponse>(null, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IDeviceRegisteredOwnersCollectionWithReferencesRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IDeviceRegisteredOwnersCollectionWithReferencesRequest Expand(Expression<Func<DirectoryObject, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IDeviceRegisteredOwnersCollectionWithReferencesRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IDeviceRegisteredOwnersCollectionWithReferencesRequest Select(Expression<Func<DirectoryObject, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IDeviceRegisteredOwnersCollectionWithReferencesRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IDeviceRegisteredOwnersCollectionWithReferencesRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IDeviceRegisteredOwnersCollectionWithReferencesRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IDeviceRegisteredOwnersCollectionWithReferencesRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| 43.344262
| 177
| 0.613212
|
[
"MIT"
] |
Aliases/msgraph-sdk-dotnet
|
src/Microsoft.Graph/Generated/requests/DeviceRegisteredOwnersCollectionWithReferencesRequest.cs
| 7,932
|
C#
|
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\d3d11.h(11391,5)
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential)]
public partial struct D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC__union_0
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public byte[] __bits;
public D3D11_TEX2D_VPIV Texture2D { get => InteropRuntime.Get<D3D11_TEX2D_VPIV>(__bits, 0, 64); set { if (__bits == null) __bits = new byte[8]; InteropRuntime.Set<D3D11_TEX2D_VPIV>(value, __bits, 0, 64); } }
}
}
| 45.133333
| 215
| 0.731167
|
[
"MIT"
] |
riQQ/DirectN
|
DirectN/DirectN/Generated/D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC__union_0.cs
| 679
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using com.rherlt.NetCoreBasicAuth.BasicAuthentication;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace com.rherlt.NetCoreBasicAuth.WebApplication.Controllers
{
[Route("api/[controller]")]
public class AuthController : Controller
{
// GET: api/Auth
[HttpGet]
[BasicAuthentication("someone@example.com", "passw0rd123")]
public string Get()
{
return $"Authorized User:{HttpContext.User.Identity.Name}";
}
}
}
| 29.791667
| 116
| 0.678322
|
[
"MIT"
] |
rherlt/Blog-NetCoreBasicAuth
|
src/com.rherlt.NetCoreBasicAuth.WebApplication/Controllers/AuthController.cs
| 717
|
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.AwsNative.DynamoDB.Outputs
{
[OutputType]
public sealed class TableProjection
{
public readonly ImmutableArray<string> NonKeyAttributes;
public readonly string? ProjectionType;
[OutputConstructor]
private TableProjection(
ImmutableArray<string> nonKeyAttributes,
string? projectionType)
{
NonKeyAttributes = nonKeyAttributes;
ProjectionType = projectionType;
}
}
}
| 26.533333
| 81
| 0.684673
|
[
"Apache-2.0"
] |
AaronFriel/pulumi-aws-native
|
sdk/dotnet/DynamoDB/Outputs/TableProjection.cs
| 796
|
C#
|
/*************************************************************************************
Extended WPF Toolkit
Copyright (C) 2007-2013 Xceed Software Inc.
This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license
For more features, controls, and fast professional support,
pick up the Plus Edition at http://xceed.com/wpf_toolkit
Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids
***********************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows;
namespace Xceed.Wpf.DataGrid.Views
{
internal class VirtualizingFixedCellSubPanel : FixedCellSubPanel
{
public VirtualizingFixedCellSubPanel( FixedCellPanel parentPanel )
: base( parentPanel )
{
}
// Measure horizontally.
protected override Size MeasureOverride( Size constraint )
{
// This can be null when the parent Row is not prepared yet.
var columnVirtualizationManager = this.ColumnVirtualizationManager;
if( columnVirtualizationManager == null )
return new Size();
var parentRow = this.ParentPanel.ParentRow;
if( parentRow == null )
return new Size();
var desiredSize = new Size();
var columnToVisibleWidth = columnVirtualizationManager.GetFieldNameToWidth( parentRow.LevelCache );
//This using prevents a WeakEvent to be raised to execute UpdateChildren() in FixedCellPanel, as it is already up to date at this point.
using( this.ParentPanel.ParentRowCells.SetIsUpdating() )
{
foreach( var cell in this.GetCellsToLayout() )
{
double width;
if( columnToVisibleWidth.TryGetValue( cell.FieldName, out width ) )
{
cell.Measure( new Size( width, constraint.Height ) );
}
else
{
// The cell will be hidden.
cell.Measure( new Size() );
}
if( cell.DesiredSize.Height > desiredSize.Height )
{
desiredSize.Height = cell.DesiredSize.Height;
}
}
}
desiredSize.Width = columnVirtualizationManager.ScrollingColumnsWidth;
return desiredSize;
}
// Arrange horizontally.
protected override Size ArrangeOverride( Size arrangeSize )
{
// This can be null when the parent Row is not prepared yet.
var columnVirtualizationManager = this.ColumnVirtualizationManager;
if( columnVirtualizationManager == null )
return new Size();
var parentRow = this.ParentPanel.ParentRow;
if( parentRow == null )
return new Size();
var dataGridContext = this.DataGridContext;
var scrollViewer = ( dataGridContext != null ) ? dataGridContext.DataGridControl.ScrollViewer : null;
var columnToVisibleOffset = columnVirtualizationManager.GetFieldNameToOffset( parentRow.LevelCache );
var horizontalOffset = ( scrollViewer != null ) ? scrollViewer.HorizontalOffset : 0d;
var fixedColumnsWidth = columnVirtualizationManager.FixedColumnsWidth;
var compensationOffset = columnVirtualizationManager.FirstColumnCompensationOffset;
var finalRect = new Rect( arrangeSize );
//This using prevents a WeakEvent to be raised to execute UpdateChildren() in FixedCellPanel, as it is already up to date at this point.
using( this.ParentPanel.ParentRowCells.SetIsUpdating() )
{
foreach( var cell in this.GetCellsToLayout() )
{
var offset = this.CalculateCellOffset( cell.ParentColumn, columnToVisibleOffset, horizontalOffset, fixedColumnsWidth, compensationOffset );
finalRect.X = offset.X;
finalRect.Width = cell.DesiredSize.Width;
finalRect.Height = Math.Max( arrangeSize.Height, cell.DesiredSize.Height );
cell.Arrange( finalRect );
}
}
return arrangeSize;
}
protected override IEnumerable<string> GetVisibleFieldsName()
{
var columnVirtualizationManager = this.ColumnVirtualizationManager;
if( columnVirtualizationManager == null )
return new string[ 0 ];
return columnVirtualizationManager.GetScrollingFieldNames( this.ParentPanel.ParentRow.LevelCache );
}
internal override Point CalculateCellOffset( ColumnBase column )
{
Debug.Assert( column != null );
var row = this.ParentPanel.ParentRow;
if( ( column != null ) && ( row != null ) )
{
var dataGridContext = this.DataGridContext;
var columnVirtualizationManager = this.ColumnVirtualizationManager;
if( ( dataGridContext != null ) && ( columnVirtualizationManager != null ) )
{
var columnToVisibleOffset = columnVirtualizationManager.GetFieldNameToOffset( row.LevelCache );
var scrollViewer = dataGridContext.DataGridControl.ScrollViewer;
var horizontalOffset = ( scrollViewer != null ) ? scrollViewer.HorizontalOffset : 0d;
var fixedColumnsWidth = columnVirtualizationManager.FixedColumnsWidth;
var compensationOffset = columnVirtualizationManager.FirstColumnCompensationOffset;
return this.CalculateCellOffset( column, columnToVisibleOffset, horizontalOffset, fixedColumnsWidth, compensationOffset );
}
}
return new Point();
}
private Point CalculateCellOffset( ColumnBase column, IColumnInfoCollection<double> columnsOffset, double horizontalOffset, double fixedColumnsWidth, double compensationOffset )
{
if( column == null )
return new Point();
Debug.Assert( columnsOffset != null );
Debug.Assert( columnsOffset.Contains( column ) );
var columnOffset = columnsOffset[ column ];
// Calculate the offset of the cell's parent column:
// The original offset of the Column
// - the horizontal offset of the ScrollViewer to scroll to the right
// - the width of the fixed columns since we are in the Scrolling FixedCellSubPanel
// + the compensation offset used in master detail to avoid scrolling when not required
return new Point( columnOffset - horizontalOffset - fixedColumnsWidth + compensationOffset, 0d );
}
private IEnumerable<Cell> GetCellsToLayout()
{
var visibleCells = this.GetVisibleCells();
// Check out if there are any out of view cells that needs to be layouted for different purpose. In case of a BringIntoView, the cell
// must be layouted in order to find out the target location. In case of a non recyclable cell, the cell must be arranged out of view.
var permanentScrollingFieldNames = this.ParentPanel.PermanentScrollingFieldNames;
if( !permanentScrollingFieldNames.Any() )
return visibleCells;
// Make sure we have access to the collection containing the additional cells to be layouted.
var parentRowCells = this.ParentPanel.ParentRowCells;
if( parentRowCells == null )
return visibleCells;
return this.GetCellsToLayout( visibleCells, permanentScrollingFieldNames, parentRowCells );
}
private IEnumerable<Cell> GetCellsToLayout( IEnumerable<Cell> visibleCells, IEnumerable<string> permanentScrollingFieldNames, VirtualizingCellCollection cellsCollection )
{
List<string> unhandledCells = permanentScrollingFieldNames.ToList();
foreach( var cell in visibleCells )
{
unhandledCells.Remove( cell.FieldName );
yield return cell;
}
foreach( var fieldName in unhandledCells )
{
var cell = cellsCollection.GetCell( fieldName, false );
Debug.Assert( cell != null );
yield return cell;
}
}
}
}
| 38.116505
| 181
| 0.67728
|
[
"Unlicense"
] |
visiontrail/LMT2018
|
Src/SCMT/UI/DataGrid/Xceed.Wpf.DataGrid/Views/(ColumnVirtualization)/VirtualizingFixedCellSubPanel.cs
| 7,854
|
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("02.ExtractSentences byKeyword")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02.ExtractSentences byKeyword")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b7aacec0-7776-4c0c-a0f3-fcb14b538d78")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.540541
| 84
| 0.751052
|
[
"MIT"
] |
sevgin0954/SoftUni-Projects
|
Programming - Fundamentals/Regular Expressions (RegEx) - Exercises/02.ExtractSentences byKeyword/Properties/AssemblyInfo.cs
| 1,429
|
C#
|
/**
* Copyright 2015 Canada Health Infoway, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: $LastChangedBy: tmcgrady $
* Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $
* Revision: $LastChangedRevision: 2623 $
*/
/* This class was auto-generated by the message builder generator tools. */
using Ca.Infoway.Messagebuilder;
namespace Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03.Domainvalue {
public interface ActInvoiceDetailTaxCode : Code {
}
}
| 37.785714
| 83
| 0.712665
|
[
"ECL-2.0",
"Apache-2.0"
] |
CanadaHealthInfoway/message-builder-dotnet
|
message-builder-release-ab-r02_04_03/Main/Ca/Infoway/Messagebuilder/Model/Ab_r02_04_03/Domainvalue/ActInvoiceDetailTaxCode.cs
| 1,058
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.