content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using Native.Tool.Log4net; using System; using System.Collections.Generic; using System.Data.SQLite; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Native.Tool.SQLite { public class SQLiteHelper { /// <summary> /// 数据库连接定义 /// </summary> public static SQLiteConnection dbConnection; ///// <summary> ///// SQL命令定义 ///// </summary> //private static SQLiteCommand dbCommand; /// <summary> /// 数据读取定义 /// </summary> private static SQLiteDataReader dataReader; ///// <summary> ///// 数据库连接字符串定义 ///// </summary> //private SQLiteConnectionStringBuilder dbConnectionstr; ///// <summary> ///// 构造函数 ///// </summary> ///// <param name="connectionString">连接SQLite库字符串</param> /* public SqLiteHelper(string connectionString) { try { dbConnection = new SQLiteConnection(); dbConnectionstr = new SQLiteConnectionStringBuilder(); dbConnectionstr.DataSource = connectionString; dbConnectionstr.Version = 3; //dbConnectionstr.Password = "admin"; //设置密码,SQLite ADO.NET实现了数据库密码保护 dbConnection.ConnectionString = dbConnectionstr.ToString(); dbConnection.Open(); } catch (Exception e) { Log(e.ToString()); Log4Helper.Error(e.Message); } } */ /// <summary> /// 创建数据库文件 /// </summary> /// <param name="DBFilePath"></param> /// <returns></returns> public static Boolean NewDbFile(string DBFilePath) { try { SQLiteConnection.CreateFile(DBFilePath); return true; } catch (Exception ex) { Log4Helper.Error("新建数据库文件" + DBFilePath + "失败:" + ex.Message); throw new Exception("新建数据库文件" + DBFilePath + "失败:" + ex.Message); } } /// <summary> /// 执行SQL命令 /// </summary> /// <returns>The query.</returns> /// <param name="queryString">SQL命令字符串</param> public static SQLiteDataReader ExecuteQuery(string queryString) { Log4Helper.Debug("执行sql命令开始"); Log4Helper.Debug("语句是:" + queryString); try { //dbCommand = dbConnection.CreateCommand(); //dbCommand.CommandText = queryString; //设置SQL语句 //dataReader = dbCommand.ExecuteReader(); using (SQLiteConnection conn = new SQLiteConnection("Data Source=BilibiliPush.db")) { conn.Open(); using (SQLiteCommand cmd = new SQLiteCommand(queryString, conn)) { dataReader = cmd.ExecuteReader(); } conn.Close(); } } catch (Exception e) { Log(e.Message); Log4Helper.Error(e.Message); } Log4Helper.Debug("执行sql命令结束"); return dataReader; } ///// <summary> ///// 关闭数据库连接 ///// </summary> /* public static void CloseConnection() { //销毁Command if (dbCommand != null) { dbCommand.Cancel(); } dbCommand = null; //销毁Reader if (dataReader != null) { dataReader.Close(); } dataReader = null; //销毁Connection if (dbConnection != null) { dbConnection.Close(); } dbConnection = null; } */ /// <summary> /// 检查是否存在 /// </summary> /// <param name="tableName">数据表名称</param> /// <returns>返回:是/否</returns> public static bool CheckTable(string tableName) { try { Log4Helper.Debug("调用CheckTable结束"); string queryString = "SELECT count(*) FROM sqlite_master WHERE type= 'table' AND name = '" + tableName + "' ;"; Log4Helper.Debug("sql语句:" + queryString); using (SQLiteConnection conn = new SQLiteConnection("Data Source=BilibiliPush.db")) { conn.Open(); using (SQLiteCommand cmd = new SQLiteCommand(queryString, conn)) { dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { if (dataReader[0].ToString() != "0") { return true; } } } dataReader.Close(); dataReader.Dispose(); conn.Close(); conn.Dispose(); } } catch (Exception e) { Log4Helper.Error(e.Message); } Log4Helper.Debug("调用CheckTable结束"); return false; } /// <summary> /// 读取整张数据表 /// </summary> /// <returns>The full table.</returns> /// <param name="tableName">数据表名称</param> /// <param name="l"></param> public static String[] ReadFullTable(string tableName, int l) { string[] arrData = new string[l]; try { Log4Helper.Debug("调用ReadFullTable开始"); string queryString = "SELECT * FROM " + tableName; //获取所有可用的字段 Log4Helper.Debug("sql语句:" + queryString); using (SQLiteConnection conn = new SQLiteConnection("Data Source=BilibiliPush.db")) { conn.Open(); using (SQLiteCommand cmd = new SQLiteCommand(queryString, conn)) { dataReader = cmd.ExecuteReader(); int i = 0; while (dataReader.Read()) { arrData[i] = dataReader.GetString(dataReader.GetOrdinal("UID")); i++; } } dataReader.Close(); dataReader.Dispose(); conn.Close(); conn.Dispose(); } } catch (Exception e) { Log4Helper.Error(e.Message); } Log4Helper.Debug("调用ReadFullTable结束"); return arrData; } /// <summary> /// 读取整张数据表 /// </summary> /// <returns>The full table.</returns> /// <param name="tableName">数据表名称</param> public static SQLiteDataReader ReadFullTable(string tableName) { try { Log4Helper.Debug("调用ReadFullTable开始"); string queryString = "SELECT * FROM " + tableName; //获取所有可用的字段 Log4Helper.Debug("sql语句:" + queryString); using (SQLiteConnection conn = new SQLiteConnection("Data Source=BilibiliPush.db")) { conn.Open(); using (SQLiteCommand cmd = new SQLiteCommand(queryString, conn)) { dataReader = cmd.ExecuteReader(); } conn.Close(); } } catch (Exception e) { Log4Helper.Error(e.Message); } Log4Helper.Debug("调用ReadFullTable结束"); return dataReader; } /// <summary> /// 计算整张表的行数 /// </summary> /// <returns>count.</returns> /// <param name="tableName">数据表名称</param> public static int CountRows(string tableName) { int count = 0; try { Log4Helper.Debug("调用CountRows开始"); string queryString = "SELECT * FROM " + tableName; //获取所有可用的字段 Log4Helper.Debug("sql语句:" + queryString); using (SQLiteConnection conn = new SQLiteConnection("Data Source=BilibiliPush.db")) { conn.Open(); using (SQLiteCommand cmd = new SQLiteCommand(queryString, conn)) { dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { count++; } Log4Helper.Debug("调用CountRows结束"); } dataReader.Close(); dataReader.Dispose(); conn.Close(); conn.Dispose(); } } catch (Exception e) { Log4Helper.Error(e.Message); } return count; } /// <summary> /// 读取指定字段的值 /// </summary> /// <returns>count.</returns> /// <param name="tableName">数据表名称</param> /// <param name="item"></param> /// <param name="colName"></param> /// <param name="colValue"></param> public static string ReadValue(string tableName, string item, string colName, string colValue) { string str = ""; //查询数据库里当前colName对应的item try { Log4Helper.Debug("调用ReadValue开始"); string queryString = "SELECT " + item + " FROM " + tableName + " where " + colName + " = " + colValue; Log4Helper.Debug("sql语句:" + queryString); using (SQLiteConnection conn = new SQLiteConnection("Data Source=BilibiliPush.db")) { conn.Open(); using (SQLiteCommand cmd = new SQLiteCommand(queryString, conn)) { dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { if ((dataReader[0].ToString() == "") || (dataReader[0] == null)) { str = ""; break; } else { str = dataReader[0].ToString(); break; } } } dataReader.Close(); dataReader.Dispose(); conn.Close(); conn.Dispose(); } } catch (Exception e) { Log4Helper.Error(e.Message); } Log4Helper.Debug("调用ReadValue结束"); return str; } /// <summary> /// 向指定数据表中插入数据 /// </summary> /// <returns>The values.</returns> /// <param name="tableName">数据表名称</param> /// <param name="values">插入的数值</param> public static void InsertValues(string tableName, string[] values) { ////获取数据表中字段数目 //int fieldCount = ReadFullTable(tableName).FieldCount; ////当插入的数据长度不等于字段数目时引发异常 //if (values.Length != fieldCount) //{ // throw new SQLiteException("values.Length!=fieldCount"); //} try { Log4Helper.Debug("调用InsertValues开始"); string queryString = "INSERT INTO " + tableName + " VALUES (" + "'" + values[0] + "'"; for (int i = 1; i < values.Length; i++) { queryString += ", " + "'" + values[i] + "'"; } queryString += " )"; Log4Helper.Debug("sql语句:" + queryString); using (SQLiteConnection conn = new SQLiteConnection("Data Source=BilibiliPush.db")) { conn.Open(); using (SQLiteCommand cmd = new SQLiteCommand(queryString, conn)) { dataReader = cmd.ExecuteReader(); } dataReader.Close(); dataReader.Dispose(); conn.Close(); conn.Dispose(); } } catch (Exception e) { Log4Helper.Error(e.Message); } Log4Helper.Debug("调用InsertValues结束"); } /// <summary> /// 更新指定数据表内的数据 /// </summary> /// <returns>The values.</returns> /// <param name="tableName">数据表名称</param> /// <param name="colNames">字段名</param> /// <param name="colValues">字段名对应的数据</param> /// <param name="key">关键字</param> /// <param name="value">关键字对应的值</param> /// <param name="operation">运算符:=,<,>,...,默认“=”</param> public static SQLiteDataReader UpdateValues(string tableName, string colNames, string colValues, string key, string operation, string value) { // operation="="; //默认 try { Log4Helper.Debug("调用UpdateValues开始"); string queryString = "UPDATE " + tableName + " SET " + colNames + "=" + "'" + colValues + "'" + " WHERE " + key + operation + "'" + value + "'"; Log4Helper.Debug("sql语句:" + queryString); using (SQLiteConnection conn = new SQLiteConnection("Data Source=BilibiliPush.db")) { conn.Open(); using (SQLiteCommand cmd = new SQLiteCommand(queryString, conn)) { dataReader = cmd.ExecuteReader(); } dataReader.Close(); dataReader.Dispose(); conn.Close(); conn.Dispose(); } } catch (Exception e) { Log4Helper.Error(e.Message); } Log4Helper.Debug("调用UpdateValues结束"); return dataReader; } /// <summary> /// 更新指定数据表内的数据 /// </summary> /// <returns>The values.</returns> /// <param name="tableName">数据表名称</param> /// <param name="colNames">字段名</param> /// <param name="colValues">字段名对应的数据</param> /// <param name="key">关键字</param> /// <param name="value">关键字对应的值</param> /// <param name="operation">运算符:=,<,>,...,默认“=”</param> public static SQLiteDataReader UpdateValues(string tableName, string[] colNames, string[] colValues, string key, string value, string operation) { // operation="="; //默认 //当字段名称和字段数值不对应时引发异常 if (colNames.Length != colValues.Length) { throw new SQLiteException("colNames.Length!=colValues.Length"); } string queryString = "UPDATE " + tableName + " SET " + colNames[0] + "=" + "'" + colValues[0] + "'"; for (int i = 1; i < colValues.Length; i++) { queryString += ", " + colNames[i] + "=" + "'" + colValues[i] + "'"; } queryString += " WHERE " + key + operation + "'" + value + "'"; return ExecuteQuery(queryString); } /// <summary> /// 更新指定数据表内的数据 /// </summary> /// <returns>The values.</returns> /// <param name="tableName">数据表名称</param> /// <param name="colNames">字段名</param> /// <param name="colValues">字段名对应的数据</param> /// <param name="key">关键字</param> /// <param name="value">关键字对应的值</param> /// <param name="operation">运算符:=,<,>,...,默认“=”</param> public SQLiteDataReader UpdateValues(string tableName, string[] colNames, string[] colValues, string key1, string value1, string operation, string key2, string value2) { // operation="="; //默认 //当字段名称和字段数值不对应时引发异常 if (colNames.Length != colValues.Length) { throw new SQLiteException("colNames.Length!=colValues.Length"); } string queryString = "UPDATE " + tableName + " SET " + colNames[0] + "=" + "'" + colValues[0] + "'"; for (int i = 1; i < colValues.Length; i++) { queryString += ", " + colNames[i] + "=" + "'" + colValues[i] + "'"; } //表中已经设置成int类型的不需要再次添加‘单引号’,而字符串类型的数据需要进行添加‘单引号’ queryString += " WHERE " + key1 + operation + "'" + value1 + "'" + "OR " + key2 + operation + "'" + value2 + "'"; return ExecuteQuery(queryString); } /// <summary> /// 删除指定数据表内的数据 /// </summary> /// <returns>The values.</returns> /// <param name="tableName">数据表名称</param> /// <param name="colNames">字段名</param> /// <param name="colValues">字段名对应的数据</param> /// <param name="operations"></param> public SQLiteDataReader DeleteValuesOR(string tableName, string[] colNames, string[] colValues, string[] operations) { //当字段名称和字段数值不对应时引发异常 if (colNames.Length != colValues.Length || operations.Length != colNames.Length || operations.Length != colValues.Length) { throw new SQLiteException("colNames.Length!=colValues.Length || operations.Length!=colNames.Length || operations.Length!=colValues.Length"); } string queryString = "DELETE FROM " + tableName + " WHERE " + colNames[0] + operations[0] + "'" + colValues[0] + "'"; for (int i = 1; i < colValues.Length; i++) { queryString += "OR " + colNames[i] + operations[0] + "'" + colValues[i] + "'"; } return ExecuteQuery(queryString); } /// <summary> /// 删除指定数据表内的数据 /// </summary> /// <returns>The values.</returns> /// <param name="tableName">数据表名称</param> /// <param name="colNames">字段名</param> /// <param name="colValues">字段名对应的数据</param> /// <param name="operations"></param> public SQLiteDataReader DeleteValuesAND(string tableName, string[] colNames, string[] colValues, string[] operations) { //当字段名称和字段数值不对应时引发异常 if (colNames.Length != colValues.Length || operations.Length != colNames.Length || operations.Length != colValues.Length) { throw new SQLiteException("colNames.Length!=colValues.Length || operations.Length!=colNames.Length || operations.Length!=colValues.Length"); } string queryString = "DELETE FROM " + tableName + " WHERE " + colNames[0] + operations[0] + "'" + colValues[0] + "'"; for (int i = 1; i < colValues.Length; i++) { queryString += " AND " + colNames[i] + operations[i] + "'" + colValues[i] + "'"; } return ExecuteQuery(queryString); } /// <summary> /// 创建数据表 /// </summary> + /// <returns>The table.</returns> /// <param name="tableName">数据表名</param> /// <param name="colNames">字段名</param> /// <param name="colTypes">字段名类型</param> public SQLiteDataReader CreateTable(string tableName, string[] colNames, string[] colTypes) { string queryString = "CREATE TABLE IF NOT EXISTS " + tableName + "( " + colNames[0] + " " + colTypes[0]; for (int i = 1; i < colNames.Length; i++) { queryString += ", " + colNames[i] + " " + colTypes[i]; } queryString += " ) "; return ExecuteQuery(queryString); } /// <summary> /// Reads the table. /// </summary> /// <returns>The table.</returns> /// <param name="tableName">Table name.</param> /// <param name="items">Items.</param> /// <param name="colNames">Col names.</param> /// <param name="operations">Operations.</param> /// <param name="colValues">Col values.</param> public SQLiteDataReader ReadTable(string tableName, string[] items, string[] colNames, string[] operations, string[] colValues) { string queryString = "SELECT " + items[0]; for (int i = 1; i < items.Length; i++) { queryString += ", " + items[i]; } queryString += " FROM " + tableName + " WHERE " + colNames[0] + " " + operations[0] + " " + colValues[0]; for (int i = 1; i < colNames.Length; i++) { queryString += " AND " + colNames[i] + " " + operations[i] + " " + colValues[i] + " "; } return ExecuteQuery(queryString); } /// <summary> /// 本类log /// </summary> /// <param name="s"></param> static void Log(string s) { Console.WriteLine("class SqLiteHelper:::" + s); } } }
36.921368
175
0.45891
[ "Apache-2.0" ]
E-hang/Bilibili.Push
Native.Tool/SQLite/SQLiteHelper.cs
22,969
C#
namespace Roydl.Text.Test.BinaryToTextTests { using System; using System.IO; using System.Text; using BinaryToText; using NUnit.Framework; [TestFixture] [Parallelizable] [Platform(Include = TestVars.PlatformInclude)] public class Base91Tests { private const BinToTextEncoding Algorithm = BinToTextEncoding.Base91; private const string ExpectedTestEncoded = "\"ONKd"; private const string ExpectedRangeEncoded = ":C#(:C?hVB$MSiVEwndBAMZRxwFfBB;IW<}YQV!A_v$Y_c%zr4cYQPFl0,@heMAJ<:N[*T+.SFGr*`b4PD}vgYqU>cW0P*1NwV,O{cQ5u0m900[8@n4,wh?DP<2+~jQSW6nmLm1o-J,?jTs%2<WF%qb=oh|}EO6WrCFfk)GH!4EEDmT?yDvcowYe4_-ufO_Y*Ud|l)TH;5RNOVTi5DIdB1<&JR<u5OTbEnz1n)gH}6eWZEV?#D8d15jN4n?u^Otde5.Tp)tHK8rfm=Ui+DVeO!|xL!]uSP,f4;G<q)6HX94ox8W?<D.e&&w{5_6v$T;(@Dgq))[JZ?)E!rii}E:n-wIhRRuv\"TK+PW2I+)DKm@[N.ak?DFjoh18*#nxvZUk-po>$,)QKz[DX_JkiKF|o`5TQT!0vzU!:(6Jf.)dK$]QgG^l?QFwpu!,0%_3v=U}<C=h|:)qK=^dpR&liXFJqH("; private static readonly string TestFileSrcPath = TestVars.GetTempFilePath(Algorithm.ToString()); private static readonly string TestFileDestPath = TestVars.GetTempFilePath(Algorithm.ToString()); private static readonly TestCaseData[] TestData = { new(TestVarsType.TestStream, ExpectedTestEncoded), new(TestVarsType.TestBytes, ExpectedTestEncoded), new(TestVarsType.TestString, ExpectedTestEncoded), new(TestVarsType.TestFile, ExpectedTestEncoded), new(TestVarsType.RangeString, ExpectedRangeEncoded), new(TestVarsType.RandomBytes, null) }; private static Base91 _instance; [OneTimeSetUp] public void CreateInstanceAndTestFile() { _instance = new Base91(); File.WriteAllText(TestFileSrcPath, TestVars.TestStr); } [OneTimeTearDown] public void CleanUpTestFiles() { var dir = Path.GetDirectoryName(TestFileSrcPath); if (dir == null) return; foreach (var file in Directory.GetFiles(dir, $"test-{Algorithm}-*.tmp")) File.Delete(file); } [Test] [TestCaseSource(nameof(TestData))] [Category("Extension")] public void ExtensionEncodeDecode(TestVarsType varsType, string expectedEncoded) { object original, decoded; string encoded; switch (varsType) { case TestVarsType.TestStream: // No extension for streams return; case TestVarsType.TestBytes: original = TestVars.TestBytes; encoded = ((byte[])original).Encode(Algorithm); decoded = encoded.Decode(Algorithm); break; case TestVarsType.TestString: original = TestVars.TestStr; encoded = ((string)original).Encode(Algorithm); decoded = encoded.DecodeString(Algorithm); break; case TestVarsType.TestFile: Assert.IsTrue(_instance.EncodeFile(TestFileSrcPath, TestFileDestPath)); original = TestVars.TestBytes; encoded = TestFileSrcPath.EncodeFile(Algorithm); decoded = TestFileDestPath.DecodeFile(Algorithm); break; case TestVarsType.QuoteString: original = TestVars.QuoteStr; encoded = ((string)original).Encode(Algorithm); decoded = encoded.DecodeString(Algorithm); break; case TestVarsType.RangeString: original = TestVars.RangeStr; encoded = ((string)original).Encode(Algorithm); decoded = encoded.DecodeString(Algorithm); break; case TestVarsType.RandomBytes: original = TestVars.GetRandomBytes(); encoded = ((byte[])original).Encode(Algorithm); decoded = encoded.Decode(Algorithm); break; default: throw new ArgumentOutOfRangeException(nameof(varsType), varsType, null); } if (expectedEncoded != null) Assert.AreEqual(expectedEncoded, encoded); Assert.AreEqual(original, decoded); } [Test] [Category("New")] public void InstanceCtor() { var instance = new Base91(); Assert.IsInstanceOf(typeof(Base91), instance); Assert.IsInstanceOf(typeof(BinaryToTextEncoding), instance); Assert.AreNotSame(_instance, instance); var defaultInstance1 = Algorithm.GetDefaultInstance(); Assert.IsInstanceOf(typeof(Base91), defaultInstance1); Assert.IsInstanceOf(typeof(BinaryToTextEncoding), defaultInstance1); Assert.AreNotSame(instance, defaultInstance1); var defaultInstance2 = Algorithm.GetDefaultInstance(); Assert.IsInstanceOf(typeof(Base91), defaultInstance2); Assert.IsInstanceOf(typeof(BinaryToTextEncoding), defaultInstance2); Assert.AreSame(defaultInstance1, defaultInstance2); } [Test] [TestCaseSource(nameof(TestData))] [Category("Method")] public void InstanceEncodeDecode(TestVarsType varsType, string expectedEncoded) { object original, decoded; string encoded; switch (varsType) { case TestVarsType.TestStream: original = TestVars.TestBytes; // dispose using (var msi = new MemoryStream((byte[])original)) { var mso = new MemoryStream(); _instance.EncodeStream(msi, mso, true); try { msi.Position = 0L; } catch (Exception e) { Assert.AreEqual(typeof(ObjectDisposedException), e.GetType()); } try { mso.Position = 0L; } catch (Exception e) { Assert.AreEqual(typeof(ObjectDisposedException), e.GetType()); } } // encode using (var msi = new MemoryStream((byte[])original)) { using var mso = new MemoryStream(); _instance.EncodeStream(msi, mso); encoded = Encoding.UTF8.GetString(mso.ToArray()); } // decode using (var msi = new MemoryStream(Encoding.UTF8.GetBytes(encoded))) { using var mso = new MemoryStream(); _instance.DecodeStream(msi, mso); decoded = mso.ToArray(); } break; case TestVarsType.TestBytes: original = TestVars.TestBytes; encoded = _instance.EncodeBytes((byte[])original); decoded = _instance.DecodeBytes(encoded); break; case TestVarsType.TestString: original = TestVars.TestStr; encoded = _instance.EncodeString((string)original); decoded = _instance.DecodeString(encoded); break; case TestVarsType.TestFile: Assert.IsTrue(_instance.EncodeFile(TestFileSrcPath, TestFileDestPath)); original = TestVars.TestBytes; encoded = _instance.EncodeFile(TestFileSrcPath); decoded = _instance.DecodeFile(TestFileDestPath); break; case TestVarsType.QuoteString: original = TestVars.QuoteStr; encoded = _instance.EncodeString((string)original); decoded = _instance.DecodeString(encoded); break; case TestVarsType.RangeString: original = TestVars.RangeStr; encoded = _instance.EncodeString((string)original); decoded = _instance.DecodeString(encoded); break; case TestVarsType.RandomBytes: original = TestVars.GetRandomBytes(); encoded = _instance.EncodeBytes((byte[])original); decoded = _instance.DecodeBytes(encoded); break; default: throw new ArgumentOutOfRangeException(nameof(varsType), varsType, null); } if (expectedEncoded != null) Assert.AreEqual(expectedEncoded, encoded); Assert.AreEqual(original, decoded); } } }
44.104265
526
0.532775
[ "MIT" ]
Roydl/Text
test/BinaryToTextTests/Base91Tests.cs
9,308
C#
// 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. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.MySql.Cmdlets { using static Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Extensions; /// <summary> /// Creates or update active directory administrator on an existing server. The update action will overwrite the existing /// administrator. /// </summary> /// <remarks> /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBForMySQL/servers/{serverName}/Administrators/activeDirectory" /// </remarks> [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.InternalExport] [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzMySqlServerAdministrator_Update", SupportsShouldProcess = true)] [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerAdministratorResource))] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Description(@"Creates or update active directory administrator on an existing server. The update action will overwrite the existing administrator.")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Generated] public partial class SetAzMySqlServerAdministrator_Update : global::System.Management.Automation.PSCmdlet, Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener { /// <summary>A unique id generatd for the this cmdlet when it is instantiated.</summary> private string __correlationId = System.Guid.NewGuid().ToString(); /// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary> private global::System.Management.Automation.InvocationInfo __invocationInfo; /// <summary>A unique id generatd for the this cmdlet when ProcessRecord() is called.</summary> private string __processRecordId; /// <summary> /// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation. /// </summary> private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); /// <summary>when specified, runs this cmdlet as a PowerShell job</summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter AsJob { get; set; } /// <summary>Wait for .NET debugger to attach</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter Break { get; set; } /// <summary>The reference to the client API class.</summary> public Microsoft.Azure.PowerShell.Cmdlets.MySql.MySql Client => Microsoft.Azure.PowerShell.Cmdlets.MySql.Module.Instance.ClientAPI; /// <summary> /// The credentials, account, tenant, and subscription used for communication with Azure /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] [global::System.Management.Automation.ValidateNotNull] [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Azure)] public global::System.Management.Automation.PSObject DefaultProfile { get; set; } /// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } /// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } /// <summary>Accessor for our copy of the InvocationInfo.</summary> public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } /// <summary> /// <see cref="IEventListener" /> cancellation delegate. Stops the cmdlet when called. /// </summary> global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; /// <summary><see cref="IEventListener" /> cancellation token.</summary> global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener.Token => _cancellationTokenSource.Token; /// <summary> /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue /// asynchronously. /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter NoWait { get; set; } /// <summary> /// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.HttpPipeline" /> that the remote call will use. /// </summary> private Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.HttpPipeline Pipeline { get; set; } /// <summary>Backing field for <see cref="Property" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerAdministratorResource _property; /// <summary>Represents a and external administrator to be created.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Represents a and external administrator to be created.", ValueFromPipeline = true)] [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = true, ReadOnly = false, Description = @"Represents a and external administrator to be created.", SerializedName = @"properties", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerAdministratorResource) })] public Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerAdministratorResource Property { get => this._property; set => this._property = value; } /// <summary>The URI for the proxy server to use</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public global::System.Uri Proxy { get; set; } /// <summary>Credentials for a proxy server to use for the remote call</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } /// <summary>Use the default credentials for the proxy</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } /// <summary>Backing field for <see cref="ResourceGroupName" /> property.</summary> private string _resourceGroupName; /// <summary>The name of the resource group. The name is case insensitive.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group. The name is case insensitive.")] [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = true, ReadOnly = false, Description = @"The name of the resource group. The name is case insensitive.", SerializedName = @"resourceGroupName", PossibleTypes = new [] { typeof(string) })] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Path)] public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } /// <summary>Backing field for <see cref="ServerName" /> property.</summary> private string _serverName; /// <summary>The name of the server.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the server.")] [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = true, ReadOnly = false, Description = @"The name of the server.", SerializedName = @"serverName", PossibleTypes = new [] { typeof(string) })] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Path)] public string ServerName { get => this._serverName; set => this._serverName = value; } /// <summary>Backing field for <see cref="SubscriptionId" /> property.</summary> private string _subscriptionId; /// <summary>The ID of the target subscription.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription.")] [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Info( Required = true, ReadOnly = false, Description = @"The ID of the target subscription.", SerializedName = @"subscriptionId", PossibleTypes = new [] { typeof(string) })] [Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.DefaultInfo( Name = @"", Description =@"", Script = @"(Get-AzContext).Subscription.Id")] [global::Microsoft.Azure.PowerShell.Cmdlets.MySql.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MySql.ParameterCategory.Path)] public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } /// <summary> /// <c>overrideOnDefault</c> will be called before the regular onDefault has been processed, allowing customization of what /// happens on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ICloudError" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onDefault method should be processed, or if the method should /// return immediately (set to true to skip further processing )</param> partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ICloudError> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens /// on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerAdministratorResource" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return /// immediately (set to true to skip further processing )</param> partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerAdministratorResource> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) /// </summary> protected override void BeginProcessing() { Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); if (Break) { Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.AttachDebugger.Break(); } ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Creates a duplicate instance of this cmdlet (via JSON serialization).</summary> /// <returns>a duplicate instance of SetAzMySqlServerAdministrator_Update</returns> public Microsoft.Azure.PowerShell.Cmdlets.MySql.Cmdlets.SetAzMySqlServerAdministrator_Update Clone() { var clone = new SetAzMySqlServerAdministrator_Update(); clone.__correlationId = this.__correlationId; clone.__processRecordId = this.__processRecordId; clone.DefaultProfile = this.DefaultProfile; clone.InvocationInformation = this.InvocationInformation; clone.Proxy = this.Proxy; clone.Pipeline = this.Pipeline; clone.AsJob = this.AsJob; clone.Break = this.Break; clone.ProxyCredential = this.ProxyCredential; clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; clone.HttpPipelinePrepend = this.HttpPipelinePrepend; clone.HttpPipelineAppend = this.HttpPipelineAppend; clone.SubscriptionId = this.SubscriptionId; clone.ResourceGroupName = this.ResourceGroupName; clone.ServerName = this.ServerName; clone.Property = this.Property; return clone; } /// <summary>Performs clean-up after the command execution</summary> protected override void EndProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Handles/Dispatches events during the call to the REST service.</summary> /// <param name="id">The message id</param> /// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param> /// <param name="messageData">Detailed message data for the message event.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed. /// </returns> async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.EventData> messageData) { using( NoSynchronizationContext ) { if (token.IsCancellationRequested) { return ; } switch ( id ) { case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Verbose: { WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Warning: { WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Information: { // When an operation supports asjob, Information messages must go thru verbose. WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Debug: { WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.Error: { WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); return ; } case Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.DelayBeforePolling: { if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) { var data = messageData(); if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) { var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); var location = response.GetFirstHeader(@"Location"); var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); // do nothing more. data.Cancel(); return; } } break; } } await Microsoft.Azure.PowerShell.Cmdlets.MySql.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); if (token.IsCancellationRequested) { return ; } WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); } } /// <summary>Performs execution of the command.</summary> protected override void ProcessRecord() { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } __processRecordId = System.Guid.NewGuid().ToString(); try { // work if (ShouldProcess($"Call remote 'ServerAdministratorsCreateOrUpdate' operation")) { if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) { var instance = this.Clone(); var job = new Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); JobRepository.Add(job); var task = instance.ProcessRecordAsync(); job.Monitor(task); WriteObject(job); } else { using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token) ) { asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token); } } } } catch (global::System.AggregateException aggregateException) { // unroll the inner exceptions to get the root cause foreach( var innerException in aggregateException.Flatten().InnerExceptions ) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } } catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } finally { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletProcessRecordEnd).Wait(); } } /// <summary>Performs execution of the command, working asynchronously if required.</summary> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> protected async global::System.Threading.Tasks.Task ProcessRecordAsync() { using( NoSynchronizationContext ) { await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MySql.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); if (null != HttpPipelinePrepend) { Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); } if (null != HttpPipelineAppend) { Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); } // get the client instance try { await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await this.Client.ServerAdministratorsCreateOrUpdate(SubscriptionId, ResourceGroupName, ServerName, Property, onOk, onDefault, this, Pipeline); await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } catch (Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.UndeclaredResponseException urexception) { WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,ServerName=ServerName,body=Property}) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } }); } finally { await ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Events.CmdletProcessRecordAsyncEnd); } } } /// <summary> /// Intializes a new instance of the <see cref="SetAzMySqlServerAdministrator_Update" /> cmdlet class. /// </summary> public SetAzMySqlServerAdministrator_Update() { } /// <summary>Interrupts currently running code within the command.</summary> protected override void StopProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.IEventListener)this).Cancel(); base.StopProcessing(); } /// <summary> /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ICloudError" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ICloudError> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnDefault(responseMessage, response, ref _returnNow); // if overrideOnDefault has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // Error Response : default var code = (await response)?.Code; var message = (await response)?.Message; if ((null == code || null == message)) { // Unrecognized Response. Create an error record based on what we have. var ex = new Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.RestException<Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.ICloudError>(responseMessage, await response); WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ServerName=ServerName, body=Property }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } }); } else { WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, ServerName=ServerName, body=Property }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } }); } } } /// <summary>a delegate that is called when the remote service returns 200 (OK).</summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerAdministratorResource" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerAdministratorResource> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnOk(responseMessage, response, ref _returnNow); // if overrideOnOk has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // onOk - response for 200 / application/json // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.MySql.Models.Api20171201.IServerAdministratorResource WriteObject((await response)); } } } }
71.8361
451
0.660852
[ "MIT" ]
3quanfeng/azure-powershell
src/MySql/generated/cmdlets/SetAzMySqlServerAdministrator_Update.cs
34,144
C#
// Copyright (c) Peter Vrenken. All rights reserved. See the license on https://github.com/vrenken/EtAlii.Ubigia namespace EtAlii.Ubigia.Api.Functional.Parsing.Tests { using System.Linq; using EtAlii.Ubigia.Api.Functional.Traversal; using Xunit; public partial class ScriptParserTests { [Fact] public void ScriptParser_Root_Add_Time_MMDDHHMMSS_FormattedString_DoubleQuotes_Absolute() { // Arrange. var scope = new ExecutionScope(); const string query = "time:\"2016\" += /12/04/13/38/22"; // Act. var result = _parser.Parse(query, scope); // Assert. var script = result.Script; Assert.False(result.Errors.Any(), result.Errors.Select(e => e.Message).FirstOrDefault()); var sequence = script.Sequences.First(); var rootedPathSubject = sequence.Parts.Skip(0).Cast<RootedPathSubject>().First(); Assert.Equal("time", rootedPathSubject.Root); Assert.Single(rootedPathSubject.Parts); Assert.IsType<ConstantPathSubjectPart>(rootedPathSubject.Parts[0]); Assert.Equal("2016", rootedPathSubject.Parts.Cast<ConstantPathSubjectPart>().First().Name); Assert.IsType<AddOperator>(sequence.Parts.ElementAt(1)); var pathSubject = sequence.Parts.Skip(2).Cast<AbsolutePathSubject>().First(); Assert.NotNull(pathSubject); Assert.Equal("/12/04/13/38/22", pathSubject.ToString()); } [Fact] public void ScriptParser_Root_Add_Time_MMDDHHMMSS_FormattedString_DoubleQuotes_Relative() { // Arrange. var scope = new ExecutionScope(); const string query = "time:\"2016\" += 12/04/13/38/22"; // Act. var result = _parser.Parse(query, scope); // Assert. var script = result.Script; Assert.False(result.Errors.Any(), result.Errors.Select(e => e.Message).FirstOrDefault()); var sequence = script.Sequences.First(); var rootedPathSubject = sequence.Parts.Skip(0).Cast<RootedPathSubject>().First(); Assert.Equal("time", rootedPathSubject.Root); Assert.Single(rootedPathSubject.Parts); Assert.IsType<ConstantPathSubjectPart>(rootedPathSubject.Parts[0]); Assert.Equal("2016", rootedPathSubject.Parts.Cast<ConstantPathSubjectPart>().First().Name); Assert.IsType<AddOperator>(sequence.Parts.ElementAt(1)); var pathSubject = sequence.Parts.Skip(2).Cast<RelativePathSubject>().First(); Assert.NotNull(pathSubject); Assert.Equal("12/04/13/38/22", pathSubject.ToString()); } [Fact] public void ScriptParser_Root_Add_Time_DDHHMMSS_FormattedString_DoubleQuotes_Absolute() { // Arrange. var scope = new ExecutionScope(); const string query = "time:\"2016-12\" += /04/13/38/22"; // Act. var result = _parser.Parse(query, scope); // Assert. var script = result.Script; Assert.False(result.Errors.Any(), result.Errors.Select(e => e.Message).FirstOrDefault()); var sequence = script.Sequences.First(); var rootedPathSubject = sequence.Parts.Skip(0).Cast<RootedPathSubject>().First(); Assert.Equal("time", rootedPathSubject.Root); Assert.Single(rootedPathSubject.Parts); Assert.IsType<ConstantPathSubjectPart>(rootedPathSubject.Parts[0]); Assert.Equal("2016-12", rootedPathSubject.Parts.Cast<ConstantPathSubjectPart>().First().Name); Assert.IsType<AddOperator>(sequence.Parts.ElementAt(1)); var pathSubject = sequence.Parts.Skip(2).Cast<AbsolutePathSubject>().First(); Assert.NotNull(pathSubject); Assert.Equal("/04/13/38/22", pathSubject.ToString()); } [Fact] public void ScriptParser_Root_Add_Time_DDHHMMSS_FormattedString_DoubleQuotes_Relative() { // Arrange. var scope = new ExecutionScope(); const string query = "time:\"2016-12\" += 04/13/38/22"; // Act. var result = _parser.Parse(query, scope); // Assert. var script = result.Script; Assert.False(result.Errors.Any(), result.Errors.Select(e => e.Message).FirstOrDefault()); var sequence = script.Sequences.First(); var rootedPathSubject = sequence.Parts.Skip(0).Cast<RootedPathSubject>().First(); Assert.Equal("time", rootedPathSubject.Root); Assert.Single(rootedPathSubject.Parts); Assert.IsType<ConstantPathSubjectPart>(rootedPathSubject.Parts[0]); Assert.Equal("2016-12", rootedPathSubject.Parts.Cast<ConstantPathSubjectPart>().First().Name); Assert.IsType<AddOperator>(sequence.Parts.ElementAt(1)); var pathSubject = sequence.Parts.Skip(2).Cast<RelativePathSubject>().First(); Assert.NotNull(pathSubject); Assert.Equal("04/13/38/22", pathSubject.ToString()); } [Fact] public void ScriptParser_Root_Add_Time_SS_FormattedString_DoubleQuotes_Absolute() { // Arrange. var scope = new ExecutionScope(); const string query = "time:\"2016-12-04 13:38\" += /22"; // Act. var result = _parser.Parse(query, scope); // Assert. var script = result.Script; Assert.False(result.Errors.Any(), result.Errors.Select(e => e.Message).FirstOrDefault()); var sequence = script.Sequences.First(); var rootedPathSubject = sequence.Parts.Skip(0).Cast<RootedPathSubject>().First(); Assert.Equal("time", rootedPathSubject.Root); Assert.Single(rootedPathSubject.Parts); Assert.IsType<ConstantPathSubjectPart>(rootedPathSubject.Parts[0]); Assert.Equal("2016-12-04 13:38", rootedPathSubject.Parts.Cast<ConstantPathSubjectPart>().First().Name); Assert.IsType<AddOperator>(sequence.Parts.ElementAt(1)); var pathSubject = sequence.Parts.Skip(2).Cast<AbsolutePathSubject>().First(); Assert.NotNull(pathSubject); Assert.Equal("/22", pathSubject.ToString()); } [Fact] public void ScriptParser_Root_Add_Time_SS_FormattedString_DoubleQuotes_Relative() { // Arrange. var scope = new ExecutionScope(); const string query = "time:\"2016-12-04 13:38\" += 22"; // Act. var result = _parser.Parse(query, scope); // Assert. var script = result.Script; Assert.False(result.Errors.Any(), result.Errors.Select(e => e.Message).FirstOrDefault()); var sequence = script.Sequences.First(); var rootedPathSubject = sequence.Parts.Skip(0).Cast<RootedPathSubject>().First(); Assert.Equal("time", rootedPathSubject.Root); Assert.Single(rootedPathSubject.Parts); Assert.IsType<ConstantPathSubjectPart>(rootedPathSubject.Parts[0]); Assert.Equal("2016-12-04 13:38", rootedPathSubject.Parts.Cast<ConstantPathSubjectPart>().First().Name); Assert.IsType<AddOperator>(sequence.Parts.ElementAt(1)); var pathSubject = sequence.Parts.Skip(2).Cast<StringConstantSubject>().First(); Assert.NotNull(pathSubject); Assert.Equal("22", pathSubject.Value); } } }
46.828221
115
0.616402
[ "MIT" ]
vrenken/EtAlii.Ubigia
Source/Api/EtAlii.Ubigia.Api.Functional.Parsing.Tests/Traversal/1. Parsing/UnitTests/ScriptParser.Root.Add.Time.FormattedString.DoubleQuotes.Tests.cs
7,635
C#
using GizmoFort.Connector.ERPNext.PublicTypes; using GizmoFort.Connector.ERPNext.WrapperTypes; namespace GizmoFort.Connector.ERPNext.ERPTypes.Ve_ve_chart_template_amd { public class ERPVe_ve_chart_template_amd : ERPNextObjectBase { public ERPVe_ve_chart_template_amd() : this(new ERPObject(DocType.Ve_ve_chart_template_amd)) { } public ERPVe_ve_chart_template_amd(ERPObject obj) : base(obj) { } } //Enums go here }
28.1875
104
0.769401
[ "MIT" ]
dmequus/gizmofort.connector.erpnext
Libs/GizmoFort.Connector.ERPNext/ERPTypes/Ve_ve_chart_template_amd/ERPVe_ve_chart_template_amd.cs
451
C#
using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Starter.Data.Entities; namespace Starter.Data.Context { public interface IDataContext { DbSet<UserProfile> UserProfiles { get; set; } EntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class; //EF Core method, not to be confused with DbSet Entries EntityEntry Entry(object entity); int SaveChanges(bool acceptAllChangesOnSuccess); int SaveChanges(); Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken)); Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken)); } }
34.208333
133
0.750305
[ "MIT" ]
ceasius/aspnetcore-api-jwt
server/Starter.Data/Context/IDataContext.cs
823
C#
/* * Copyright (C) 2015-2019 Virgil Security Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * (1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * (3) Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com> */ [assembly: System.Runtime.CompilerServices.InternalsVisibleToAttribute("PureKit.Tests")] namespace Virgil.PureKit.Phe { using System; using Google.Protobuf; using Org.BouncyCastle.Asn1.Nist; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Math.EC; using Virgil.PureKit.Utils; /// <summary> /// Phe crypto. /// </summary> public class PheCrypto { private const int PheClientKeyLen = 32; private const int PheNonceLen = 32; private const int ZLen = 32; private SHA512Helper sha512; private Swu swu; private X9ECParameters curveParams; public PheCrypto() { this.curveParams = NistNamedCurves.GetByName("P-256"); this.Curve = (FpCurve)this.curveParams.Curve; this.CurveG = this.curveParams.G.Multiply(BigInteger.ValueOf(1)); this.Rng = new PheRandomGenerator(); this.sha512 = new SHA512Helper(); this.swu = new Swu(this.Curve.Q, this.Curve.B.ToBigInteger()); } internal FpCurve Curve { get; private set; } internal ECPoint CurveG { get; private set; } internal IPheRandomGenerator Rng { get; set; } /// <summary> /// Generates a random default length nonce. /// </summary> public byte[] GenerateNonce() { return this.GenerateNonce(PheNonceLen); } /// <summary> /// Generates a new random secret key. /// </summary> public SecretKey GenerateSecretKey() { var randomZ = this.RandomZ(); return new SecretKey(randomZ); } /// <summary> /// Decodes <see cref="SecretKey"/> from specified byte array. /// </summary> public SecretKey DecodeSecretKey(byte[] encodedSecretKey) { Validation.NotNullOrEmptyByteArray(encodedSecretKey); var secretKeyInt = new BigInteger(1, encodedSecretKey); var point = this.curveParams.G.Multiply(secretKeyInt); return new SecretKey(secretKeyInt); } public PublicKey ExtractPublicKey(SecretKey secretKey) { var point = (FpPoint)this.curveParams.G.Multiply(secretKey.Value); return new PublicKey(point); } /// <summary> /// Decodes <see cref="PublicKey"/> from specified byte array. /// </summary> public PublicKey DecodePublicKey(byte[] encodedPublicKey) { Validation.NotNullOrEmptyByteArray(encodedPublicKey); var point = (FpPoint)this.Curve.DecodePoint(encodedPublicKey); return new PublicKey(point); } /// <summary> /// Encrypt the specified data using the specified key. ///Encrypt generates 32 byte salt, uses master key ///& salt to generate per-data key & nonce with the help of HKDF ///Salt is concatenated to the ciphertext /// </summary> /// <returns>The encrypted data bytes.</returns> /// <param name="data">Data to be encrypted.</param> /// <param name="key">Key to be used for encryption.</param> public byte[] Encrypt(byte[] data, byte[] key) { Validation.NotNull(data); Validation.NotNullOrEmptyByteArray(key); var encryptionService = new EncryptionService(key); return encryptionService.Encrypt(data); } /// <summary> /// Decrypt the specified cipherText using the specified key. ///Decrypt extracts 32 byte salt, derives key & nonce and decrypts ///ciphertext with the help of HKDF /// </summary> /// <returns>The decrypted data bytes.</returns> /// <param name="cipherText">Encrypted data to be decrypted.</param> /// <param name="key">Key to be used for decryption.</param> public byte[] Decrypt(byte[] cipherText, byte[] key) { Validation.NotNullOrEmptyByteArray(cipherText); Validation.NotNullOrEmptyByteArray(key); var encryptionService = new EncryptionService(key); return encryptionService.Decrypt(cipherText); } /// <summary> /// Computes the c0 point for specified T record and password. /// </summary> public byte[] ComputeC0(SecretKey skC, byte[] pwd, byte[] nc, byte[] t0) { Validation.NotNull(skC); Validation.NotNullOrEmptyByteArray(pwd); Validation.NotNullOrEmptyByteArray(nc); Validation.NotNullOrEmptyByteArray(t0); var hc0Point = this.HashToPoint(Domains.Dhc0, nc, pwd); var minusY = skC.Value.Negate(); var t0Point = this.Curve.DecodePoint(t0); var c0Point = t0Point.Add(hc0Point.Multiply(minusY)); return c0Point.GetEncoded(); } /// <summary> /// Rotates the secret key. /// </summary> public SecretKey RotateSecretKey(SecretKey secretKey, byte[] tokenBytes) { Validation.NotNull(secretKey); Validation.NotNullOrEmptyByteArray(tokenBytes); var token = UpdateToken.Parser.ParseFrom(tokenBytes); var aInt = new BigInteger(1, token.A.ToByteArray()); var bInt = new BigInteger(1, token.B.ToByteArray()); var newSecretKey = new SecretKey(this.curveParams.N.Mul(secretKey.Value, aInt)); return newSecretKey; } /// <summary> /// Rotates the public key. /// </summary> public PublicKey RotatePublicKey(PublicKey publicKey, byte[] tokenBytes) { Validation.NotNull(publicKey); Validation.NotNullOrEmptyByteArray(tokenBytes); var token = UpdateToken.Parser.ParseFrom(tokenBytes); var aInt = new BigInteger(1, token.A.ToByteArray()); var bInt = new BigInteger(1, token.B.ToByteArray()); var newPoint = (FpPoint)publicKey.Point.Multiply(aInt).Add(this.curveParams.G.Multiply(bInt)); var newPublicKey = new PublicKey(newPoint); return newPublicKey; } /// <summary> /// Computes the record T for specified password. /// </summary> internal (byte[], byte[], byte[]) ComputeT(SecretKey skC, byte[] pwd, byte[] nC, byte[] c0, byte[] c1) { Validation.NotNull(skC); Validation.NotNullOrEmptyByteArray(pwd); Validation.NotNullOrEmptyByteArray(nC); Validation.NotNullOrEmptyByteArray(c0); Validation.NotNullOrEmptyByteArray(c1); var c0Point = this.Curve.DecodePoint(c0); var c1Point = this.Curve.DecodePoint(c1); var mPoint = this.HashToPoint(this.GenerateNonce(Swu.PointHashLen)); var hc0Point = this.HashToPoint(Domains.Dhc0, nC, pwd); var hc1Point = this.HashToPoint(Domains.Dhc1, nC, pwd); // encryption key in a form of a random point var hkdf = this.InitHkdf(mPoint.GetEncoded(), null, Domains.KdfInfoClientKey); var key = new byte[PheClientKeyLen]; hkdf.GenerateBytes(key, 0, key.Length); var t0Point = c0Point.Add(hc0Point.Multiply(skC.Value)); var t1Point = c1Point.Add(hc1Point.Multiply(skC.Value)).Add(mPoint.Multiply(skC.Value)); return (t0Point.GetEncoded(), t1Point.GetEncoded(), key); } /// <summary> /// Computes the c. /// </summary> internal Tuple<byte[], byte[]> ComputeC(SecretKey skS, byte[] nS) { Validation.NotNull(skS); Validation.NotNullOrEmptyByteArray(nS); var hs0 = this.HashToPoint(Domains.Dhs0, nS); var hs1 = this.HashToPoint(Domains.Dhs1, nS); var c0 = hs0.Multiply(skS.Value); var c1 = hs1.Multiply(skS.Value); return new Tuple<byte[], byte[]>(c0.GetEncoded(), c1.GetEncoded()); } /// <summary> /// Decrypts the M value for specified password. /// </summary> internal byte[] DecryptM(SecretKey skC, byte[] pwd, byte[] nC, byte[] t1, byte[] c1) { Validation.NotNull(skC); Validation.NotNullOrEmptyByteArray(pwd); Validation.NotNullOrEmptyByteArray(nC); Validation.NotNullOrEmptyByteArray(t1); Validation.NotNullOrEmptyByteArray(c1); var t1Point = this.Curve.DecodePoint(t1); var c1Point = this.Curve.DecodePoint(c1); var hc1Point = this.HashToPoint(Domains.Dhc1, nC, pwd); var minusY = this.curveParams.N.Neg(skC.Value); var mPoint = t1Point.Add(c1Point.Negate()).Add(hc1Point.Multiply(minusY)).Multiply(skC.Value.ModInverse(this.curveParams.N)); var hkdf = this.InitHkdf(mPoint.GetEncoded(), null, Domains.KdfInfoClientKey); var key = new byte[PheClientKeyLen]; hkdf.GenerateBytes(key, 0, key.Length); return key; } /// <summary> /// Updates an encryption record T with the specified update token parameters. /// </summary> internal Tuple<byte[], byte[]> UpdateT(byte[] nS, byte[] t0, byte[] t1, byte[] tokenBytes) { Validation.NotNullOrEmptyByteArray(nS); Validation.NotNullOrEmptyByteArray(t0); Validation.NotNullOrEmptyByteArray(t1); Validation.NotNullOrEmptyByteArray(tokenBytes); var token = UpdateToken.Parser.ParseFrom(tokenBytes); var hs0Point = this.HashToPoint(Domains.Dhs0, nS); var hs1Point = this.HashToPoint(Domains.Dhs1, nS); var t0Point = this.Curve.DecodePoint(t0); var t1Point = this.Curve.DecodePoint(t1); var aInt = new BigInteger(1, token.A.ToByteArray()); var bInt = new BigInteger(1, token.B.ToByteArray()); var t00Point = t0Point.Multiply(aInt).Add(hs0Point.Multiply(bInt)); var t11Point = t1Point.Multiply(aInt).Add(hs1Point.Multiply(bInt)); return new Tuple<byte[], byte[]>(t00Point.GetEncoded(), t11Point.GetEncoded()); } /// <summary> /// Proves the success. /// </summary> internal ProofOfSuccess ProveSuccess(SecretKey skS, byte[] nS, byte[] c0, byte[] c1) { Validation.NotNull(skS); Validation.NotNullOrEmptyByteArray(nS); Validation.NotNullOrEmptyByteArray(c0); Validation.NotNullOrEmptyByteArray(c1); var pkSPoint = this.curveParams.G.Multiply(skS.Value); var blindX = this.RandomZ(); var hs0Point = this.HashToPoint(Domains.Dhs0, nS); var hs1Point = this.HashToPoint(Domains.Dhs1, nS); var term1 = hs0Point.Multiply(blindX).GetEncoded(); var term2 = hs1Point.Multiply(blindX).GetEncoded(); var term3 = this.curveParams.G.Multiply(blindX).GetEncoded(); var pubKey = pkSPoint.GetEncoded(); var challenge = this.HashZ(Domains.ProofOK, pubKey, this.CurveG.GetEncoded(), c0, c1, term1, term2, term3); var result = blindX.Add(skS.Value.Multiply(challenge)).ToByteArray(); return new ProofOfSuccess { Term1 = ByteString.CopyFrom(term1), Term2 = ByteString.CopyFrom(term2), Term3 = ByteString.CopyFrom(term3), BlindX = ByteString.CopyFrom(result), }; } /// <summary> /// Validates the proof of success. /// </summary> internal bool ValidateProofOfSuccess(ProofOfSuccess proof, PublicKey pkS, byte[] nS, byte[] c0, byte[] c1) { Validation.NotNull(proof); Validation.NotNull(pkS); Validation.NotNullOrEmptyByteArray(nS); Validation.NotNullOrEmptyByteArray(c0); Validation.NotNullOrEmptyByteArray(c1); var term1 = proof.Term1.ToByteArray(); var term2 = proof.Term2.ToByteArray(); var term3 = proof.Term3.ToByteArray(); var trm1Point = this.Curve.DecodePoint(term1); var trm2Point = this.Curve.DecodePoint(term2); var trm3Point = this.Curve.DecodePoint(term3); var blindXInt = new BigInteger(1, proof.BlindX.ToByteArray()); var c0Point = this.Curve.DecodePoint(c0); var c1Point = this.Curve.DecodePoint(c1); var hs0Point = this.HashToPoint(Domains.Dhs0, nS); var hs1Point = this.HashToPoint(Domains.Dhs1, nS); var challenge = this.HashZ( Domains.ProofOK, pkS.Encode(), this.CurveG.GetEncoded(), c0, c1, term1, term2, term3); var t1Point = trm1Point.Add(c0Point.Multiply(challenge)); var t2Point = hs0Point.Multiply(blindXInt); if (!t1Point.Equals(t2Point)) { return false; } t1Point = trm2Point.Add(c1Point.Multiply(challenge)); t2Point = hs1Point.Multiply(blindXInt); if (!t1Point.Equals(t2Point)) { return false; } t1Point = trm3Point.Add(pkS.Point.Multiply(challenge)); t2Point = this.curveParams.G.Multiply(blindXInt); if (!t1Point.Equals(t2Point)) { return false; } return true; } /// <summary> /// Validates the proof of fail. /// </summary> internal bool ValidateProofOfFail(ProofOfFail proof, PublicKey pkS, byte[] nS, byte[] c0, byte[] c1) { Validation.NotNull(proof); Validation.NotNull(pkS); Validation.NotNullOrEmptyByteArray(nS); Validation.NotNullOrEmptyByteArray(c0); Validation.NotNullOrEmptyByteArray(c1); var term1 = proof.Term1.ToByteArray(); var term2 = proof.Term2.ToByteArray(); var term3 = proof.Term3.ToByteArray(); var term4 = proof.Term4.ToByteArray(); var challenge = this.HashZ( Domains.ProofErr, pkS.Encode(), this.CurveG.GetEncoded(), c0, c1, term1, term2, term3, term4); var hs0Point = this.HashToPoint(Domains.Dhs0, nS); var term1Point = this.Curve.DecodePoint(term1); var term2Point = this.Curve.DecodePoint(term2); var term3Point = this.Curve.DecodePoint(term3); var term4Point = this.Curve.DecodePoint(term4); var blindAInt = new BigInteger(1, proof.BlindA.ToByteArray()); var blindBInt = new BigInteger(1, proof.BlindB.ToByteArray()); var c0Point = this.Curve.DecodePoint(c0); var c1Point = this.Curve.DecodePoint(c1); var t1Point = term1Point.Add(term2Point).Add(c1Point.Multiply(challenge)); var t2Point = c0Point.Multiply(blindAInt).Add(hs0Point.Multiply(blindBInt)); if (!t1Point.Equals(t2Point)) { return false; } t1Point = term3Point.Add(term4Point); t2Point = pkS.Point.Multiply(blindAInt).Add(this.curveParams.G.Multiply(blindBInt)); if (!t1Point.Equals(t2Point)) { return false; } return true; } /// <summary> /// Maps arrays of bytes to an integer less than curve's N parameter /// </summary> internal BigInteger HashZ(byte[] domain, params byte[][] datas) { Validation.NotNullOrEmptyByteArray(domain); Validation.NotNullOrEmptyByteArray(datas); var key = this.sha512.ComputeHash(null, datas); var hkdf = this.InitHkdf(key, domain, Domains.KdfInfoZ); var result = new byte[32]; BigInteger z; do { hkdf.GenerateBytes(result, 0, result.Length); z = new BigInteger(1, result); } while (z.CompareTo(this.curveParams.N) >= 0); return z; } /// <summary> /// Maps arrays of bytes to a valid curve point. /// </summary> internal FpPoint HashToPoint(byte[] domain, params byte[][] datas) { var hash = this.sha512.ComputeHash(domain, datas); var hash256 = ((Span<byte>)hash).Slice(0, Swu.PointHashLen).ToArray(); var (x, y) = this.swu.HashToPoint(hash256); var xField = this.Curve.FromBigInteger(x); var yField = this.Curve.FromBigInteger(y); return (FpPoint)this.Curve.CreatePoint(x, y); } internal int NonceLength() { return PheNonceLen; } private HkdfBytesGenerator InitHkdf(byte[] key, byte[] salt, byte[] info) { Validation.NotNullOrEmptyByteArray(key); Validation.NotNullOrEmptyByteArray(info); var hkdf = new HkdfBytesGenerator(new Sha512Digest()); hkdf.Init(new HkdfParameters(key, salt, info)); return hkdf; } /// <summary> /// Generates big random 256 bit integer which must be less than /// curve's N parameter. /// </summary> private BigInteger RandomZ() { BigInteger z; do { z = new BigInteger(1, this.GenerateNonce(ZLen)); } while (z.CompareTo(this.curveParams.N) >= 0); return z; } /// <summary> /// Generates a random nonce. /// </summary> private byte[] GenerateNonce(int length) { return this.Rng.GenerateNonce(length); } } }
36.511883
137
0.589625
[ "BSD-3-Clause" ]
KeithLabelle/virgil-purekit-net
PureKit/Phe/PheCrypto.cs
19,974
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Bolt { class DiskRipper : IThread { public void Run(ConcurrentQueue<string> queue) { if(!IsDiskInTray()) { OpenDiskTray(); Logger.Info("Waiting for new disk"); //Wait for disk in tray to be true Thread.Sleep(1000); while (!IsDiskInTray()) { Thread.Sleep(100); } } while(true) { //rip disk Logger.Info($"DiskRipper: Processing disk {GetDiskName()}"); Directory.CreateDirectory($@"{Settings.OutputDirectory}{GetDiskName()}"); Process.Start(Settings.MakeMKV_Location, $@"mkv disc:0 all --cache=1024 --minlength={Settings.MakeMKV_Min_Seconds} {Settings.OutputDirectory}{GetDiskName()}").WaitForExit(); //Add file to a queue Logger.Info("Added disk to queue"); queue.Enqueue($@"{Settings.OutputDirectory}{GetDiskName()}"); //Open the tray OpenDiskTray(); Logger.Info("Waiting for new disk"); //Wait for disk in tray to be true Thread.Sleep(1000); while (!IsDiskInTray()) { Thread.Sleep(100); } } } //Source: https://stackoverflow.com/questions/3797141/programmatically-opening-the-cd-tray [DllImport("winmm.dll", EntryPoint = "mciSendString")] private static extern int mciSendStringA(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback); private void OpenDiskTray() { string returnString = ""; mciSendStringA("set cdaudio door open", returnString, 0, 0); Logger.Info("Opening Disk Tray"); } private void CloseDiskTray() { string returnString = ""; mciSendStringA("set cdaudio door closed", returnString, 0, 0); Logger.Info("Closing Disk Tray"); } private bool IsDiskInTray() { //Source: https://stackoverflow.com/questions/11420365/detecting-if-disc-is-in-dvd-drive var drives = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.CDRom); return drives.ElementAt(0).IsReady; } private string GetDiskName() { var drives = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.CDRom); return drives.ElementAt(0).VolumeLabel; } public void Setup() { } public void TakeDown() { } } }
31.894737
189
0.545875
[ "MIT" ]
op-erator/Bolt
Bolt/DiskRipper.cs
3,032
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.PowerBI.Api.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Detailed information about a Power BI error response /// </summary> public partial class PowerBIApiErrorResponseDetail { /// <summary> /// Initializes a new instance of the PowerBIApiErrorResponseDetail /// class. /// </summary> public PowerBIApiErrorResponseDetail() { CustomInit(); } /// <summary> /// Initializes a new instance of the PowerBIApiErrorResponseDetail /// class. /// </summary> /// <param name="code">The error code</param> /// <param name="message">The error message</param> /// <param name="target">The error target</param> public PowerBIApiErrorResponseDetail(string code = default(string), string message = default(string), string target = default(string)) { Code = code; Message = message; Target = target; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the error code /// </summary> [JsonProperty(PropertyName = "code")] public string Code { get; set; } /// <summary> /// Gets or sets the error message /// </summary> [JsonProperty(PropertyName = "message")] public string Message { get; set; } /// <summary> /// Gets or sets the error target /// </summary> [JsonProperty(PropertyName = "target")] public string Target { get; set; } } }
29.939394
142
0.576923
[ "MIT" ]
DhyanRathore/PowerBI-CSharp
sdk/PowerBI.Api/Source/Models/PowerBIApiErrorResponseDetail.cs
1,976
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.VisualStudio.LanguageServices.Razor { [Obsolete("Use Microsoft.CodeAnalysis.ExternalAccess.Razor.RazorRemoteHostClient instead")] internal static class RazorLanguageServiceClientFactory { public static async Task<RazorLanguageServiceClient> CreateAsync(Workspace workspace, CancellationToken cancellationToken = default) { var clientFactory = workspace.Services.GetRequiredService<IRemoteHostClientService>(); var client = await clientFactory.TryGetRemoteHostClientAsync(cancellationToken).ConfigureAwait(false); return client == null ? null : new RazorLanguageServiceClient(client, GetServiceName(workspace)); } #region support a/b testing. after a/b testing, we can remove all this code private static string s_serviceNameDoNotAccessDirectly = null; private static string GetServiceName(Workspace workspace) { if (s_serviceNameDoNotAccessDirectly == null) { var x64 = workspace.Options.GetOption(OOP64Bit); if (!x64) { x64 = workspace.Services.GetService<IExperimentationService>().IsExperimentEnabled( WellKnownExperimentNames.RoslynOOP64bit); } Interlocked.CompareExchange( ref s_serviceNameDoNotAccessDirectly, x64 ? "razorLanguageService64" : "razorLanguageService", null); } return s_serviceNameDoNotAccessDirectly; } public static readonly Option<bool> OOP64Bit = new Option<bool>( nameof(InternalFeatureOnOffOptions), nameof(OOP64Bit), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(InternalFeatureOnOffOptions.LocalRegistryPath + nameof(OOP64Bit))); private static class InternalFeatureOnOffOptions { internal const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Features\"; } #endregion } }
43.245614
140
0.700203
[ "MIT" ]
Dean-ZhenYao-Wang/roslyn
src/VisualStudio/Razor/RazorLanguageServiceClientFactory.cs
2,467
C#
namespace Stripe { public class SourceTransactionsListOptions : ListOptions { } }
13.428571
60
0.702128
[ "Apache-2.0" ]
Franklin89/stripe-dotnet
src/Stripe.net/Services/SourceTransactions/SourceTransactionsListOptions.cs
94
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using log4net; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Framework { /// <summary> /// This class stores and retrieves dynamic attributes. /// </summary> /// <remarks> /// Modules that want to use dynamic attributes need to do so in a private data store /// which is accessed using a unique name. DAMap provides access to the data stores, /// each of which is an OSDMap. Modules are free to store any type of data they want /// within their data store. However, avoid storing large amounts of data because that /// would slow down database access. /// </remarks> public class DAMap : IXmlSerializable { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly int MIN_NAMESPACE_LENGTH = 4; private OSDMap m_map = new OSDMap(); // WARNING: this is temporary for experimentation only, it will be removed!!!! public OSDMap TopLevelMap { get { return m_map; } set { m_map = value; } } public XmlSchema GetSchema() { return null; } public static DAMap FromXml(string rawXml) { DAMap map = new DAMap(); map.ReadXml(rawXml); return map; } public void ReadXml(XmlReader reader) { ReadXml(reader.ReadInnerXml()); } public void ReadXml(string rawXml) { // System.Console.WriteLine("Trying to deserialize [{0}]", rawXml); lock (this) { m_map = (OSDMap)OSDParser.DeserializeLLSDXml(rawXml); SanitiseMap(this); } } public void WriteXml(XmlWriter writer) { writer.WriteRaw(ToXml()); } public string ToXml() { lock (this) return OSDParser.SerializeLLSDXmlString(m_map); } public void CopyFrom(DAMap other) { // Deep copy string data = null; lock (other) { if (other.CountNamespaces > 0) { data = OSDParser.SerializeLLSDXmlString(other.m_map); } } lock (this) { if (data == null) Clear(); else m_map = (OSDMap)OSDParser.DeserializeLLSDXml(data); } } /// <summary> /// Sanitise the map to remove any namespaces or stores that are not OSDMap. /// </summary> /// <param name='map'> /// </param> public static void SanitiseMap(DAMap daMap) { List<string> keysToRemove = null; OSDMap namespacesMap = daMap.m_map; foreach (string key in namespacesMap.Keys) { // Console.WriteLine("Processing ns {0}", key); if (!(namespacesMap[key] is OSDMap)) { if (keysToRemove == null) keysToRemove = new List<string>(); keysToRemove.Add(key); } } if (keysToRemove != null) { foreach (string key in keysToRemove) { // Console.WriteLine ("Removing bad ns {0}", key); namespacesMap.Remove(key); } } foreach (OSD nsOsd in namespacesMap.Values) { OSDMap nsOsdMap = (OSDMap)nsOsd; keysToRemove = null; foreach (string key in nsOsdMap.Keys) { if (!(nsOsdMap[key] is OSDMap)) { if (keysToRemove == null) keysToRemove = new List<string>(); keysToRemove.Add(key); } } if (keysToRemove != null) foreach (string key in keysToRemove) nsOsdMap.Remove(key); } } /// <summary> /// Get the number of namespaces /// </summary> public int CountNamespaces { get { lock (this) { return m_map.Count; } } } /// <summary> /// Get the number of stores. /// </summary> public int CountStores { get { int count = 0; lock (this) { foreach (OSD osdNamespace in m_map) { count += ((OSDMap)osdNamespace).Count; } } return count; } } /// <summary> /// Retrieve a Dynamic Attribute store /// </summary> /// <param name="ns">namespace for the store - use "OpenSim" for in-core modules</param> /// <param name="storeName">name of the store within the namespace</param> /// <returns>an OSDMap representing the stored data, or null if not found</returns> public OSDMap GetStore(string ns, string storeName) { OSD namespaceOsd; lock (this) { if (m_map.TryGetValue(ns, out namespaceOsd)) { OSD store; if (((OSDMap)namespaceOsd).TryGetValue(storeName, out store)) return (OSDMap)store; } } return null; } /// <summary> /// Saves a Dynamic attribute store /// </summary> /// <param name="ns">namespace for the store - use "OpenSim" for in-core modules</param> /// <param name="storeName">name of the store within the namespace</param> /// <param name="store">an OSDMap representing the data to store</param> public void SetStore(string ns, string storeName, OSDMap store) { ValidateNamespace(ns); OSDMap nsMap; lock (this) { if (!m_map.ContainsKey(ns)) { nsMap = new OSDMap(); m_map[ns] = nsMap; } nsMap = (OSDMap)m_map[ns]; // m_log.DebugFormat("[DA MAP]: Setting store to {0}:{1}", ns, storeName); nsMap[storeName] = store; } } /// <summary> /// Validate the key used for storing separate data stores. /// </summary> /// <param name='key'></param> public static void ValidateNamespace(string ns) { if (ns.Length < MIN_NAMESPACE_LENGTH) throw new Exception("Minimum namespace length is " + MIN_NAMESPACE_LENGTH); } public bool ContainsStore(string ns, string storeName) { OSD namespaceOsd; lock (this) { if (m_map.TryGetValue(ns, out namespaceOsd)) { return ((OSDMap)namespaceOsd).ContainsKey(storeName); } } return false; } public bool TryGetStore(string ns, string storeName, out OSDMap store) { OSD namespaceOsd; lock (this) { if (m_map.TryGetValue(ns, out namespaceOsd)) { OSD storeOsd; bool result = ((OSDMap)namespaceOsd).TryGetValue(storeName, out storeOsd); store = (OSDMap)storeOsd; return result; } } store = null; return false; } public void Clear() { lock (this) m_map.Clear(); } public bool RemoveStore(string ns, string storeName) { OSD namespaceOsd; lock (this) { if (m_map.TryGetValue(ns, out namespaceOsd)) { OSDMap namespaceOsdMap = (OSDMap)namespaceOsd; namespaceOsdMap.Remove(storeName); // Don't keep empty namespaces around if (namespaceOsdMap.Count <= 0) m_map.Remove(ns); } } return false; } } }
31.887195
113
0.51831
[ "BSD-3-Clause" ]
AlericInglewood/opensimulator
OpenSim/Framework/DAMap.cs
10,459
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Buffers; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.Diagnostics.Runtime.Utilities; namespace Microsoft.Diagnostics.Runtime.DacInterface { public sealed unsafe class ClrDataModule : CallableCOMWrapper { private const uint DACDATAMODULEPRIV_REQUEST_GET_MODULEDATA = 0xf0000001; private static readonly Guid IID_IXCLRDataModule = new("88E32849-0A0A-4cb0-9022-7CD2E9E139E2"); public ClrDataModule(DacLibrary library, IntPtr pUnknown) : base(library?.OwningLibrary, IID_IXCLRDataModule, pUnknown) { } private ref readonly IClrDataModuleVTable VTable => ref Unsafe.AsRef<IClrDataModuleVTable>(_vtable); public HResult GetModuleData(out ExtendedModuleData data) { HResult hr; fixed (void* dataPtr = &data) { hr = VTable.Request(Self, DACDATAMODULEPRIV_REQUEST_GET_MODULEDATA, 0, null, sizeof(ExtendedModuleData), dataPtr); if (!hr) data = default; return hr; } } public string? GetName() { HResult hr = VTable.GetName(Self, 0, out int nameLength, null); if (!hr) return null; string name = new string('\0', nameLength - 1); fixed (char* namePtr = name) hr = VTable.GetName(Self, nameLength, out _, namePtr); return hr ? name : null; } public string? GetFileName() { // GetFileName will fault if buffer pointer is null. Use fixed size buffer. char[] buffer = ArrayPool<char>.Shared.Rent(1024); try { fixed (char* bufferPtr = buffer) { HResult hr = VTable.GetFileName(Self, buffer.Length, out int nameLength, bufferPtr); return hr && nameLength > 0 ? new string(buffer, 0, nameLength - 1) : null; } } finally { ArrayPool<char>.Shared.Return(buffer); } } [StructLayout(LayoutKind.Sequential)] private readonly unsafe struct IClrDataModuleVTable { private readonly IntPtr StartEnumAssemblies; private readonly IntPtr EnumAssembly; private readonly IntPtr EndEnumAssemblies; private readonly IntPtr StartEnumTypeDefinitions; private readonly IntPtr EnumTypeDefinition; private readonly IntPtr EndEnumTypeDefinitions; private readonly IntPtr StartEnumTypeInstances; private readonly IntPtr EnumTypeInstance; private readonly IntPtr EndEnumTypeInstances; private readonly IntPtr StartEnumTypeDefinitionsByName; private readonly IntPtr EnumTypeDefinitionByName; private readonly IntPtr EndEnumTypeDefinitionsByName; private readonly IntPtr StartEnumTypeInstancesByName; private readonly IntPtr EnumTypeInstanceByName; private readonly IntPtr EndEnumTypeInstancesByName; private readonly IntPtr GetTypeDefinitionByToken; private readonly IntPtr StartEnumMethodDefinitionsByName; private readonly IntPtr EnumMethodDefinitionByName; private readonly IntPtr EndEnumMethodDefinitionsByName; private readonly IntPtr StartEnumMethodInstancesByName; private readonly IntPtr EnumMethodInstanceByName; private readonly IntPtr EndEnumMethodInstancesByName; private readonly IntPtr GetMethodDefinitionByToken; private readonly IntPtr StartEnumDataByName; private readonly IntPtr EnumDataByName; private readonly IntPtr EndEnumDataByName; public readonly delegate* unmanaged[Stdcall]<IntPtr, int, out int, char*, HResult> GetName; public readonly delegate* unmanaged[Stdcall]<IntPtr, int, out int, char*, HResult> GetFileName; private readonly IntPtr GetFlags; private readonly IntPtr IsSameObject; private readonly IntPtr StartEnumExtents; private readonly IntPtr EnumExtent; private readonly IntPtr EndEnumExtents; public readonly delegate* unmanaged[Stdcall]<IntPtr, uint, int, void*, int, void*, HResult> Request; private readonly IntPtr StartEnumAppDomains; private readonly IntPtr EnumAppDomain; private readonly IntPtr EndEnumAppDomains; private readonly IntPtr GetVersionId; } } }
42.947368
130
0.646855
[ "MIT" ]
EphronCloud/clrmd
src/Microsoft.Diagnostics.Runtime/src/DacInterface/ClrDataModule.cs
4,898
C#
using System; using System.Diagnostics; using System.Net; using NUnit.Framework; namespace Nano.Tests.RequestHandlers { [TestFixture] public class FileRequestHandlerShould { [TestCase( "/ApiExplorer/" )] [TestCase( "/ApiExplorer/index.html" )] [TestCase( "/APIEXPLORER/INDEX.HTML", Description = "Testing all UPPERCASE" )] [TestCase( "/apiexplorer/index.html", Description = "Testing all lowercase" )] [TestCase( "/aPiExpLoRer/InDeX.hTMl", Description = "Testing UPPER and lower case" )] public void Return_A_File_That_Exists( string path ) { using ( var server = NanoTestServer.Start() ) { // Arrange server.NanoConfiguration.AddFile( path, "www/ApiExplorer/index.html" ); // Act var response = HttpHelper.GetResponseString( server.GetUrl() + path ); // Assert Assert.That( response.Contains( "Api Explorer" ) ); } } [TestCase( "/ApiExplorer/" )] [TestCase( "/ApiExplorer/index.htm" )] [TestCase( "/NoSuchFile.html" )] [TestCase( "//////lkjasldkffj409803948/laijsdfoiuwpo0e9ouphasldifj/ljpowu98723984uoiasjdlfknasl;dijpasoeurpoweur/" )] public void Return_An_Http_404_When_The_Requested_File_Is_Not_Found( string path ) { using( var server = NanoTestServer.Start() ) { // Arrange server.NanoConfiguration.AddFile( "/ApiExplorer/index.html", "www/ApiExplorer/index.html" ); // Act var response = HttpHelper.GetHttpWebResponse( server.GetUrl() + path ); // Visual Assertion Trace.WriteLine( response.StatusCode ); Trace.WriteLine( response.GetResponseString()); // Assert Assert.That( response.StatusCode == HttpStatusCode.NotFound ); } } #region ETag Tests [TestCase( "/ApiExplorer/" )] public void Return_An_ETag_Header_When_A_File_Is_Returned( string path ) { using( var server = NanoTestServer.Start() ) { // Arrange server.NanoConfiguration.AddFile( path, "www/ApiExplorer/index.html" ); // Act var response = HttpHelper.GetHttpWebResponse( server.GetUrl() + path ); var eTag = response.GetResponseHeader( "ETag" ); // Visual Assertion Trace.WriteLine( "ETag Header Value: " + eTag ); // Assert Assert.NotNull( eTag ); } } [TestCase( "/ApiExplorer/" )] public void Return_Not_Modified_Http_Status_Code_304_When_Request_ETag_Matches_File_ETag( string path ) { using( var server = NanoTestServer.Start() ) { // Arrange server.NanoConfiguration.AddFile( path, "www/ApiExplorer/index.html" ); var initialResponse = HttpHelper.GetHttpWebResponse( server.GetUrl() + path ); var initialETag = initialResponse.GetResponseHeader( "ETag" ); var request = HttpHelper.GetHttpWebRequest( server.GetUrl() + path ); request.Headers["If-None-Match"] = initialETag; // Act var response = request.GetHttpWebResponse(); var responseCode = response.StatusCode; // Visual Assertion Trace.WriteLine( "HTTP Status Code: " + responseCode ); // Assert Assert.That( responseCode == HttpStatusCode.NotModified ); } } [TestCase( "/ApiExplorer/" )] public void Return_Matching_ETag_When_Server_Returns_Not_Modified( string path ) { using( var server = NanoTestServer.Start() ) { // Arrange server.NanoConfiguration.AddFile( path, "www/ApiExplorer/index.html" ); var initialResponse = HttpHelper.GetHttpWebResponse( server.GetUrl() + path ); var initialETag = initialResponse.GetResponseHeader( "ETag" ); var request = HttpHelper.GetHttpWebRequest( server.GetUrl() + path ); request.Headers["If-None-Match"] = initialETag; // Act var response = request.GetHttpWebResponse(); var eTag = response.GetResponseHeader( "ETag" ); // Visual Assertion Trace.WriteLine( "ETag Header Value: " + eTag ); // Assert Assert.That( initialETag == eTag ); } } [TestCase( "/ApiExplorer/" )] public void Return_Empty_Body_When_Server_Returns_Not_Modified_Http_Status_Code_304_Because_Of_A_Matching_ETag( string path ) { using( var server = NanoTestServer.Start() ) { // Arrange server.NanoConfiguration.AddFile( path, "www/ApiExplorer/index.html" ); var initialResponse = HttpHelper.GetHttpWebResponse( server.GetUrl() + path ); Trace.WriteLine( "Initial Response Length: " + initialResponse.GetResponseString().Length ); var initialETag = initialResponse.GetResponseHeader( "ETag" ); var request = HttpHelper.GetHttpWebRequest( server.GetUrl() + path ); request.Headers["If-None-Match"] = initialETag; // Act var response = request.GetHttpWebResponse(); var responseLength = response.GetResponseString().Length; // Visual Assertion Trace.WriteLine( "Not Modified Response Length: " + responseLength ); // Assert Assert.That( responseLength == 0 ); } } #endregion ETag Tests #region Last-Modified Tests [TestCase( "/ApiExplorer/" )] public void Return_An_Last_Modified_Header_When_A_File_Is_Returned( string path ) { using( var server = NanoTestServer.Start() ) { // Arrange server.NanoConfiguration.AddFile( path, "www/ApiExplorer/index.html" ); // Act var response = HttpHelper.GetHttpWebResponse( server.GetUrl() + path ); var lastModified = response.GetResponseHeader( "Last-Modified" ); // Visual Assertion Trace.WriteLine( "Last-Modified Header Value: " + lastModified ); // Assert Assert.NotNull( lastModified ); } } [TestCase( "/ApiExplorer/" )] public void Return_Not_Modified_Http_Status_Code_304_When_Request_Last_Modified_Header_Matches_File_Last_Modified_DateTime( string path ) { using( var server = NanoTestServer.Start() ) { // Arrange server.NanoConfiguration.AddFile( path, "www/ApiExplorer/index.html" ); var initialResponse = HttpHelper.GetHttpWebResponse( server.GetUrl() + path ); var initialLastModified = initialResponse.GetResponseHeader( "Last-Modified" ); var request = HttpHelper.GetHttpWebRequest( server.GetUrl() + path ); request.IfModifiedSince = DateTime.Parse( initialLastModified ); // Act var response = request.GetHttpWebResponse(); var responseCode = response.StatusCode; // Visual Assertion Trace.WriteLine( "HTTP Status Code: " + responseCode ); // Assert Assert.That( responseCode == HttpStatusCode.NotModified ); } } [TestCase( "/ApiExplorer/" )] public void Return_Matching_Last_Modified_Header_When_Server_Returns_Not_Modified( string path ) { using( var server = NanoTestServer.Start() ) { // Arrange server.NanoConfiguration.AddFile( path, "www/ApiExplorer/index.html" ); var initialResponse = HttpHelper.GetHttpWebResponse( server.GetUrl() + path ); var initialLastModified = initialResponse.GetResponseHeader( "Last-Modified" ); var request = HttpHelper.GetHttpWebRequest( server.GetUrl() + path ); request.IfModifiedSince = DateTime.Parse( initialLastModified ); // Act var response = request.GetHttpWebResponse(); var lastModified = response.GetResponseHeader( "Last-Modified" ); // Visual Assertion Trace.WriteLine( "Last-Modified Header Value: " + lastModified ); // Assert Assert.That( initialLastModified == lastModified ); } } [TestCase( "/ApiExplorer/" )] public void Return_Empty_Body_When_Server_Returns_Not_Modified_Http_Status_Code_304_Because_Of_A_Matching_Last_Modified_Header( string path ) { using( var server = NanoTestServer.Start() ) { // Arrange server.NanoConfiguration.AddFile( path, "www/ApiExplorer/index.html" ); var initialResponse = HttpHelper.GetHttpWebResponse( server.GetUrl() + path ); Trace.WriteLine( "Initial Response Length: " + initialResponse.GetResponseString().Length ); var initialLastModified = initialResponse.GetResponseHeader( "Last-Modified" ); var request = HttpHelper.GetHttpWebRequest( server.GetUrl() + path ); request.IfModifiedSince = DateTime.Parse( initialLastModified ); // Act var response = request.GetHttpWebResponse(); var responseLength = response.GetResponseString().Length; // Visual Assertion Trace.WriteLine( "Not Modified Response Length: " + responseLength ); // Assert Assert.That( responseLength == 0 ); } } #endregion Last-Modified Tests } }
41.322581
149
0.572697
[ "MIT" ]
revnique/Nano
src/Nano.Tests/RequestHandlers/FileRequestHandlerShould.cs
10,250
C#
using System.Collections.Generic; using System.Windows; using System.Windows.Media; namespace ZumtenSoft.WebsiteCrawler.Utils { public static class DependencyObjectHelper { /// <summary> /// Récupère l'ancètre immédiat d'un objet ou null s'il est non-trouvable. /// </summary> public static DependencyObject Ancestor(this DependencyObject current) { if (current != null) { return VisualTreeHelper.GetParent(current); } return null; } /// <summary> /// Récupère le premier ancètre de type T ou null s'il est non-trouvable. /// </summary> public static T Ancestor<T>(this DependencyObject current) where T : DependencyObject { if (current != null) { while ((current = VisualTreeHelper.GetParent(current)) != null) { T castedCurrent = current as T; if (castedCurrent != null) return castedCurrent; } } return null; } /// <summary> /// Récupère la liste de tous les ancètres. /// </summary> public static IEnumerable<DependencyObject> Ancestors(this DependencyObject current) { if (current != null) { while ((current = VisualTreeHelper.GetParent(current)) != null) yield return current; } } /// <summary> /// Récupère la liste de tous les ancètres de type T. /// </summary> public static IEnumerable<T> Ancestors<T>(this DependencyObject current) where T : DependencyObject { if (current != null) { while ((current = VisualTreeHelper.GetParent(current)) != null) { T castedCurrent = current as T; if (castedCurrent != null) yield return castedCurrent; } } } } }
31.507463
107
0.510658
[ "Apache-2.0" ]
zumten/WebsiteCrawler
src/ZumtenSoft.WebsiteCrawler/Utils/DependencyObjectHelper.cs
2,126
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; public class TestToggler : MonoBehaviour { // flickers between two gameobjects every time gizmos are drawn (such as every frame while the camera is moving in the editor) // was using to check for visual differences between models public GameObject gameObject1; public GameObject gameObject2; public static bool blah; [MenuItem("Editor/Toggle Object _F1")] public static void ToggleObject() { blah = !blah; } void OnDrawGizmos() { if (gameObject1 != null && gameObject2 != null) { gameObject1.SetActive(blah); gameObject2.SetActive(!blah); } } }
21.903226
127
0.739323
[ "MIT" ]
Terrev/Bionicle-Area-Editor
Assets/Scripts/TestToggler.cs
681
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Grafeas.V1.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedGrafeasClientSnippets { /// <summary>Snippet for GetOccurrence</summary> public void GetOccurrenceRequestObject() { string endpoint = ""; // Snippet: GetOccurrence(GetOccurrenceRequest, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) GetOccurrenceRequest request = new GetOccurrenceRequest { OccurrenceName = OccurrenceName.FromProjectOccurrence("[PROJECT]", "[OCCURRENCE]"), }; // Make the request Occurrence response = grafeasClient.GetOccurrence(request); // End snippet } /// <summary>Snippet for GetOccurrenceAsync</summary> public async Task GetOccurrenceRequestObjectAsync() { string endpoint = ""; // Snippet: GetOccurrenceAsync(GetOccurrenceRequest, CallSettings) // Additional: GetOccurrenceAsync(GetOccurrenceRequest, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) GetOccurrenceRequest request = new GetOccurrenceRequest { OccurrenceName = OccurrenceName.FromProjectOccurrence("[PROJECT]", "[OCCURRENCE]"), }; // Make the request Occurrence response = await grafeasClient.GetOccurrenceAsync(request); // End snippet } /// <summary>Snippet for GetOccurrence</summary> public void GetOccurrence() { string endpoint = ""; // Snippet: GetOccurrence(string, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string name = "projects/[PROJECT]/occurrences/[OCCURRENCE]"; // Make the request Occurrence response = grafeasClient.GetOccurrence(name); // End snippet } /// <summary>Snippet for GetOccurrenceAsync</summary> public async Task GetOccurrenceAsync() { string endpoint = ""; // Snippet: GetOccurrenceAsync(string, CallSettings) // Additional: GetOccurrenceAsync(string, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string name = "projects/[PROJECT]/occurrences/[OCCURRENCE]"; // Make the request Occurrence response = await grafeasClient.GetOccurrenceAsync(name); // End snippet } /// <summary>Snippet for GetOccurrence</summary> public void GetOccurrenceResourceNames() { string endpoint = ""; // Snippet: GetOccurrence(OccurrenceName, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) OccurrenceName name = OccurrenceName.FromProjectOccurrence("[PROJECT]", "[OCCURRENCE]"); // Make the request Occurrence response = grafeasClient.GetOccurrence(name); // End snippet } /// <summary>Snippet for GetOccurrenceAsync</summary> public async Task GetOccurrenceResourceNamesAsync() { string endpoint = ""; // Snippet: GetOccurrenceAsync(OccurrenceName, CallSettings) // Additional: GetOccurrenceAsync(OccurrenceName, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) OccurrenceName name = OccurrenceName.FromProjectOccurrence("[PROJECT]", "[OCCURRENCE]"); // Make the request Occurrence response = await grafeasClient.GetOccurrenceAsync(name); // End snippet } /// <summary>Snippet for ListOccurrences</summary> public void ListOccurrencesRequestObject() { string endpoint = ""; // Snippet: ListOccurrences(ListOccurrencesRequest, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) ListOccurrencesRequest request = new ListOccurrencesRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Filter = "", }; // Make the request PagedEnumerable<ListOccurrencesResponse, Occurrence> response = grafeasClient.ListOccurrences(request); // Iterate over all response items, lazily performing RPCs as required foreach (Occurrence item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListOccurrencesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Occurrence item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Occurrence> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Occurrence item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListOccurrences</summary> public async Task ListOccurrencesRequestObjectAsync() { string endpoint = ""; // Snippet: ListOccurrencesAsync(ListOccurrencesRequest, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) ListOccurrencesRequest request = new ListOccurrencesRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Filter = "", }; // Make the request PagedAsyncEnumerable<ListOccurrencesResponse, Occurrence> response = grafeasClient.ListOccurrencesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Occurrence item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListOccurrencesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Occurrence item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Occurrence> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Occurrence item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListOccurrences</summary> public void ListOccurrences() { string endpoint = ""; // Snippet: ListOccurrences(string, string, string, int?, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; string filter = ""; // Make the request PagedEnumerable<ListOccurrencesResponse, Occurrence> response = grafeasClient.ListOccurrences(parent, filter); // Iterate over all response items, lazily performing RPCs as required foreach (Occurrence item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListOccurrencesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Occurrence item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Occurrence> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Occurrence item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListOccurrences</summary> public async Task ListOccurrencesAsync() { string endpoint = ""; // Snippet: ListOccurrencesAsync(string, string, string, int?, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; string filter = ""; // Make the request PagedAsyncEnumerable<ListOccurrencesResponse, Occurrence> response = grafeasClient.ListOccurrencesAsync(parent, filter); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Occurrence item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListOccurrencesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Occurrence item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Occurrence> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Occurrence item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListOccurrences</summary> public void ListOccurrencesResourceNames() { string endpoint = ""; // Snippet: ListOccurrences(ProjectName, string, string, int?, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); string filter = ""; // Make the request PagedEnumerable<ListOccurrencesResponse, Occurrence> response = grafeasClient.ListOccurrences(parent, filter); // Iterate over all response items, lazily performing RPCs as required foreach (Occurrence item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListOccurrencesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Occurrence item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Occurrence> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Occurrence item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListOccurrences</summary> public async Task ListOccurrencesResourceNamesAsync() { string endpoint = ""; // Snippet: ListOccurrencesAsync(ProjectName, string, string, int?, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); string filter = ""; // Make the request PagedAsyncEnumerable<ListOccurrencesResponse, Occurrence> response = grafeasClient.ListOccurrencesAsync(parent, filter); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Occurrence item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListOccurrencesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Occurrence item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Occurrence> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Occurrence item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for DeleteOccurrence</summary> public void DeleteOccurrenceRequestObject() { string endpoint = ""; // Snippet: DeleteOccurrence(DeleteOccurrenceRequest, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) DeleteOccurrenceRequest request = new DeleteOccurrenceRequest { OccurrenceName = OccurrenceName.FromProjectOccurrence("[PROJECT]", "[OCCURRENCE]"), }; // Make the request grafeasClient.DeleteOccurrence(request); // End snippet } /// <summary>Snippet for DeleteOccurrenceAsync</summary> public async Task DeleteOccurrenceRequestObjectAsync() { string endpoint = ""; // Snippet: DeleteOccurrenceAsync(DeleteOccurrenceRequest, CallSettings) // Additional: DeleteOccurrenceAsync(DeleteOccurrenceRequest, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) DeleteOccurrenceRequest request = new DeleteOccurrenceRequest { OccurrenceName = OccurrenceName.FromProjectOccurrence("[PROJECT]", "[OCCURRENCE]"), }; // Make the request await grafeasClient.DeleteOccurrenceAsync(request); // End snippet } /// <summary>Snippet for DeleteOccurrence</summary> public void DeleteOccurrence() { string endpoint = ""; // Snippet: DeleteOccurrence(string, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string name = "projects/[PROJECT]/occurrences/[OCCURRENCE]"; // Make the request grafeasClient.DeleteOccurrence(name); // End snippet } /// <summary>Snippet for DeleteOccurrenceAsync</summary> public async Task DeleteOccurrenceAsync() { string endpoint = ""; // Snippet: DeleteOccurrenceAsync(string, CallSettings) // Additional: DeleteOccurrenceAsync(string, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string name = "projects/[PROJECT]/occurrences/[OCCURRENCE]"; // Make the request await grafeasClient.DeleteOccurrenceAsync(name); // End snippet } /// <summary>Snippet for DeleteOccurrence</summary> public void DeleteOccurrenceResourceNames() { string endpoint = ""; // Snippet: DeleteOccurrence(OccurrenceName, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) OccurrenceName name = OccurrenceName.FromProjectOccurrence("[PROJECT]", "[OCCURRENCE]"); // Make the request grafeasClient.DeleteOccurrence(name); // End snippet } /// <summary>Snippet for DeleteOccurrenceAsync</summary> public async Task DeleteOccurrenceResourceNamesAsync() { string endpoint = ""; // Snippet: DeleteOccurrenceAsync(OccurrenceName, CallSettings) // Additional: DeleteOccurrenceAsync(OccurrenceName, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) OccurrenceName name = OccurrenceName.FromProjectOccurrence("[PROJECT]", "[OCCURRENCE]"); // Make the request await grafeasClient.DeleteOccurrenceAsync(name); // End snippet } /// <summary>Snippet for CreateOccurrence</summary> public void CreateOccurrenceRequestObject() { string endpoint = ""; // Snippet: CreateOccurrence(CreateOccurrenceRequest, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) CreateOccurrenceRequest request = new CreateOccurrenceRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Occurrence = new Occurrence(), }; // Make the request Occurrence response = grafeasClient.CreateOccurrence(request); // End snippet } /// <summary>Snippet for CreateOccurrenceAsync</summary> public async Task CreateOccurrenceRequestObjectAsync() { string endpoint = ""; // Snippet: CreateOccurrenceAsync(CreateOccurrenceRequest, CallSettings) // Additional: CreateOccurrenceAsync(CreateOccurrenceRequest, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) CreateOccurrenceRequest request = new CreateOccurrenceRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Occurrence = new Occurrence(), }; // Make the request Occurrence response = await grafeasClient.CreateOccurrenceAsync(request); // End snippet } /// <summary>Snippet for CreateOccurrence</summary> public void CreateOccurrence() { string endpoint = ""; // Snippet: CreateOccurrence(string, Occurrence, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; Occurrence occurrence = new Occurrence(); // Make the request Occurrence response = grafeasClient.CreateOccurrence(parent, occurrence); // End snippet } /// <summary>Snippet for CreateOccurrenceAsync</summary> public async Task CreateOccurrenceAsync() { string endpoint = ""; // Snippet: CreateOccurrenceAsync(string, Occurrence, CallSettings) // Additional: CreateOccurrenceAsync(string, Occurrence, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; Occurrence occurrence = new Occurrence(); // Make the request Occurrence response = await grafeasClient.CreateOccurrenceAsync(parent, occurrence); // End snippet } /// <summary>Snippet for CreateOccurrence</summary> public void CreateOccurrenceResourceNames() { string endpoint = ""; // Snippet: CreateOccurrence(ProjectName, Occurrence, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); Occurrence occurrence = new Occurrence(); // Make the request Occurrence response = grafeasClient.CreateOccurrence(parent, occurrence); // End snippet } /// <summary>Snippet for CreateOccurrenceAsync</summary> public async Task CreateOccurrenceResourceNamesAsync() { string endpoint = ""; // Snippet: CreateOccurrenceAsync(ProjectName, Occurrence, CallSettings) // Additional: CreateOccurrenceAsync(ProjectName, Occurrence, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); Occurrence occurrence = new Occurrence(); // Make the request Occurrence response = await grafeasClient.CreateOccurrenceAsync(parent, occurrence); // End snippet } /// <summary>Snippet for BatchCreateOccurrences</summary> public void BatchCreateOccurrencesRequestObject() { string endpoint = ""; // Snippet: BatchCreateOccurrences(BatchCreateOccurrencesRequest, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) BatchCreateOccurrencesRequest request = new BatchCreateOccurrencesRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Occurrences = { new Occurrence(), }, }; // Make the request BatchCreateOccurrencesResponse response = grafeasClient.BatchCreateOccurrences(request); // End snippet } /// <summary>Snippet for BatchCreateOccurrencesAsync</summary> public async Task BatchCreateOccurrencesRequestObjectAsync() { string endpoint = ""; // Snippet: BatchCreateOccurrencesAsync(BatchCreateOccurrencesRequest, CallSettings) // Additional: BatchCreateOccurrencesAsync(BatchCreateOccurrencesRequest, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) BatchCreateOccurrencesRequest request = new BatchCreateOccurrencesRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Occurrences = { new Occurrence(), }, }; // Make the request BatchCreateOccurrencesResponse response = await grafeasClient.BatchCreateOccurrencesAsync(request); // End snippet } /// <summary>Snippet for BatchCreateOccurrences</summary> public void BatchCreateOccurrences() { string endpoint = ""; // Snippet: BatchCreateOccurrences(string, IEnumerable<Occurrence>, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; IEnumerable<Occurrence> occurrences = new Occurrence[] { new Occurrence(), }; // Make the request BatchCreateOccurrencesResponse response = grafeasClient.BatchCreateOccurrences(parent, occurrences); // End snippet } /// <summary>Snippet for BatchCreateOccurrencesAsync</summary> public async Task BatchCreateOccurrencesAsync() { string endpoint = ""; // Snippet: BatchCreateOccurrencesAsync(string, IEnumerable<Occurrence>, CallSettings) // Additional: BatchCreateOccurrencesAsync(string, IEnumerable<Occurrence>, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; IEnumerable<Occurrence> occurrences = new Occurrence[] { new Occurrence(), }; // Make the request BatchCreateOccurrencesResponse response = await grafeasClient.BatchCreateOccurrencesAsync(parent, occurrences); // End snippet } /// <summary>Snippet for BatchCreateOccurrences</summary> public void BatchCreateOccurrencesResourceNames() { string endpoint = ""; // Snippet: BatchCreateOccurrences(ProjectName, IEnumerable<Occurrence>, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); IEnumerable<Occurrence> occurrences = new Occurrence[] { new Occurrence(), }; // Make the request BatchCreateOccurrencesResponse response = grafeasClient.BatchCreateOccurrences(parent, occurrences); // End snippet } /// <summary>Snippet for BatchCreateOccurrencesAsync</summary> public async Task BatchCreateOccurrencesResourceNamesAsync() { string endpoint = ""; // Snippet: BatchCreateOccurrencesAsync(ProjectName, IEnumerable<Occurrence>, CallSettings) // Additional: BatchCreateOccurrencesAsync(ProjectName, IEnumerable<Occurrence>, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); IEnumerable<Occurrence> occurrences = new Occurrence[] { new Occurrence(), }; // Make the request BatchCreateOccurrencesResponse response = await grafeasClient.BatchCreateOccurrencesAsync(parent, occurrences); // End snippet } /// <summary>Snippet for UpdateOccurrence</summary> public void UpdateOccurrenceRequestObject() { string endpoint = ""; // Snippet: UpdateOccurrence(UpdateOccurrenceRequest, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) UpdateOccurrenceRequest request = new UpdateOccurrenceRequest { OccurrenceName = OccurrenceName.FromProjectOccurrence("[PROJECT]", "[OCCURRENCE]"), Occurrence = new Occurrence(), UpdateMask = new FieldMask(), }; // Make the request Occurrence response = grafeasClient.UpdateOccurrence(request); // End snippet } /// <summary>Snippet for UpdateOccurrenceAsync</summary> public async Task UpdateOccurrenceRequestObjectAsync() { string endpoint = ""; // Snippet: UpdateOccurrenceAsync(UpdateOccurrenceRequest, CallSettings) // Additional: UpdateOccurrenceAsync(UpdateOccurrenceRequest, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) UpdateOccurrenceRequest request = new UpdateOccurrenceRequest { OccurrenceName = OccurrenceName.FromProjectOccurrence("[PROJECT]", "[OCCURRENCE]"), Occurrence = new Occurrence(), UpdateMask = new FieldMask(), }; // Make the request Occurrence response = await grafeasClient.UpdateOccurrenceAsync(request); // End snippet } /// <summary>Snippet for UpdateOccurrence</summary> public void UpdateOccurrence() { string endpoint = ""; // Snippet: UpdateOccurrence(string, Occurrence, FieldMask, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string name = "projects/[PROJECT]/occurrences/[OCCURRENCE]"; Occurrence occurrence = new Occurrence(); FieldMask updateMask = new FieldMask(); // Make the request Occurrence response = grafeasClient.UpdateOccurrence(name, occurrence, updateMask); // End snippet } /// <summary>Snippet for UpdateOccurrenceAsync</summary> public async Task UpdateOccurrenceAsync() { string endpoint = ""; // Snippet: UpdateOccurrenceAsync(string, Occurrence, FieldMask, CallSettings) // Additional: UpdateOccurrenceAsync(string, Occurrence, FieldMask, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string name = "projects/[PROJECT]/occurrences/[OCCURRENCE]"; Occurrence occurrence = new Occurrence(); FieldMask updateMask = new FieldMask(); // Make the request Occurrence response = await grafeasClient.UpdateOccurrenceAsync(name, occurrence, updateMask); // End snippet } /// <summary>Snippet for UpdateOccurrence</summary> public void UpdateOccurrenceResourceNames() { string endpoint = ""; // Snippet: UpdateOccurrence(OccurrenceName, Occurrence, FieldMask, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) OccurrenceName name = OccurrenceName.FromProjectOccurrence("[PROJECT]", "[OCCURRENCE]"); Occurrence occurrence = new Occurrence(); FieldMask updateMask = new FieldMask(); // Make the request Occurrence response = grafeasClient.UpdateOccurrence(name, occurrence, updateMask); // End snippet } /// <summary>Snippet for UpdateOccurrenceAsync</summary> public async Task UpdateOccurrenceResourceNamesAsync() { string endpoint = ""; // Snippet: UpdateOccurrenceAsync(OccurrenceName, Occurrence, FieldMask, CallSettings) // Additional: UpdateOccurrenceAsync(OccurrenceName, Occurrence, FieldMask, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) OccurrenceName name = OccurrenceName.FromProjectOccurrence("[PROJECT]", "[OCCURRENCE]"); Occurrence occurrence = new Occurrence(); FieldMask updateMask = new FieldMask(); // Make the request Occurrence response = await grafeasClient.UpdateOccurrenceAsync(name, occurrence, updateMask); // End snippet } /// <summary>Snippet for GetOccurrenceNote</summary> public void GetOccurrenceNoteRequestObject() { string endpoint = ""; // Snippet: GetOccurrenceNote(GetOccurrenceNoteRequest, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) GetOccurrenceNoteRequest request = new GetOccurrenceNoteRequest { OccurrenceName = OccurrenceName.FromProjectOccurrence("[PROJECT]", "[OCCURRENCE]"), }; // Make the request Note response = grafeasClient.GetOccurrenceNote(request); // End snippet } /// <summary>Snippet for GetOccurrenceNoteAsync</summary> public async Task GetOccurrenceNoteRequestObjectAsync() { string endpoint = ""; // Snippet: GetOccurrenceNoteAsync(GetOccurrenceNoteRequest, CallSettings) // Additional: GetOccurrenceNoteAsync(GetOccurrenceNoteRequest, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) GetOccurrenceNoteRequest request = new GetOccurrenceNoteRequest { OccurrenceName = OccurrenceName.FromProjectOccurrence("[PROJECT]", "[OCCURRENCE]"), }; // Make the request Note response = await grafeasClient.GetOccurrenceNoteAsync(request); // End snippet } /// <summary>Snippet for GetOccurrenceNote</summary> public void GetOccurrenceNote() { string endpoint = ""; // Snippet: GetOccurrenceNote(string, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string name = "projects/[PROJECT]/occurrences/[OCCURRENCE]"; // Make the request Note response = grafeasClient.GetOccurrenceNote(name); // End snippet } /// <summary>Snippet for GetOccurrenceNoteAsync</summary> public async Task GetOccurrenceNoteAsync() { string endpoint = ""; // Snippet: GetOccurrenceNoteAsync(string, CallSettings) // Additional: GetOccurrenceNoteAsync(string, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string name = "projects/[PROJECT]/occurrences/[OCCURRENCE]"; // Make the request Note response = await grafeasClient.GetOccurrenceNoteAsync(name); // End snippet } /// <summary>Snippet for GetOccurrenceNote</summary> public void GetOccurrenceNoteResourceNames() { string endpoint = ""; // Snippet: GetOccurrenceNote(OccurrenceName, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) OccurrenceName name = OccurrenceName.FromProjectOccurrence("[PROJECT]", "[OCCURRENCE]"); // Make the request Note response = grafeasClient.GetOccurrenceNote(name); // End snippet } /// <summary>Snippet for GetOccurrenceNoteAsync</summary> public async Task GetOccurrenceNoteResourceNamesAsync() { string endpoint = ""; // Snippet: GetOccurrenceNoteAsync(OccurrenceName, CallSettings) // Additional: GetOccurrenceNoteAsync(OccurrenceName, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) OccurrenceName name = OccurrenceName.FromProjectOccurrence("[PROJECT]", "[OCCURRENCE]"); // Make the request Note response = await grafeasClient.GetOccurrenceNoteAsync(name); // End snippet } /// <summary>Snippet for GetNote</summary> public void GetNoteRequestObject() { string endpoint = ""; // Snippet: GetNote(GetNoteRequest, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) GetNoteRequest request = new GetNoteRequest { NoteName = NoteName.FromProjectNote("[PROJECT]", "[NOTE]"), }; // Make the request Note response = grafeasClient.GetNote(request); // End snippet } /// <summary>Snippet for GetNoteAsync</summary> public async Task GetNoteRequestObjectAsync() { string endpoint = ""; // Snippet: GetNoteAsync(GetNoteRequest, CallSettings) // Additional: GetNoteAsync(GetNoteRequest, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) GetNoteRequest request = new GetNoteRequest { NoteName = NoteName.FromProjectNote("[PROJECT]", "[NOTE]"), }; // Make the request Note response = await grafeasClient.GetNoteAsync(request); // End snippet } /// <summary>Snippet for GetNote</summary> public void GetNote() { string endpoint = ""; // Snippet: GetNote(string, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string name = "projects/[PROJECT]/notes/[NOTE]"; // Make the request Note response = grafeasClient.GetNote(name); // End snippet } /// <summary>Snippet for GetNoteAsync</summary> public async Task GetNoteAsync() { string endpoint = ""; // Snippet: GetNoteAsync(string, CallSettings) // Additional: GetNoteAsync(string, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string name = "projects/[PROJECT]/notes/[NOTE]"; // Make the request Note response = await grafeasClient.GetNoteAsync(name); // End snippet } /// <summary>Snippet for GetNote</summary> public void GetNoteResourceNames() { string endpoint = ""; // Snippet: GetNote(NoteName, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) NoteName name = NoteName.FromProjectNote("[PROJECT]", "[NOTE]"); // Make the request Note response = grafeasClient.GetNote(name); // End snippet } /// <summary>Snippet for GetNoteAsync</summary> public async Task GetNoteResourceNamesAsync() { string endpoint = ""; // Snippet: GetNoteAsync(NoteName, CallSettings) // Additional: GetNoteAsync(NoteName, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) NoteName name = NoteName.FromProjectNote("[PROJECT]", "[NOTE]"); // Make the request Note response = await grafeasClient.GetNoteAsync(name); // End snippet } /// <summary>Snippet for ListNotes</summary> public void ListNotesRequestObject() { string endpoint = ""; // Snippet: ListNotes(ListNotesRequest, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) ListNotesRequest request = new ListNotesRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Filter = "", }; // Make the request PagedEnumerable<ListNotesResponse, Note> response = grafeasClient.ListNotes(request); // Iterate over all response items, lazily performing RPCs as required foreach (Note item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListNotesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Note item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Note> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Note item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListNotes</summary> public async Task ListNotesRequestObjectAsync() { string endpoint = ""; // Snippet: ListNotesAsync(ListNotesRequest, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) ListNotesRequest request = new ListNotesRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Filter = "", }; // Make the request PagedAsyncEnumerable<ListNotesResponse, Note> response = grafeasClient.ListNotesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Note item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListNotesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Note item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Note> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Note item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListNotes</summary> public void ListNotes() { string endpoint = ""; // Snippet: ListNotes(string, string, string, int?, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; string filter = ""; // Make the request PagedEnumerable<ListNotesResponse, Note> response = grafeasClient.ListNotes(parent, filter); // Iterate over all response items, lazily performing RPCs as required foreach (Note item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListNotesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Note item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Note> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Note item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListNotes</summary> public async Task ListNotesAsync() { string endpoint = ""; // Snippet: ListNotesAsync(string, string, string, int?, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; string filter = ""; // Make the request PagedAsyncEnumerable<ListNotesResponse, Note> response = grafeasClient.ListNotesAsync(parent, filter); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Note item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListNotesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Note item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Note> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Note item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListNotes</summary> public void ListNotesResourceNames() { string endpoint = ""; // Snippet: ListNotes(ProjectName, string, string, int?, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); string filter = ""; // Make the request PagedEnumerable<ListNotesResponse, Note> response = grafeasClient.ListNotes(parent, filter); // Iterate over all response items, lazily performing RPCs as required foreach (Note item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListNotesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Note item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Note> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Note item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListNotes</summary> public async Task ListNotesResourceNamesAsync() { string endpoint = ""; // Snippet: ListNotesAsync(ProjectName, string, string, int?, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); string filter = ""; // Make the request PagedAsyncEnumerable<ListNotesResponse, Note> response = grafeasClient.ListNotesAsync(parent, filter); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Note item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListNotesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Note item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Note> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Note item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for DeleteNote</summary> public void DeleteNoteRequestObject() { string endpoint = ""; // Snippet: DeleteNote(DeleteNoteRequest, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) DeleteNoteRequest request = new DeleteNoteRequest { NoteName = NoteName.FromProjectNote("[PROJECT]", "[NOTE]"), }; // Make the request grafeasClient.DeleteNote(request); // End snippet } /// <summary>Snippet for DeleteNoteAsync</summary> public async Task DeleteNoteRequestObjectAsync() { string endpoint = ""; // Snippet: DeleteNoteAsync(DeleteNoteRequest, CallSettings) // Additional: DeleteNoteAsync(DeleteNoteRequest, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) DeleteNoteRequest request = new DeleteNoteRequest { NoteName = NoteName.FromProjectNote("[PROJECT]", "[NOTE]"), }; // Make the request await grafeasClient.DeleteNoteAsync(request); // End snippet } /// <summary>Snippet for DeleteNote</summary> public void DeleteNote() { string endpoint = ""; // Snippet: DeleteNote(string, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string name = "projects/[PROJECT]/notes/[NOTE]"; // Make the request grafeasClient.DeleteNote(name); // End snippet } /// <summary>Snippet for DeleteNoteAsync</summary> public async Task DeleteNoteAsync() { string endpoint = ""; // Snippet: DeleteNoteAsync(string, CallSettings) // Additional: DeleteNoteAsync(string, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string name = "projects/[PROJECT]/notes/[NOTE]"; // Make the request await grafeasClient.DeleteNoteAsync(name); // End snippet } /// <summary>Snippet for DeleteNote</summary> public void DeleteNoteResourceNames() { string endpoint = ""; // Snippet: DeleteNote(NoteName, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) NoteName name = NoteName.FromProjectNote("[PROJECT]", "[NOTE]"); // Make the request grafeasClient.DeleteNote(name); // End snippet } /// <summary>Snippet for DeleteNoteAsync</summary> public async Task DeleteNoteResourceNamesAsync() { string endpoint = ""; // Snippet: DeleteNoteAsync(NoteName, CallSettings) // Additional: DeleteNoteAsync(NoteName, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) NoteName name = NoteName.FromProjectNote("[PROJECT]", "[NOTE]"); // Make the request await grafeasClient.DeleteNoteAsync(name); // End snippet } /// <summary>Snippet for CreateNote</summary> public void CreateNoteRequestObject() { string endpoint = ""; // Snippet: CreateNote(CreateNoteRequest, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) CreateNoteRequest request = new CreateNoteRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), NoteId = "", Note = new Note(), }; // Make the request Note response = grafeasClient.CreateNote(request); // End snippet } /// <summary>Snippet for CreateNoteAsync</summary> public async Task CreateNoteRequestObjectAsync() { string endpoint = ""; // Snippet: CreateNoteAsync(CreateNoteRequest, CallSettings) // Additional: CreateNoteAsync(CreateNoteRequest, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) CreateNoteRequest request = new CreateNoteRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), NoteId = "", Note = new Note(), }; // Make the request Note response = await grafeasClient.CreateNoteAsync(request); // End snippet } /// <summary>Snippet for CreateNote</summary> public void CreateNote() { string endpoint = ""; // Snippet: CreateNote(string, string, Note, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; string noteId = ""; Note note = new Note(); // Make the request Note response = grafeasClient.CreateNote(parent, noteId, note); // End snippet } /// <summary>Snippet for CreateNoteAsync</summary> public async Task CreateNoteAsync() { string endpoint = ""; // Snippet: CreateNoteAsync(string, string, Note, CallSettings) // Additional: CreateNoteAsync(string, string, Note, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; string noteId = ""; Note note = new Note(); // Make the request Note response = await grafeasClient.CreateNoteAsync(parent, noteId, note); // End snippet } /// <summary>Snippet for CreateNote</summary> public void CreateNoteResourceNames() { string endpoint = ""; // Snippet: CreateNote(ProjectName, string, Note, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); string noteId = ""; Note note = new Note(); // Make the request Note response = grafeasClient.CreateNote(parent, noteId, note); // End snippet } /// <summary>Snippet for CreateNoteAsync</summary> public async Task CreateNoteResourceNamesAsync() { string endpoint = ""; // Snippet: CreateNoteAsync(ProjectName, string, Note, CallSettings) // Additional: CreateNoteAsync(ProjectName, string, Note, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); string noteId = ""; Note note = new Note(); // Make the request Note response = await grafeasClient.CreateNoteAsync(parent, noteId, note); // End snippet } /// <summary>Snippet for BatchCreateNotes</summary> public void BatchCreateNotesRequestObject() { string endpoint = ""; // Snippet: BatchCreateNotes(BatchCreateNotesRequest, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) BatchCreateNotesRequest request = new BatchCreateNotesRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Notes = { { "", new Note() }, }, }; // Make the request BatchCreateNotesResponse response = grafeasClient.BatchCreateNotes(request); // End snippet } /// <summary>Snippet for BatchCreateNotesAsync</summary> public async Task BatchCreateNotesRequestObjectAsync() { string endpoint = ""; // Snippet: BatchCreateNotesAsync(BatchCreateNotesRequest, CallSettings) // Additional: BatchCreateNotesAsync(BatchCreateNotesRequest, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) BatchCreateNotesRequest request = new BatchCreateNotesRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Notes = { { "", new Note() }, }, }; // Make the request BatchCreateNotesResponse response = await grafeasClient.BatchCreateNotesAsync(request); // End snippet } /// <summary>Snippet for BatchCreateNotes</summary> public void BatchCreateNotes() { string endpoint = ""; // Snippet: BatchCreateNotes(string, IDictionary<string,Note>, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; IDictionary<string, Note> notes = new Dictionary<string, Note> { { "", new Note() }, }; // Make the request BatchCreateNotesResponse response = grafeasClient.BatchCreateNotes(parent, notes); // End snippet } /// <summary>Snippet for BatchCreateNotesAsync</summary> public async Task BatchCreateNotesAsync() { string endpoint = ""; // Snippet: BatchCreateNotesAsync(string, IDictionary<string,Note>, CallSettings) // Additional: BatchCreateNotesAsync(string, IDictionary<string,Note>, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; IDictionary<string, Note> notes = new Dictionary<string, Note> { { "", new Note() }, }; // Make the request BatchCreateNotesResponse response = await grafeasClient.BatchCreateNotesAsync(parent, notes); // End snippet } /// <summary>Snippet for BatchCreateNotes</summary> public void BatchCreateNotesResourceNames() { string endpoint = ""; // Snippet: BatchCreateNotes(ProjectName, IDictionary<string,Note>, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); IDictionary<string, Note> notes = new Dictionary<string, Note> { { "", new Note() }, }; // Make the request BatchCreateNotesResponse response = grafeasClient.BatchCreateNotes(parent, notes); // End snippet } /// <summary>Snippet for BatchCreateNotesAsync</summary> public async Task BatchCreateNotesResourceNamesAsync() { string endpoint = ""; // Snippet: BatchCreateNotesAsync(ProjectName, IDictionary<string,Note>, CallSettings) // Additional: BatchCreateNotesAsync(ProjectName, IDictionary<string,Note>, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); IDictionary<string, Note> notes = new Dictionary<string, Note> { { "", new Note() }, }; // Make the request BatchCreateNotesResponse response = await grafeasClient.BatchCreateNotesAsync(parent, notes); // End snippet } /// <summary>Snippet for UpdateNote</summary> public void UpdateNoteRequestObject() { string endpoint = ""; // Snippet: UpdateNote(UpdateNoteRequest, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) UpdateNoteRequest request = new UpdateNoteRequest { NoteName = NoteName.FromProjectNote("[PROJECT]", "[NOTE]"), Note = new Note(), UpdateMask = new FieldMask(), }; // Make the request Note response = grafeasClient.UpdateNote(request); // End snippet } /// <summary>Snippet for UpdateNoteAsync</summary> public async Task UpdateNoteRequestObjectAsync() { string endpoint = ""; // Snippet: UpdateNoteAsync(UpdateNoteRequest, CallSettings) // Additional: UpdateNoteAsync(UpdateNoteRequest, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) UpdateNoteRequest request = new UpdateNoteRequest { NoteName = NoteName.FromProjectNote("[PROJECT]", "[NOTE]"), Note = new Note(), UpdateMask = new FieldMask(), }; // Make the request Note response = await grafeasClient.UpdateNoteAsync(request); // End snippet } /// <summary>Snippet for UpdateNote</summary> public void UpdateNote() { string endpoint = ""; // Snippet: UpdateNote(string, Note, FieldMask, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string name = "projects/[PROJECT]/notes/[NOTE]"; Note note = new Note(); FieldMask updateMask = new FieldMask(); // Make the request Note response = grafeasClient.UpdateNote(name, note, updateMask); // End snippet } /// <summary>Snippet for UpdateNoteAsync</summary> public async Task UpdateNoteAsync() { string endpoint = ""; // Snippet: UpdateNoteAsync(string, Note, FieldMask, CallSettings) // Additional: UpdateNoteAsync(string, Note, FieldMask, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string name = "projects/[PROJECT]/notes/[NOTE]"; Note note = new Note(); FieldMask updateMask = new FieldMask(); // Make the request Note response = await grafeasClient.UpdateNoteAsync(name, note, updateMask); // End snippet } /// <summary>Snippet for UpdateNote</summary> public void UpdateNoteResourceNames() { string endpoint = ""; // Snippet: UpdateNote(NoteName, Note, FieldMask, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) NoteName name = NoteName.FromProjectNote("[PROJECT]", "[NOTE]"); Note note = new Note(); FieldMask updateMask = new FieldMask(); // Make the request Note response = grafeasClient.UpdateNote(name, note, updateMask); // End snippet } /// <summary>Snippet for UpdateNoteAsync</summary> public async Task UpdateNoteResourceNamesAsync() { string endpoint = ""; // Snippet: UpdateNoteAsync(NoteName, Note, FieldMask, CallSettings) // Additional: UpdateNoteAsync(NoteName, Note, FieldMask, CancellationToken) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) NoteName name = NoteName.FromProjectNote("[PROJECT]", "[NOTE]"); Note note = new Note(); FieldMask updateMask = new FieldMask(); // Make the request Note response = await grafeasClient.UpdateNoteAsync(name, note, updateMask); // End snippet } /// <summary>Snippet for ListNoteOccurrences</summary> public void ListNoteOccurrencesRequestObject() { string endpoint = ""; // Snippet: ListNoteOccurrences(ListNoteOccurrencesRequest, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) ListNoteOccurrencesRequest request = new ListNoteOccurrencesRequest { NoteName = NoteName.FromProjectNote("[PROJECT]", "[NOTE]"), Filter = "", }; // Make the request PagedEnumerable<ListNoteOccurrencesResponse, Occurrence> response = grafeasClient.ListNoteOccurrences(request); // Iterate over all response items, lazily performing RPCs as required foreach (Occurrence item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListNoteOccurrencesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Occurrence item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Occurrence> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Occurrence item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListNoteOccurrences</summary> public async Task ListNoteOccurrencesRequestObjectAsync() { string endpoint = ""; // Snippet: ListNoteOccurrencesAsync(ListNoteOccurrencesRequest, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) ListNoteOccurrencesRequest request = new ListNoteOccurrencesRequest { NoteName = NoteName.FromProjectNote("[PROJECT]", "[NOTE]"), Filter = "", }; // Make the request PagedAsyncEnumerable<ListNoteOccurrencesResponse, Occurrence> response = grafeasClient.ListNoteOccurrencesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Occurrence item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListNoteOccurrencesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Occurrence item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Occurrence> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Occurrence item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListNoteOccurrences</summary> public void ListNoteOccurrences() { string endpoint = ""; // Snippet: ListNoteOccurrences(string, string, string, int?, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string name = "projects/[PROJECT]/notes/[NOTE]"; string filter = ""; // Make the request PagedEnumerable<ListNoteOccurrencesResponse, Occurrence> response = grafeasClient.ListNoteOccurrences(name, filter); // Iterate over all response items, lazily performing RPCs as required foreach (Occurrence item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListNoteOccurrencesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Occurrence item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Occurrence> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Occurrence item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListNoteOccurrences</summary> public async Task ListNoteOccurrencesAsync() { string endpoint = ""; // Snippet: ListNoteOccurrencesAsync(string, string, string, int?, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) string name = "projects/[PROJECT]/notes/[NOTE]"; string filter = ""; // Make the request PagedAsyncEnumerable<ListNoteOccurrencesResponse, Occurrence> response = grafeasClient.ListNoteOccurrencesAsync(name, filter); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Occurrence item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListNoteOccurrencesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Occurrence item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Occurrence> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Occurrence item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListNoteOccurrences</summary> public void ListNoteOccurrencesResourceNames() { string endpoint = ""; // Snippet: ListNoteOccurrences(NoteName, string, string, int?, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) NoteName name = NoteName.FromProjectNote("[PROJECT]", "[NOTE]"); string filter = ""; // Make the request PagedEnumerable<ListNoteOccurrencesResponse, Occurrence> response = grafeasClient.ListNoteOccurrences(name, filter); // Iterate over all response items, lazily performing RPCs as required foreach (Occurrence item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListNoteOccurrencesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Occurrence item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Occurrence> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Occurrence item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListNoteOccurrences</summary> public async Task ListNoteOccurrencesResourceNamesAsync() { string endpoint = ""; // Snippet: ListNoteOccurrencesAsync(NoteName, string, string, int?, CallSettings) // Create client GrafeasClient grafeasClient = new GrafeasClientBuilder { Endpoint = endpoint }.Build(); // Initialize request argument(s) NoteName name = NoteName.FromProjectNote("[PROJECT]", "[NOTE]"); string filter = ""; // Make the request PagedAsyncEnumerable<ListNoteOccurrencesResponse, Occurrence> response = grafeasClient.ListNoteOccurrencesAsync(name, filter); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Occurrence item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListNoteOccurrencesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Occurrence item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Occurrence> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Occurrence item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } } }
45.430238
138
0.58831
[ "Apache-2.0" ]
shyamsundarb-arch/google-cloud-dotnet
apis/Grafeas.V1/Grafeas.V1.Snippets/GrafeasClientSnippets.g.cs
89,543
C#
using System; using System.Collections.Generic; using System.Linq; using Windows.Foundation.Collections; namespace GamepadSemester.Common { /// <summary> /// Реализация интерфейса IObservableMap, поддерживающего повторный вход для использования в качестве модели представления /// по умолчанию. /// </summary> public class ObservableDictionary : IObservableMap<string, object> { private class ObservableDictionaryChangedEventArgs : IMapChangedEventArgs<string> { public ObservableDictionaryChangedEventArgs(CollectionChange change, string key) { this.CollectionChange = change; this.Key = key; } public CollectionChange CollectionChange { get; private set; } public string Key { get; private set; } } private Dictionary<string, object> _dictionary = new Dictionary<string, object>(); public event MapChangedEventHandler<string, object> MapChanged; private void InvokeMapChanged(CollectionChange change, string key) { var eventHandler = MapChanged; if (eventHandler != null) { eventHandler(this, new ObservableDictionaryChangedEventArgs(change, key)); } } public void Add(string key, object value) { this._dictionary.Add(key, value); this.InvokeMapChanged(CollectionChange.ItemInserted, key); } public void Add(KeyValuePair<string, object> item) { this.Add(item.Key, item.Value); } public bool Remove(string key) { if (this._dictionary.Remove(key)) { this.InvokeMapChanged(CollectionChange.ItemRemoved, key); return true; } return false; } public bool Remove(KeyValuePair<string, object> item) { object currentValue; if (this._dictionary.TryGetValue(item.Key, out currentValue) && Object.Equals(item.Value, currentValue) && this._dictionary.Remove(item.Key)) { this.InvokeMapChanged(CollectionChange.ItemRemoved, item.Key); return true; } return false; } public object this[string key] { get { return this._dictionary[key]; } set { this._dictionary[key] = value; this.InvokeMapChanged(CollectionChange.ItemChanged, key); } } public void Clear() { var priorKeys = this._dictionary.Keys.ToArray(); this._dictionary.Clear(); foreach (var key in priorKeys) { this.InvokeMapChanged(CollectionChange.ItemRemoved, key); } } public ICollection<string> Keys { get { return this._dictionary.Keys; } } public bool ContainsKey(string key) { return this._dictionary.ContainsKey(key); } public bool TryGetValue(string key, out object value) { return this._dictionary.TryGetValue(key, out value); } public ICollection<object> Values { get { return this._dictionary.Values; } } public bool Contains(KeyValuePair<string, object> item) { return this._dictionary.Contains(item); } public int Count { get { return this._dictionary.Count; } } public bool IsReadOnly { get { return false; } } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { return this._dictionary.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this._dictionary.GetEnumerator(); } public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) { int arraySize = array.Length; foreach (var pair in this._dictionary) { if (arrayIndex >= arraySize) break; array[arrayIndex++] = pair; } } } }
29.213333
126
0.55728
[ "Apache-2.0" ]
GudoshnikovaAnna/qreal
plugins/appFamily/Joystick/Common/ObservableDictionary.cs
4,487
C#
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2014 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit mindtouch.com; * please review the licensing section. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MindTouch Dream Misc Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("MindTouch, Inc.")] [assembly: AssemblyProduct("MindTouch Dream")] [assembly: AssemblyCopyright("Copyright (c) 2006-2014 MindTouch, Inc.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: log4net.Config.XmlConfigurator(Watch = true)] // 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("08465a1f-5950-4e3b-935e-d831dcb72ba5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("2.5.0.*")] [assembly: AssemblyFileVersion("2.5.0.0")]
39.603448
85
0.725729
[ "Apache-2.0" ]
PeteE/DReAM
src/tests/DreamMisc/AssemblyInfo.cs
2,299
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the chime-2018-05-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Chime.Model { /// <summary> /// This is the response object from the DeleteAppInstanceStreamingConfigurations operation. /// </summary> public partial class DeleteAppInstanceStreamingConfigurationsResponse : AmazonWebServiceResponse { } }
30.5
103
0.743745
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Chime/Generated/Model/DeleteAppInstanceStreamingConfigurationsResponse.cs
1,159
C#
using CooperSystem.Domain.Dto; using CooperSystem.Domain.Repositories; using Dapper; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace CooperSystem.Infrastructure.Data.Repositories { public class CarroRepository : ICarroRepository { private readonly string connectionString; public CarroRepository(string connectionString) { this.connectionString = connectionString; } public async Task<CarroResponse> Add(CarroRequest carro) { try { using (IDbConnection db = new SqlConnection(connectionString)) { string insertSql = @"INSERT INTO Carro (Nome, [Km_por_galao], Cilindros,[Cavalor_de_forca], Peso, Aceleracao, Ano, OrigemId) VALUES (@Nome, @Km_por_galao, @Cilindros, @Cavalor_de_forca, @Peso, @Aceleracao, @Ano, @OrigemId) SELECT CAST(SCOPE_IDENTITY() as int)"; DynamicParameters Parameters = new DynamicParameters(); Parameters.Add("@Nome", carro.Nome); Parameters.Add("@Km_por_galao", carro.Km_por_galao); Parameters.Add("@Cilindros", carro.Cilindros); Parameters.Add("@Cavalor_de_forca", carro.Cavalor_de_forca); Parameters.Add("@Peso", carro.Peso); Parameters.Add("@Aceleracao", carro.Aceleracao); Parameters.Add("@Ano", carro.Ano); Parameters.Add("@OrigemId", carro.OrigemId); var id = db.QueryAsync<int>(insertSql, Parameters).Result.SingleOrDefault(); string selectSql = @"Select C.*, O.* from Carro as C inner join Origem as O on O.id = C.OrigemId where C.Id = @Id"; var response = db.QueryAsync<CarroResponse>(selectSql, new[] { typeof(CarroResponse), typeof(OrigemResponse), }, objects => { CarroResponse carro = objects[0] as CarroResponse; carro.Origem = (OrigemResponse)objects[1]; return carro; }, splitOn: "Id", param: new { Id = id }).Result.SingleOrDefault(); return response; } } catch (Exception ex) { return null; } } public async Task<int> Delete(int id) { try { using (IDbConnection db = new SqlConnection(connectionString)) { string updateQuery = @"UPDATE[dbo].[Carro] SET Enabled = @Enabled, UpdatedAt = @UpdatedAt WHERE Id = @Id"; int rowsAffected = await db.ExecuteAsync(updateQuery, new { Id = id , UpdatedAt = DateTime.Now , Enabled = false }); return rowsAffected; } } catch (Exception ex) { return 0; } } public async Task<List<CarroGet>> GetAll(string nome, string origem) { try { using (IDbConnection db = new SqlConnection(connectionString)) { string selectnome = nome != null ? " and C.Nome Like '%' + @Nome + '%' " : ""; string selectorigem = origem != null ? " and O.Abbr = @Abbr " : ""; string selectSql = @"Select * from Carro as C inner join Origem as O on O.id = C.OrigemId where Enabled = 1 " + selectnome + selectorigem; var response = db.QueryAsync<CarroGet>(selectSql, new[] { typeof(CarroGet), typeof(OrigemResponse), }, objects => { CarroGet carro = objects[0] as CarroGet; carro.Origem = (OrigemResponse)objects[1]; return carro; }, splitOn: "Id", param: new { Nome = nome, Abbr = origem }).Result.ToList(); return response; } } catch (Exception ex) { return null; } } public async Task<CarroResponse> GetCarro(int id) { try { using (IDbConnection db = new SqlConnection(connectionString)) { string selectSql = @"Select * from Carro as C inner join Origem as O on O.id = C.OrigemId where C.Id = @Id and Enabled = 1"; var response = db.QueryAsync<CarroResponse>(selectSql, new[] { typeof(CarroResponse), typeof(OrigemResponse), }, objects => { CarroResponse carro = objects[0] as CarroResponse; carro.Origem = (OrigemResponse)objects[1]; return carro; }, splitOn: "Id", param: new { Id = id }).Result.SingleOrDefault(); return response; } } catch (Exception ex) { return null; } } public async Task<CarroResponse> Update(CarroUpdate carro) { try { using (IDbConnection db = new SqlConnection(connectionString)) { string updateQuery = @"UPDATE [Carro] SET Nome = @Nome, [Km_por_galao] = @Km_por_galao, Cilindros = @Cilindros, [Cavalor_de_forca] = @Cavalor_de_forca, Peso = @Peso , Ano = @Ano, OrigemId = @OrigemId, UpdatedAt = @UpdatedAt WHERE Id = @Id"; DynamicParameters Parameters = new DynamicParameters(); Parameters.Add("@Id", carro.Id); Parameters.Add("@Nome", carro.Nome); Parameters.Add("@Km_por_galao", carro.Km_por_galao); Parameters.Add("@Cilindros", carro.Cilindros); Parameters.Add("@Cavalor_de_forca", carro.Cavalor_de_forca); Parameters.Add("@Peso", carro.Peso); Parameters.Add("@Aceleracao", carro.Aceleracao); Parameters.Add("@Ano", carro.Ano); Parameters.Add("@OrigemId", carro.OrigemId); Parameters.Add("@UpdatedAt", DateTime.Now); db.QueryAsync<int>(updateQuery, Parameters).Result.SingleOrDefault(); string selectSql = @"Select C.*, O.* from Carro as C inner join Origem as O on O.id = C.OrigemId where C.Id = @Id"; var response = db.QueryAsync<CarroResponse>(selectSql, new[] { typeof(CarroResponse), typeof(OrigemResponse), }, objects => { CarroResponse carro = objects[0] as CarroResponse; carro.Origem = (OrigemResponse)objects[1]; return carro; }, splitOn: "Id", param: new { Id = carro.Id }).Result.SingleOrDefault(); return response; } } catch (Exception ex) { return null; } } } }
35.638767
156
0.461928
[ "MIT" ]
danielm2512/CooperSystem
CooperSystem.Infrastructure/Repositories/CarroRepository.cs
8,092
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ec2-2016-11-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.EC2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.EC2.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ClientVpnRouteStatus Object /// </summary> public class ClientVpnRouteStatusUnmarshaller : IUnmarshaller<ClientVpnRouteStatus, XmlUnmarshallerContext>, IUnmarshaller<ClientVpnRouteStatus, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public ClientVpnRouteStatus Unmarshall(XmlUnmarshallerContext context) { ClientVpnRouteStatus unmarshalledObject = new ClientVpnRouteStatus(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("code", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Code = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("message", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Message = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return unmarshalledObject; } } return unmarshalledObject; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <returns></returns> public ClientVpnRouteStatus Unmarshall(JsonUnmarshallerContext context) { return null; } private static ClientVpnRouteStatusUnmarshaller _instance = new ClientVpnRouteStatusUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ClientVpnRouteStatusUnmarshaller Instance { get { return _instance; } } } }
35.165049
173
0.602982
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/Internal/MarshallTransformations/ClientVpnRouteStatusUnmarshaller.cs
3,622
C#
using System; using System.Device.Gpio; using System.Device.Gpio.Drivers; namespace dotnet_led_button { class Program { private const int GPIOCHIP = 1; private const int LED_PIN = 36; private const int BUTTON_PIN = 38; private static PinValue ledPinValue = PinValue.Low; private static GpioController controller; private static int exitCode=0; static void Main(string[] args) { try { var drvGpio = new LibGpiodDriver(GPIOCHIP); controller = new GpioController(PinNumberingScheme.Logical, drvGpio); //set value if(!controller.IsPinOpen(LED_PIN)&&!controller.IsPinOpen(BUTTON_PIN)) { controller.OpenPin(LED_PIN,PinMode.Output); controller.OpenPin(BUTTON_PIN,PinMode.Input); } else { Console.WriteLine("LED_PIN or BUTTON_PIN is busy"); exitCode=-1; return; } controller.Write(LED_PIN,ledPinValue); //LED OFF // Console.WriteLine("CTRL+C to interrupt the read operation:"); controller.RegisterCallbackForPinValueChangedEvent(BUTTON_PIN,PinEventTypes.Rising,(o, e) => { ledPinValue=!ledPinValue; controller.Write(LED_PIN,ledPinValue); Console.WriteLine($"Press button, LED={ledPinValue}"); }); //Console string cki; while (true) { Console.Write("Press any key, or 'X' to quit, or "); Console.WriteLine("CTRL+C to interrupt the read operation:"); // Start a console read operation. Do not display the input. cki = Console.In.ReadLineAsync().GetAwaiter().GetResult(); // Announce the name of the key that was pressed . Console.WriteLine($" Key pressed: {cki}\n"); // Exit if the user pressed the 'X' key. if (cki == "X"||cki == "x") break; } } catch (Exception ex) { Console.WriteLine($"Error: {ex}"); exitCode=-2; } finally { if(controller is not null) controller.Dispose(); } Environment.Exit(exitCode); } } }
40.880597
108
0.469149
[ "MIT" ]
devdotnetorg/dotnet-iot-samples
dotnet-led-button/Program.cs
2,741
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.CodeDom; using System.Diagnostics; using Thinktecture.Tools.Web.Services.Wscf.Environment; namespace Thinktecture.Tools.Web.Services.CodeGeneration { [DebuggerDisplay("Name = {extendedObject.Name}")] public abstract class AttributableCodeDomObject : CodeTypeMember { #region Private Fields // Holds a reference to the actual object we are decorating. private CodeTypeMember extendedObject; // Dictionary we use for caching the CodeAttributeDeclaration(s). private Dictionary<string, CodeAttributeDeclaration> attributesCache; #endregion #region Constructors public AttributableCodeDomObject(CodeTypeMember extendedObject) { this.extendedObject = extendedObject; attributesCache = new Dictionary<string, CodeAttributeDeclaration>(); } #endregion #region Public Methods /// <summary> /// This method finds the attribute as specified by attribute parameter. /// </summary> /// <param name="attribute">string containing the name of the attribute.</param> /// <returns> /// If the requested attribute is found, this method returns a reference to it. /// Otherwise returns null. /// </returns> /// <remarks> /// This method initially looks up an internal attribute cache. If the attribute /// is not found in the cache, it searches for it in the actual object extended /// by this instance. If the attribute is found, this method adds it to internal /// cache causing the faster access time in the subsequent requests. /// </remarks> public CodeAttributeDeclaration FindAttribute(string attributeName) { if (string.IsNullOrEmpty(attributeName)) { throw new ArgumentException("attributeName could not be null or an empty string."); } if (attributesCache.ContainsKey(attributeName)) { return attributesCache[attributeName]; } foreach (CodeAttributeDeclaration attribDecl in extendedObject.CustomAttributes) { if (attribDecl.Name == attributeName) { attributesCache.Add(attributeName, attribDecl); return attribDecl; } } return null; } /// <summary> /// Finds all instances of the attribute with the specified name. /// </summary> /// <param name="attributeName">Name of the attribute.</param> /// <returns>A list of the matching attributes.</returns> public IEnumerable<CodeAttributeDeclaration> FindAttributes(string attributeName) { foreach (CodeAttributeDeclaration attribute in extendedObject.CustomAttributes .Cast<CodeAttributeDeclaration>() .Where(attribute => attribute.Name == attributeName)) { yield return attribute; } yield break; } /// <summary> /// Removes the attribute from the custom attributes collection of the type. /// </summary> /// <param name="attribute">The attribute to remove.</param> public void RemoveAttribute(CodeAttributeDeclaration attribute) { Enforce.IsNotNull(attribute, "attribute"); if (attributesCache.ContainsKey(attribute.Name)) { attributesCache.Remove(attribute.Name); } extendedObject.CustomAttributes.Remove(attribute); } /// <summary> /// Adds a new attribute to a attributes collection or modify an existing attribute. /// It checks whether a given attribute exists and adds it if its not there. If it is there, then it will /// add the arguments available in the new attribute but not available in the existing attribute. /// </summary> /// <param name="attribute">Attribute to add.</param> /// <returns> /// Returns true if the attribute is actually added to the object. Otherwise returns false. /// The latter happens when the attribute already exists in the object. /// </returns> public bool AddAttribute(CodeAttributeDeclaration attribDecl) { if (attribDecl == null) { throw new ArgumentException("attribDecl could not be null."); } CodeAttributeDeclaration existingAttrib = FindAttribute(attribDecl.Name); // Can we see a matching, existing attribute? Then try to sync the attributes. if (existingAttrib != null) { CodeTypeMemberExtension.SyncSourceAttributes(existingAttrib, attribDecl); return false; } else { // Add this to the CustomAttributes collection. extendedObject.CustomAttributes.Add(attribDecl); attributesCache.Add(attribDecl.Name, attribDecl); return true; } } /// <summary> /// /// </summary> private static void SyncSourceAttributes(CodeAttributeDeclaration source, CodeAttributeDeclaration destination) { Debug.Assert(source != null, "source parameter could not be null."); Debug.Assert(destination != null, "destination parameter could not be null."); // Process all arguments in the destination attribute. foreach (CodeAttributeArgument dstArg in destination.Arguments) { bool argumentFound = false; CodeAttributeArgumentExtended extDstArg = dstArg as CodeAttributeArgumentExtended; // Lookup all attribute arguments in the source to see if we can find a matching // argument. foreach (CodeAttributeArgument srcArg in source.Arguments) { // Can we access the argument with our extended type pointer? // Then use it to match empty argument names generated for // default arguments. if (extDstArg != null) { if ((string.Compare(srcArg.Name, extDstArg.Name, true) == 0) || (extDstArg.Default && srcArg.Name == "")) { // We've found the argument. argumentFound = true; // Sync value. srcArg.Value = extDstArg.Value; break; } } else { if (string.Compare(srcArg.Name, dstArg.Name, true) == 0) { // We've found the argument. argumentFound = true; // Sync value. srcArg.Value = dstArg.Value; break; } } } // Add the argument if we haven't found it yet. if (!argumentFound) { source.Arguments.Add(dstArg); } } } #endregion #region Public properties /// <summary> /// Gets the original instance extended by this decorator instance. /// </summary> /// <remarks> /// If you want to use the internal instance use this property to access it. /// However, refrain from searching and adding attributes directly using this /// reference if you are concerned about caching. /// </remarks> public CodeTypeMember ExtendedObject { get { return extendedObject; } } #endregion } }
37.900943
119
0.569757
[ "MIT" ]
WSCF/WSCF
src/Thinktecture.Tools.Web.Services.CodeGeneration/CodeDomExtensions/AttributableCodeDomObject.cs
8,035
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Reflection; using System.Linq; using System.Xml.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Amazon.CodeAnalysis.Shared; namespace Amazon.Synthetics.CodeAnalysis { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class PropertyValueAssignmentAnalyzer : AbstractPropertyValueAssignmentAnalyzer { public override string GetServiceName() { return "Synthetics"; } } }
27.32
91
0.749634
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/Synthetics/Generated/PropertyValueAssignmentAnalyzer.cs
683
C#
using System; namespace Cars { public class StartUp { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
13.769231
46
0.513966
[ "MIT" ]
VinsantSavov/SoftUni-Software-Engineering
CSharp-OOP/Homeworks-And-Labs/Interfaces and Abstraction/Lab/Lab/Cars/StartUp.cs
181
C#
// ****************************************************************************** // ** // ** Yahoo! Managed // ** Written by Marius Häusler 2012 // ** It would be pleasant, if you contact me when you are using this code. // ** Contact: YahooFinanceManaged@gmail.com // ** Project Home: http://code.google.com/p/yahoo-finance-managed/ // ** // ****************************************************************************** // ** // ** Copyright 2012 Marius Häusler // ** // ** Licensed under the Apache License, Version 2.0 (the "License"); // ** you may not use this file except in compliance with the License. // ** You may obtain a copy of the License at // ** // ** http://www.apache.org/licenses/LICENSE-2.0 // ** // ** Unless required by applicable law or agreed to in writing, software // ** distributed under the License is distributed on an "AS IS" BASIS, // ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // ** See the License for the specific language governing permissions and // ** limitations under the License. // ** // ****************************************************************************** using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; namespace MaasOne.Finance.YahooFinance { internal abstract class FinanceHelper { public const string NameOptionSymbol = "symbol"; public const string NameOptionType = "type"; public const string NameOptionLastPrice = "lastPrice"; public const string NameOptionStrikePrice = "strikePrice"; public const string NameOptionChange = "change"; public const string NameOptionBid = "bid"; public const string NameOptionAsk = "ask"; public const string NameOptionVolume = "vol"; public const string NameOptionOpenInterest = "openInt"; public const string NameOptionChangeDir = "changeDir"; public const string NameQuoteBaseID = "Symbol"; public const string NameQuoteBaseLastTradePriceOnly = "LastTradePriceOnly"; public const string NameQuoteBaseChange = "Change"; public const string NameQuoteBaseOpen = "Open"; public const string NameQuoteBaseDaysHigh = "DaysHigh"; public const string NameQuoteBaseDaysLow = "DaysLow"; public const string NameQuoteBaseVolume = "Volume"; public const string NameQuoteBaseLastTradeDate = "LastTradeDate"; public const string NameQuoteBaseLastTradeTime = "LastTradeTime"; public const string NameHistQuoteDate = "Date"; public const string NameHistQuoteOpen = "Open"; public const string NameHistQuoteHigh = "High"; public const string NameHistQuoteLow = "Low"; public const string NameHistQuoteClose = "Close"; public const string NameHistQuoteVolume = "Volume"; public const string NameHistQuoteAdjClose = "AdjClose"; public const string NameMarketName = "name"; public const string NameIndustryID = "id"; public const string NameCompanySymbol = "symbol"; public const string NameCompanyCompanyName = "CompanyName"; public const string NameCompanyStart = "start"; public const string NameCompanyEnd = "end"; public const string NameCompanySector = "Sector"; public const string NameCompanyIndustry = "Industry"; public const string NameCompanyFullTimeEmployees = "FullTimeEmployees"; public const string NameCompanyNotAvailable = "NaN"; private static System.Globalization.CultureInfo mDefaultCulture = new System.Globalization.CultureInfo("en-US"); public static System.Globalization.CultureInfo DefaultYqlCulture { get { return mDefaultCulture; } } public static IEnumerable<string> IIDsToStrings(IEnumerable<IID> idList) { List<string> lst = new List<string>(); if (idList != null) { foreach (IID id in idList) { if (id != null && id.ID != string.Empty) lst.Add(id.ID); } } return lst; } public static Sector[] SectorEnumToArray(IEnumerable<Sector> values) { List<Sector> lst = new List<Sector>(); if (values != null) { lst.AddRange(values); } return lst.ToArray(); } public static string[] CleanIDfromAT(IEnumerable<string> enm) { if (enm != null) { List<string> lst = new List<string>(); foreach (string id in enm) { lst.Add(CleanIndexID(id)); } return lst.ToArray(); } else { return null; } } public static string CleanIndexID(string id) { return id.Replace("@", ""); } public static QuoteProperty[] CheckPropertiesOfQuotesData(IEnumerable<QuotesData> quotes, IEnumerable<QuoteProperty> properties) { List<QuoteProperty> lstProperties = new List<QuoteProperty>(); if (properties == null) { return GetAllActiveProperties(quotes); } else { lstProperties.AddRange(properties); if (lstProperties.Count == 0) { return GetAllActiveProperties(quotes); } else { return lstProperties.ToArray(); } } } public static QuoteProperty[] GetAllActiveProperties(IEnumerable<QuotesData> quotes) { List<QuoteProperty> lst = new List<QuoteProperty>(); if (quotes != null) { foreach (QuoteProperty qp in Enum.GetValues(typeof(QuoteProperty))) { bool valueIsNotNull = false; foreach (QuotesData quote in quotes) { if (quote[qp] != null) { valueIsNotNull = true; break; // TODO: might not be correct. Was : Exit For } } if (valueIsNotNull) lst.Add(qp); } } return lst.ToArray(); } public static double GetStringMillionFactor(string s) { if (s.EndsWith("T") || s.EndsWith("K")) { return 1.0 / 1000; } else if (s.EndsWith("M")) { return 1; } else if (s.EndsWith("B")) { return 1000; } else { return 0; } } public static double GetMillionValue(string s) { double v = 0; double.TryParse(s.Substring(0, s.Length - 1), System.Globalization.NumberStyles.Any, mDefaultCulture, out v); return v * GetStringMillionFactor(s); } public static string CleanTd(string value) { List<char> sb = new List<char>(); if (value.Length > 0) { bool allowCopy = true; for (int i = 0; i <= value.Length - 1; i++) { if (value[i] == '<') { allowCopy = false; } else if (value[i] == '>') { allowCopy = true; continue; } if (allowCopy) sb.Add(value[i]); } } return new string(sb.ToArray()).Replace("&nbsp;", ""); } public static double ParseToDouble(string s) { double v = 0; double.TryParse(s.Replace("%", ""), System.Globalization.NumberStyles.Any, mDefaultCulture, out v); return v; } public static DateTime ParseToDateTime(string s) { DateTime d = new DateTime(); System.DateTime.TryParse(s, mDefaultCulture, System.Globalization.DateTimeStyles.AdjustToUniversal, out d); return d; } public static Support.YCurrencyID YCurrencyIDFromString(string id) { string idStr = id.ToUpper(); System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("[A-Z][A-Z][A-Z][A-Z][A-Z][A-Z]=X"); if (idStr.Length == 8 && regex.Match(idStr).Success) { Support.CurrencyInfo b = null; Support.CurrencyInfo dep = null; string baseStr = idStr.Substring(0, 3); string depStr = idStr.Substring(3, 3); foreach (Support.CurrencyInfo cur in Support.WorldMarket.DefaultCurrencies) { if (baseStr == cur.ID) { b = new Support.CurrencyInfo(cur.ID, cur.Description); } else if (depStr == cur.ID) { dep = new Support.CurrencyInfo(cur.ID, cur.Description); } if (b != null & dep != null) { return new Support.YCurrencyID(b, dep); } } return null; } else { return null; } } public static string GetChartImageSize(ChartImageSize value) { return value.ToString().Substring(0, 1).ToLower(); } public static string GetChartTimeSpan(ChartTimeSpan value) { if (value == ChartTimeSpan.cMax) { return "my"; } else { return value.ToString().Replace("c", "").ToLower(); } } public static string GetChartType(ChartType value) { return value.ToString().Substring(0, 1).ToLower(); } public static string GetChartScale(ChartScale value) { if (value == ChartScale.Arithmetic) { return "off"; } else { return "on"; } } public static string GetMovingAverageInterval(MovingAverageInterval value) { return value.ToString().Replace("m", ""); } public static string GetTechnicalIndicatorsI(TechnicalIndicator value) { switch (value) { case TechnicalIndicator.Bollinger_Bands: return value.ToString().Substring(0, 1).ToLower() + ','; case TechnicalIndicator.Parabolic_SAR: return value.ToString().Substring(0, 1).ToLower() + ','; case TechnicalIndicator.Splits: return value.ToString().Substring(0, 1).ToLower() + ','; case TechnicalIndicator.Volume: return value.ToString().Substring(0, 1).ToLower() + ','; default: return string.Empty; } } public static string GetTechnicalIndicatorsII(TechnicalIndicator value) { switch (value) { case TechnicalIndicator.MACD: return "m26-12-9,"; case TechnicalIndicator.MFI: return "f14,"; case TechnicalIndicator.ROC: return "p12,"; case TechnicalIndicator.RSI: return "r14,"; case TechnicalIndicator.Slow_Stoch: return "ss,"; case TechnicalIndicator.Fast_Stoch: return "fs,"; case TechnicalIndicator.Vol: return "v,"; case TechnicalIndicator.Vol_MA: return "vm,"; case TechnicalIndicator.W_R: return "w14,"; default: return string.Empty; } } public static char GetHistQuotesInterval(HistQuotesInterval item) { switch (item) { case HistQuotesInterval.Daily: return 'd'; case HistQuotesInterval.Weekly: return 'w'; default: return 'm'; } } public static string MarketQuotesRankingTypeString(MarketQuoteProperty rankedBy) { switch (rankedBy) { case MarketQuoteProperty.Name: return "coname"; case MarketQuoteProperty.DividendYieldPercent: return "yie"; case MarketQuoteProperty.LongTermDeptToEquity: return "qto"; case MarketQuoteProperty.MarketCapitalizationInMillion: return "mkt"; case MarketQuoteProperty.NetProfitMarginPercent: return "qpm"; case MarketQuoteProperty.OneDayPriceChangePercent: return "pr1"; case MarketQuoteProperty.PriceEarningsRatio: return "pee"; case MarketQuoteProperty.PriceToBookValue: return "pri"; case MarketQuoteProperty.PriceToFreeCashFlow: return "prf"; case MarketQuoteProperty.ReturnOnEquityPercent: return "ttm"; default: return string.Empty; } } public static string MarketQuotesRankingDirectionString(System.ComponentModel.ListSortDirection dir) { if (dir == ListSortDirection.Ascending) { return "u"; } else { return "d"; } } public static string CsvQuotePropertyTags(QuoteProperty[] properties) { System.Text.StringBuilder symbols = new System.Text.StringBuilder(); if (properties != null && properties.Length > 0) { foreach (QuoteProperty qp in properties) { switch (qp) { case QuoteProperty.Ask: symbols.Append("a0"); break; case QuoteProperty.AverageDailyVolume: symbols.Append("a2"); break; case QuoteProperty.AskSize: symbols.Append("a5"); break; case QuoteProperty.Bid: symbols.Append("b0"); break; case QuoteProperty.AskRealtime: symbols.Append("b2"); break; case QuoteProperty.BidRealtime: symbols.Append("b3"); break; case QuoteProperty.BookValuePerShare: symbols.Append("b4"); break; case QuoteProperty.BidSize: symbols.Append("b6"); break; case QuoteProperty.Change_ChangeInPercent: symbols.Append('c'); break; case QuoteProperty.Change: symbols.Append("c1"); break; case QuoteProperty.Commission: symbols.Append("c3"); break; case QuoteProperty.Currency: symbols.Append("c4"); break; case QuoteProperty.ChangeRealtime: symbols.Append("c6"); break; case QuoteProperty.AfterHoursChangeRealtime: symbols.Append("c8"); break; case QuoteProperty.TrailingAnnualDividendYield: symbols.Append("d0"); break; case QuoteProperty.LastTradeDate: symbols.Append("d1"); break; case QuoteProperty.TradeDate: symbols.Append("d2"); break; case QuoteProperty.DilutedEPS: symbols.Append("e0"); break; case QuoteProperty.EPSEstimateCurrentYear: symbols.Append("e7"); break; case QuoteProperty.EPSEstimateNextYear: symbols.Append("e8"); break; case QuoteProperty.EPSEstimateNextQuarter: symbols.Append("e9"); break; case QuoteProperty.TradeLinksAdditional: symbols.Append("f0"); break; case QuoteProperty.SharesFloat: symbols.Append("f6"); break; case QuoteProperty.DaysLow: symbols.Append("g0"); break; case QuoteProperty.HoldingsGainPercent: symbols.Append("g1"); break; case QuoteProperty.AnnualizedGain: symbols.Append("g3"); break; case QuoteProperty.HoldingsGain: symbols.Append("g4"); break; case QuoteProperty.HoldingsGainPercentRealtime: symbols.Append("g5"); break; case QuoteProperty.HoldingsGainRealtime: symbols.Append("g6"); break; case QuoteProperty.DaysHigh: symbols.Append("h0"); break; case QuoteProperty.MoreInfo: symbols.Append('i'); break; case QuoteProperty.OrderBookRealtime: symbols.Append("i5"); break; case QuoteProperty.YearLow: symbols.Append("j0"); break; case QuoteProperty.MarketCapitalization: symbols.Append("j1"); break; case QuoteProperty.SharesOutstanding: symbols.Append("j2"); break; case QuoteProperty.MarketCapRealtime: symbols.Append("j3"); break; case QuoteProperty.EBITDA: symbols.Append("j4"); break; case QuoteProperty.ChangeFromYearLow: symbols.Append("j5"); break; case QuoteProperty.PercentChangeFromYearLow: symbols.Append("j6"); break; case QuoteProperty.YearHigh: symbols.Append("k0"); break; case QuoteProperty.LastTradeRealtimeWithTime: symbols.Append("k1"); break; case QuoteProperty.ChangeInPercentRealtime: symbols.Append("k2"); break; case QuoteProperty.LastTradeSize: symbols.Append("k3"); break; case QuoteProperty.ChangeFromYearHigh: symbols.Append("k4"); break; case QuoteProperty.ChangeInPercentFromYearHigh: symbols.Append("k5"); break; case QuoteProperty.LastTradeWithTime: symbols.Append("l0"); break; case QuoteProperty.LastTradePriceOnly: symbols.Append("l1"); break; case QuoteProperty.HighLimit: symbols.Append("l2"); break; case QuoteProperty.LowLimit: symbols.Append("l3"); break; case QuoteProperty.DaysRange: symbols.Append('m'); break; case QuoteProperty.DaysRangeRealtime: symbols.Append("m2"); break; case QuoteProperty.FiftydayMovingAverage: symbols.Append("m3"); break; case QuoteProperty.TwoHundreddayMovingAverage: symbols.Append("m4"); break; case QuoteProperty.ChangeFromTwoHundreddayMovingAverage: symbols.Append("m5"); break; case QuoteProperty.PercentChangeFromTwoHundreddayMovingAverage: symbols.Append("m6"); break; case QuoteProperty.ChangeFromFiftydayMovingAverage: symbols.Append("m7"); break; case QuoteProperty.PercentChangeFromFiftydayMovingAverage: symbols.Append("m8"); break; case QuoteProperty.Name: symbols.Append("n0"); break; case QuoteProperty.Notes: symbols.Append("n4"); break; case QuoteProperty.Open: symbols.Append("o0"); break; case QuoteProperty.PreviousClose: symbols.Append("p0"); break; case QuoteProperty.PricePaid: symbols.Append("p1"); break; case QuoteProperty.ChangeInPercent: symbols.Append("p2"); break; case QuoteProperty.PriceSales: symbols.Append("p5"); break; case QuoteProperty.PriceBook: symbols.Append("p6"); break; case QuoteProperty.ExDividendDate: symbols.Append("q0"); break; case QuoteProperty.PERatio: symbols.Append("r0"); break; case QuoteProperty.DividendPayDate: symbols.Append("r1"); break; case QuoteProperty.PERatioRealtime: symbols.Append("r2"); break; case QuoteProperty.PEGRatio: symbols.Append("r5"); break; case QuoteProperty.PriceEPSEstimateCurrentYear: symbols.Append("r6"); break; case QuoteProperty.PriceEPSEstimateNextYear: symbols.Append("r7"); break; case QuoteProperty.Symbol: symbols.Append("s0"); break; case QuoteProperty.SharesOwned: symbols.Append("s1"); break; case QuoteProperty.Revenue: symbols.Append("s6"); break; case QuoteProperty.ShortRatio: symbols.Append("s7"); break; case QuoteProperty.LastTradeTime: symbols.Append("t1"); break; case QuoteProperty.TradeLinks: symbols.Append("t6"); break; case QuoteProperty.TickerTrend: symbols.Append("t7"); break; case QuoteProperty.OneyrTargetPrice: symbols.Append("t8"); break; case QuoteProperty.Volume: symbols.Append("v0"); break; case QuoteProperty.HoldingsValue: symbols.Append("v1"); break; case QuoteProperty.HoldingsValueRealtime: symbols.Append("v7"); break; case QuoteProperty.YearRange: symbols.Append("w0"); break; case QuoteProperty.DaysValueChange: symbols.Append("w1"); break; case QuoteProperty.DaysValueChangeRealtime: symbols.Append("w4"); break; case QuoteProperty.StockExchange: symbols.Append("x0"); break; case QuoteProperty.TrailingAnnualDividendYieldInPercent: symbols.Append("y0"); break; } } } return symbols.ToString(); } public static char ServerToDelimiter(YahooServer server) { if (server == YahooServer.Australia | server == YahooServer.Canada | server == YahooServer.HongKong | server == YahooServer.India | server == YahooServer.Korea | server == YahooServer.Mexico | server == YahooServer.Singapore | server == YahooServer.UK | server == YahooServer.USA) { return ','; } else { return ';'; } } private static string ReplaceDjiID(string id) { if (id.ToUpper() == "^DJI") { return "INDU"; } else { return id; } } private FinanceHelper() { } } }
40.779685
292
0.434871
[ "Apache-2.0" ]
kflu/yahoo-finance-managed
MaasOne.Yahoo/Finance/YahooFinance/FinanceHelper.cs
28,509
C#
namespace SharedElement.Official.Core.ViewModels { public class ListItemViewModel { public int Id { get; set; } public string Title { get; set; } public override string ToString() => Title; } }
18.846154
49
0.591837
[ "MIT" ]
Plac3hold3r/PH.SharedElement
src/SharedElement.Official.Core/ViewModels/ListItemViewModel.cs
247
C#
using FamilyTreeWebApp.Data; using FamilyTreeWebApp.Services; using FamilyTreeWebTools.Data; using FamilyTreeWebTools.Services; //using Newtonsoft.Json; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Http; using System.Text.Json; using System.Threading; using System.Threading.Tasks; namespace FamilyTreeServices.Pages { [Authorize] public class GeniLoginOkModel : PageModel { private static readonly TraceSource trace = new TraceSource("GeniLoginOk", SourceLevels.Information); //private static GeniAppAuthenticationClass appAuthentication = new GeniAppAuthenticationClass(); private readonly WebAppIdentity _appId; private readonly FamilyTreeDbContext _context; private readonly UserManager<IdentityUser> _userManager; private static HttpClient httpClient; private static HttpClientHandler clientHandler; public string Message { get; set; } public GeniLoginOkModel(FamilyTreeDbContext context, UserManager<IdentityUser> userManager, WebAppIdentity appId) { _context = context; _userManager = userManager; _appId = appId; } private class HttpAppAuthenticationResponse { public string access_token { get; set; } public string refresh_token { get; set; } public int expires_in { get; set; } } //[TempData] //public string geni_access_token { get; set; } //[TempData] //public string geni_expires_in { get; set; } public IActionResult OnGet(string code, string expires_in, string state, string message, string redirectTarget) { Message = "Logging into Geni...."; //geni_expires_in = expires_in; //geni_access_token = access_token; trace.TraceData(TraceEventType.Information, 0, "GeniLoginOkModel.OnGet() code:" + code + " expires_in: " + expires_in + " state: " + state + " message: " + message); if (string.IsNullOrEmpty(code)) { code = HttpContext.Session.GetString("geni_code"); expires_in = HttpContext.Session.GetString("token_expires_in"); trace.TraceData(TraceEventType.Warning, 0, "Error code is empty (1):" + code); if (string.IsNullOrEmpty(code)) { return Redirect("./Login"); } trace.TraceData(TraceEventType.Warning, 0, "Hmm code is almost empty:" + code); } else { HttpContext.Session.SetString("geni_code", code); HttpContext.Session.SetString("geni_access_token", ""); HttpContext.Session.SetString("token_expires_in", expires_in); HttpContext.Session.SetString("GedcomFilename", ""); HttpContext.Session.SetString("OriginalFilename", ""); } string retryCounter = HttpContext.Session.GetString("RetryCounter"); if (string.IsNullOrEmpty(retryCounter)) { retryCounter = "1"; } else { Message += " (retry " + retryCounter + ")"; int retryCounterValue = Convert.ToInt32(retryCounter); retryCounterValue++; retryCounter = retryCounterValue.ToString(); } HttpContext.Session.SetString("RetryCounter", retryCounter); /*if (refresh_token != null) { HttpContext.Session.SetString("geni_refresh_token", refresh_token); }*/ //string redirectUrl = "/FamilyTree/Analyze/Settings"; string redirectUrl = "https://improveyourtree.com/FamilyTree/Geni/LoginOk"; WebAuthentication appAuthentication = new WebAuthentication(_userManager.GetUserId(this.User), _appId.AppId, _appId.AppSecret, FamilyDbContextClass.UpdateGeniAuthentication); string redirectTo = appAuthentication.getRequestTokenUrl(code, redirectUrl); bool Ok = false; int retryCount = 0; string returnLine = null; do { try { clientHandler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }; clientHandler.UseDefaultCredentials = false; clientHandler.Credentials = CredentialCache.DefaultCredentials; clientHandler.AllowAutoRedirect = true; httpClient = new HttpClient(clientHandler); //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Uri.EscapeDataString(appAuthentication.GetAccessToken())); httpClient.DefaultRequestHeaders.Add("accept-encoding", "gzip,deflate"); //WebRequest webRequestGetUrl; //webRequestGetUrl = WebRequest.Create(redirectTo); Task<HttpResponseMessage> responseTask = httpClient.GetAsync(redirectUrl); HttpResponseMessage response = responseTask.Result; StreamReader objReader = new StreamReader(response.Content.ReadAsStream()); returnLine = objReader.ReadToEnd(); objReader.Dispose(); Ok = true; } catch (WebException we) { Message += " Web:" + retryCount.ToString(); trace.TraceData(TraceEventType.Warning, 0, "Error webException:" + retryCount + " " + we.ToString()); //HttpContext.Session.SetString("geni_code", ""); Thread.Sleep(2000); //return Redirect("./Login"); } catch (IOException ioe) { Message += " IO:" + retryCount.ToString(); trace.TraceData(TraceEventType.Warning, 0, "Error ioException:" + retryCount + " " + ioe.ToString()); Thread.Sleep(2000); } catch (Exception e) { Message += " e:" + retryCount.ToString(); trace.TraceData(TraceEventType.Warning, 0, "Error unknown Exception:" + retryCount + " " + e.ToString()); Thread.Sleep(2000); } retryCount++; if (retryCount == 5) { HttpContext.Session.SetString("geni_code", ""); return Redirect("./Login"); } } while (!Ok && retryCount < 5); HttpAppAuthenticationResponse appAuthenticationResponse = JsonSerializer.Deserialize<HttpAppAuthenticationResponse>(returnLine); if (appAuthenticationResponse != null) { trace.TraceData(TraceEventType.Information, 0, "GeniLoginOkModel.OnGet() get auth " + appAuthenticationResponse.access_token + " refreshToken:" + appAuthenticationResponse.refresh_token + " expiresIn:" + appAuthenticationResponse.expires_in); if (!String.IsNullOrEmpty(appAuthenticationResponse.access_token)) { HttpContext.Session.SetString("geni_access_token", appAuthenticationResponse.access_token); } if (!String.IsNullOrEmpty(appAuthenticationResponse.refresh_token)) { HttpContext.Session.SetString("geni_refresh_token", appAuthenticationResponse.refresh_token); } HttpContext.Session.SetString("token_expires_in", appAuthenticationResponse.expires_in.ToString()); HttpContext.Session.SetString("geni_code", ""); string curUser = _userManager.GetUserId(User); FamilyDbContextClass.SaveGeniAuthentication(_context, curUser, appAuthenticationResponse.access_token, appAuthenticationResponse.refresh_token, appAuthenticationResponse.expires_in); } //ViewData["access_token"] = access_token; //ViewData["expires_in"] = expires_in; if (redirectTarget == null) { redirectTarget = "/FamilyTree/Analyze/Settings"; } string AlternativeRedirect = HttpContext.Session.GetString("RedirectAfterGeniLogin"); if ((AlternativeRedirect != null) && (AlternativeRedirect.Length > 0)) { redirectTarget = AlternativeRedirect; trace.TraceData(TraceEventType.Information, 0, "GeniLoginOkModel.OnGet() redirect to " + redirectTarget); HttpContext.Session.SetString("RedirectAfterGeniLogin", ""); } return Redirect(redirectTarget); } public void OnPost() { //Message = "Your Login to Geni. post" ; trace.TraceData(TraceEventType.Information, 0, "GeniLoginOkModel.OnPost()"); //trace.TraceData(TraceEventType.Information, 0, "Geni LoginOk post " + Message); } } }
38.439815
250
0.680477
[ "Apache-2.0" ]
Ekmansoft/FamilyTreeWebApp
Areas/FamilyTree/Pages/Geni/LoginOk.cshtml.cs
8,303
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. using System; using System.ComponentModel; using System.Security.Cryptography; using System.Text; using Azure.Storage.Blobs.Models; namespace Azure.Storage.Sas { /// <summary> /// <see cref="BlobSasBuilder"/> is used to generate a Shared Access /// Signature (SAS) for an Azure Storage container or blob. /// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas" />. /// </summary> public struct BlobSasBuilder : IEquatable<BlobSasBuilder> { /// <summary> /// The storage service version to use to authenticate requests made /// with this shared access signature, and the service version to use /// when handling requests made with this shared access signature. /// </summary> public string Version { get; set; } /// <summary> /// The optional signed protocol field specifies the protocol /// permitted for a request made with the SAS. Possible values are /// <see cref="SasProtocol.HttpsAndHttp"/>, /// <see cref="SasProtocol.Https"/>, and /// <see cref="SasProtocol.None"/>. /// </summary> public SasProtocol Protocol { get; set; } /// <summary> /// Optionally specify the time at which the shared access signature /// becomes valid. If omitted when DateTimeOffset.MinValue is used, /// start time for this call is assumed to be the time when the /// storage service receives the request. /// </summary> public DateTimeOffset StartTime { get; set; } /// <summary> /// The time at which the shared access signature becomes invalid. /// This field must be omitted if it has been specified in an /// associated stored access policy. /// </summary> public DateTimeOffset ExpiryTime { get; set; } /// <summary> /// The permissions associated with the shared access signature. The /// user is restricted to operations allowed by the permissions. This /// field must be omitted if it has been specified in an associated /// stored access policy. The <see cref="BlobSasPermissions"/>, /// <see cref="ContainerSasPermissions"/>, and /// <see cref="SnapshotSasPermissions"/> can be used to create the /// permissions string. /// </summary> public string Permissions { get; set; } /// <summary> /// Specifies an IP address or a range of IP addresses from which to /// accept requests. If the IP address from which the request /// originates does not match the IP address or address range /// specified on the SAS token, the request is not authenticated. /// When specifying a range of IP addresses, note that the range is /// inclusive. /// </summary> public IPRange IPRange { get; set; } /// <summary> /// An optional unique value up to 64 characters in length that /// correlates to an access policy specified for the container. /// </summary> public string Identifier { get; set; } /// <summary> /// The name of the container being made accessible. /// </summary> public string ContainerName { get; set; } /// <summary> /// The name of the blob being made accessible, or /// <see cref="String.Empty"/> for a container SAS. /// </summary> public string BlobName { get; set; } /// <summary> /// The name of the snapshot being made accessible, or /// <see cref="String.Empty"/> for a blob SAS. /// </summary> public string Snapshot { get; set; } /// <summary> /// Specifies which resources are accessible via the shared access /// signature. /// /// Specify b if the shared resource is a blob. This grants access to /// the content and metadata of the blob. /// /// Specify c if the shared resource is a container. This grants /// access to the content and metadata of any blob in the container, /// and to the list of blobs in the container. /// /// Beginning in version 2018-11-09, specify bs if the shared resource /// is a blob snapshot. This grants access to the content and /// metadata of the specific snapshot, but not the corresponding root /// blob. /// </summary> public string Resource { get; set; } /// <summary> /// Override the value returned for Cache-Control response header. /// </summary> public string CacheControl { get; set; } /// <summary> /// Override the value returned for Content-Disposition response /// header. /// </summary> public string ContentDisposition { get; set; } /// <summary> /// Override the value returned for Cache-Encoding response header. /// </summary> public string ContentEncoding { get; set; } /// <summary> /// Override the value returned for Cache-Language response header. /// </summary> public string ContentLanguage { get; set; } /// <summary> /// Override the value returned for Cache-Type response header. /// </summary> public string ContentType { get; set; } /// <summary> /// Use an account's <see cref="StorageSharedKeyCredential"/> to sign this /// shared access signature values to produce the proper SAS query /// parameters for authenticating requests. /// </summary> /// <param name="sharedKeyCredential"> /// The storage account's <see cref="StorageSharedKeyCredential"/>. /// </param> /// <returns> /// The <see cref="BlobSasQueryParameters"/> used for authenticating /// requests. /// </returns> public BlobSasQueryParameters ToSasQueryParameters(StorageSharedKeyCredential sharedKeyCredential) { sharedKeyCredential = sharedKeyCredential ?? throw Errors.ArgumentNull(nameof(sharedKeyCredential)); this.EnsureState(); var startTime = SasQueryParameters.FormatTimesForSasSigning(this.StartTime); var expiryTime = SasQueryParameters.FormatTimesForSasSigning(this.ExpiryTime); // See http://msdn.microsoft.com/en-us/library/azure/dn140255.aspx var stringToSign = String.Join("\n", this.Permissions, startTime, expiryTime, GetCanonicalName(sharedKeyCredential.AccountName, this.ContainerName ?? String.Empty, this.BlobName ?? String.Empty), this.Identifier, this.IPRange.ToString(), this.Protocol.ToString(), this.Version, this.Resource, this.Snapshot, this.CacheControl, this.ContentDisposition, this.ContentEncoding, this.ContentLanguage, this.ContentType); var signature = sharedKeyCredential.ComputeHMACSHA256(stringToSign); var p = new BlobSasQueryParameters( version: this.Version, services: null, resourceTypes: null, protocol: this.Protocol, startTime: this.StartTime, expiryTime: this.ExpiryTime, ipRange: this.IPRange, identifier: this.Identifier, resource: this.Resource, permissions: this.Permissions, signature: signature); return p; } /// <summary> /// Use an account's <see cref="UserDelegationKey"/> to sign this /// shared access signature values to produce the propery SAS query /// parameters for authenticating requests. /// </summary> /// <param name="userDelegationKey"> /// A <see cref="UserDelegationKey"/> returned from /// <see cref="Azure.Storage.Blobs.BlobServiceClient.GetUserDelegationKeyAsync"/>. /// </param> /// <param name="accountName">The name of the storage account.</param> /// <returns> /// The <see cref="BlobSasQueryParameters"/> used for authenticating requests. /// </returns> public BlobSasQueryParameters ToSasQueryParameters(UserDelegationKey userDelegationKey, string accountName) { userDelegationKey = userDelegationKey ?? throw Errors.ArgumentNull(nameof(userDelegationKey)); this.EnsureState(); var startTime = SasQueryParameters.FormatTimesForSasSigning(this.StartTime); var expiryTime = SasQueryParameters.FormatTimesForSasSigning(this.ExpiryTime); var signedStart = SasQueryParameters.FormatTimesForSasSigning(userDelegationKey.SignedStart); var signedExpiry = SasQueryParameters.FormatTimesForSasSigning(userDelegationKey.SignedExpiry); // See http://msdn.microsoft.com/en-us/library/azure/dn140255.aspx var stringToSign = String.Join("\n", this.Permissions, startTime, expiryTime, GetCanonicalName(accountName, this.ContainerName ?? String.Empty, this.BlobName ?? String.Empty), userDelegationKey.SignedOid, userDelegationKey.SignedTid, signedStart, signedExpiry, userDelegationKey.SignedService, userDelegationKey.SignedVersion, this.IPRange.ToString(), this.Protocol.ToString(), this.Version, this.Resource, this.Snapshot, this.CacheControl, this.ContentDisposition, this.ContentEncoding, this.ContentLanguage, this.ContentType); var signature = ComputeHMACSHA256(userDelegationKey.Value, stringToSign); var p = new BlobSasQueryParameters( version: this.Version, services: null, resourceTypes: null, protocol: this.Protocol, startTime: this.StartTime, expiryTime: this.ExpiryTime, ipRange: this.IPRange, identifier: null, resource: this.Resource, permissions: this.Permissions, keyOid: userDelegationKey.SignedOid, keyTid: userDelegationKey.SignedTid, keyStart: userDelegationKey.SignedStart, keyExpiry: userDelegationKey.SignedExpiry, keyService: userDelegationKey.SignedService, keyVersion: userDelegationKey.SignedVersion, signature: signature); return p; } /// <summary> /// Computes the canonical name for a container or blob resource for SAS signing. /// Container: "/blob/account/containername" /// Blob: "/blob/account/containername/blobname" /// </summary> /// <param name="account">The name of the storage account.</param> /// <param name="containerName">The name of the container.</param> /// <param name="blobName">The name of the blob.</param> /// <returns>The canonical resource name.</returns> static string GetCanonicalName(string account, string containerName, string blobName) => !String.IsNullOrEmpty(blobName) ? $"/blob/{account}/{containerName}/{blobName.Replace("\\", "/")}" : $"/blob/{account}/{containerName}"; /// <summary> /// ComputeHMACSHA256 generates a base-64 hash signature string for an /// HTTP request or for a SAS. /// </summary> /// <param name="userDelegationKeyValue"> /// A <see cref="UserDelegationKey.Value"/> used to sign with a key /// representing AD credentials. /// </param> /// <param name="message">The message to sign.</param> /// <returns>The signed message.</returns> static string ComputeHMACSHA256(string userDelegationKeyValue, string message) => Convert.ToBase64String( new HMACSHA256( Convert.FromBase64String(userDelegationKeyValue)) .ComputeHash(Encoding.UTF8.GetBytes(message))); /// <summary> /// Ensure the <see cref="BlobSasBuilder"/>'s properties are in a /// consistent state. /// </summary> private void EnsureState() { // Container if (String.IsNullOrEmpty(this.BlobName)) { // Make sure the permission characters are in the correct order this.Permissions = ContainerSasPermissions.Parse(this.Permissions).ToString(); this.Resource = Constants.Sas.Resource.Container; } // Blob or Snapshot else { // Blob if (String.IsNullOrEmpty(this.Snapshot)) { // Make sure the permission characters are in the correct order this.Permissions = BlobSasPermissions.Parse(this.Permissions).ToString(); this.Resource = Constants.Sas.Resource.Blob; } // Snapshot else { // Make sure the permission characters are in the correct order this.Permissions = SnapshotSasPermissions.Parse(this.Permissions).ToString(); this.Resource = Constants.Sas.Resource.BlobSnapshot; } } if (String.IsNullOrEmpty(this.Version)) { this.Version = SasQueryParameters.DefaultSasVersion; } } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns>A string that represents the current object.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public override string ToString() => base.ToString(); /// <summary> /// Check if two BlobSasBuilder instances are equal. /// </summary> /// <param name="obj">The instance to compare to.</param> /// <returns>True if they're equal, false otherwise.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is BlobSasBuilder other && this.Equals(other); /// <summary> /// Get a hash code for the BlobSasBuilder. /// </summary> /// <returns>Hash code for the BlobSasBuilder.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => this.BlobName.GetHashCode() ^ this.CacheControl.GetHashCode() ^ this.ContainerName.GetHashCode() ^ this.ContentDisposition.GetHashCode() ^ this.ContentEncoding.GetHashCode() ^ this.ContentLanguage.GetHashCode() ^ this.ContentType.GetHashCode() ^ this.ExpiryTime.GetHashCode() ^ this.Identifier.GetHashCode() ^ this.IPRange.GetHashCode() ^ this.Permissions.GetHashCode() ^ this.Protocol.GetHashCode() ^ this.StartTime.GetHashCode() ^ this.Version.GetHashCode(); /// <summary> /// Check if two BlobSasBuilder instances are equal. /// </summary> /// <param name="left">The first instance to compare.</param> /// <param name="right">The second instance to compare.</param> /// <returns>True if they're equal, false otherwise.</returns> public static bool operator ==(BlobSasBuilder left, BlobSasBuilder right) => left.Equals(right); /// <summary> /// Check if two BlobSasBuilder instances are not equal. /// </summary> /// <param name="left">The first instance to compare.</param> /// <param name="right">The second instance to compare.</param> /// <returns>True if they're not equal, false otherwise.</returns> public static bool operator !=(BlobSasBuilder left, BlobSasBuilder right) => !(left == right); /// <summary> /// Check if two BlobSasBuilder instances are equal. /// </summary> /// <param name="other">The instance to compare to.</param> /// <returns>True if they're equal, false otherwise.</returns> public bool Equals(BlobSasBuilder other) => this.BlobName == other.BlobName && this.CacheControl == other.CacheControl && this.ContainerName == other.ContainerName && this.ContentDisposition == other.ContentDisposition && this.ContentEncoding == other.ContentEncoding && this.ContentLanguage == other.ContentEncoding && this.ContentType == other.ContentType && this.ExpiryTime == other.ExpiryTime && this.Identifier == other.Identifier && this.IPRange == other.IPRange && this.Permissions == other.Permissions && this.Protocol == other.Protocol && this.StartTime == other.StartTime && this.Version == other.Version; } }
43.114078
134
0.590103
[ "MIT" ]
Only2125/azure-sdk-for-net
sdk/storage/Azure.Storage.Blobs/src/Sas/BlobSasBuilder.cs
17,765
C#
using System; using System.Data; using System.Collections; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using Mediachase.Ibn.Web.UI.WebControls; using Mediachase.IBN.Business; using System.Globalization; using System.Resources; using System.Reflection; namespace Mediachase.Ibn.Web.UI.HelpDeskManagement.Modules { public partial class AssignResponsible : System.Web.UI.UserControl { protected ResourceManager LocRM = new ResourceManager("Mediachase.UI.Web.App_GlobalResources.Incidents.Resources.strIncidentGeneral", Assembly.GetExecutingAssembly()); #region Command protected string Command { get { string retval = String.Empty; if (Request["commandName"] != null) retval = Request["commandName"]; return retval; } } #endregion protected void Page_Load(object sender, EventArgs e) { UtilHelper.RegisterCssStyleSheet(Page, "~/Styles/IbnFramework/objectDD.css"); divErrors.Visible = false; ApplyLocalization(); if (!IsPostBack) { BindValues(); ClientScript.RegisterStartupScript(this.Page, this.Page.GetType(), Guid.NewGuid().ToString("N"), "GetIds();", true); } CommandManager cm = CommandManager.GetCurrent(this.Page); cm.AddCommand("Incident", "", "IncidentView", "MC_HDM_SelectResourceInFrame"); cm.AddCommand("Incident", "", "IncidentView", "MC_HDM_GroupResponsibilityInFrame"); } #region Page_PreRender protected void Page_PreRender(object sender, EventArgs e) { BindList(); } #endregion #region ApplyLocalization private void ApplyLocalization() { btnSave.Text = GetGlobalResourceObject("IbnFramework.Global", "_mc_Save").ToString(); btnSave.CustomImage = Page.ResolveUrl("~/Layouts/Images/saveitem.gif"); btnCancel.Text = GetGlobalResourceObject("IbnFramework.Global", "_mc_Cancel").ToString(); btnCancel.CustomImage = Page.ResolveUrl("~/Layouts/Images/cancel.gif"); btnClose.Text = GetGlobalResourceObject("IbnFramework.Global", "_mc_Close").ToString(); btnClose.CustomImage = Page.ResolveUrl("~/Layouts/Images/cancel.gif"); btnClose.ServerClick += new EventHandler(btnClose_ServerClick); if (Request["closeFramePopup"] != null) btnCancel.Attributes.Add("onclick", String.Format(CultureInfo.InvariantCulture, "javascript:try{{window.parent.{0}();}}catch(ex){{;}}return false;", Request["closeFramePopup"])); this.btnRefresh.Click += new EventHandler(btnRefresh_Click); this.btnRefreshMore.Click += new EventHandler(btnRefreshMore_Click); this.btnSave.ServerClick += new EventHandler(btnSave_ServerClick); } #endregion #region BindValues private void BindValues() { DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn("ResourceId", typeof(int))); dt.Columns.Add(new DataColumn("IncidentId", typeof(int))); dt.Columns.Add(new DataColumn("PrincipalId", typeof(int))); dt.Columns.Add(new DataColumn("IsGroup", typeof(bool))); dt.Columns.Add(new DataColumn("MustBeConfirmed", typeof(bool))); dt.Columns.Add(new DataColumn("ResponsePending", typeof(bool))); dt.Columns.Add(new DataColumn("IsConfirmed", typeof(bool))); dt.Columns.Add(new DataColumn("IsExternal", typeof(bool))); dt.Columns.Add(new DataColumn("IsNew", typeof(bool))); ViewState["ResponsiblePool"] = dt.Copy(); CommandManager cm = CommandManager.GetCurrent(this.Page); lblClient.Text = "&nbsp;"; hidResp.Value = "-3"; lblChange.Text = String.Format(CultureInfo.InvariantCulture, "<img alt='' class='btndown2' src='{0}'/>", Page.ResolveUrl("~/Layouts/Images/downbtn.gif")); tdChange.Attributes.Add("onclick", "javascript:ShowHideList(event, '" + tdChange.ClientID + "')"); tdChange.Style.Add("cursor", "pointer"); } #endregion private static HtmlTableCell CreateDDCell(string onclick) { HtmlTableCell tc = new HtmlTableCell(); tc.Attributes.Add("class", "cellclass"); tc.Attributes.Add("onmouseover", "TdOver(this)"); tc.Attributes.Add("onmouseout", "TdOut(this)"); tc.Attributes.Add("onclick", onclick); return tc; } #region BindList private void BindList() { DataTable dt = null; if (ViewState["ResponsiblePool"] != null) dt = ((DataTable)ViewState["ResponsiblePool"]).Copy(); string sUsers = ""; if (dt != null) foreach (DataRow dr in dt.Rows) { if ((bool)dr["ResponsePending"]) sUsers += dr["PrincipalId"].ToString() + "*1_"; else sUsers += dr["PrincipalId"].ToString() + "*0_"; } tableDD.Rows.Clear(); HtmlTableRow tr = null; HtmlTableCell tc = null; CommandManager cm = CommandManager.GetCurrent(this.Page); CommandParameters cp = null; string cmd = String.Empty; //NotChange tr = new HtmlTableRow(); tc = CreateDDCell("SelectThis(this, -3)"); tc.InnerHtml = "&nbsp;"; tr.Cells.Add(tc); tableDD.Rows.Add(tr); //NotSet tr = new HtmlTableRow(); tc = CreateDDCell("SelectThis(this, -2)"); tc.InnerHtml = BuildIconAndText("not_set.png", "tRespNotSet"); tr.Cells.Add(tc); tableDD.Rows.Add(tr); //Group Resp tr = new HtmlTableRow(); tc = CreateDDCell("SelectThis(this, -1)"); if (IsAllDenied()) { if (!Mediachase.IBN.Business.Security.CurrentUser.IsExternal) { cp = new CommandParameters("MC_HDM_GroupResponsibilityInFrame"); cp.CommandArguments = new System.Collections.Generic.Dictionary<string, string>(); cp.AddCommandArgument("sUsersKey", sUsers); cp.AddCommandArgument("NotChangeKey", "0"); cmd = cm.AddCommand("Incident", "", "IncidentView", cp); tc.InnerHtml = BuildLinkWithIconAndText("red_denied.gif", "tRespGroup", cmd); } else tc.InnerHtml = BuildIconAndText("red_denied.gif", "tRespGroup"); } else { if (!Mediachase.IBN.Business.Security.CurrentUser.IsExternal) { cp = new CommandParameters("MC_HDM_GroupResponsibilityInFrame"); cp.CommandArguments = new System.Collections.Generic.Dictionary<string, string>(); cp.AddCommandArgument("sUsersKey", sUsers); cp.AddCommandArgument("NotChangeKey", "0"); cmd = cm.AddCommand("Incident", "", "IncidentView", cp); tc.InnerHtml = BuildLinkWithIconAndText("waiting.gif", "tRespGroup", cmd); } else tc.InnerHtml = BuildIconAndText("waiting.gif", "tRespGroup"); } tr.Cells.Add(tc); tableDD.Rows.Add(tr); //User tr = new HtmlTableRow(); tc = CreateDDCell("SelectThis(this, " + Mediachase.IBN.Business.Security.CurrentUser.UserID + ")"); tc.InnerHtml = Mediachase.UI.Web.Util.CommonHelper.GetUserStatusUL(Mediachase.IBN.Business.Security.CurrentUser.UserID); tr.Cells.Add(tc); tableDD.Rows.Add(tr); //MORE cp = new CommandParameters("MC_HDM_SelectResourceInFrame"); cmd = cm.AddCommand("Incident", "", "IncidentView", cp); cmd = "closeMenu();" + cmd; tr = new HtmlTableRow(); tc = CreateDDCell(cmd); tc.InnerHtml = String.Format("<b>{0}</b>", LocRM.GetString("tRespMore")); tr.Cells.Add(tc); tableDD.Rows.Add(tr); } #endregion #region btnRefreshMore_Click void btnRefreshMore_Click(object sender, EventArgs e) { string arg = Request["__EVENTARGUMENT"]; string[] values = arg.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries); if (values.Length >= 2) { hidResp.Value = values[1]; lblClient.Text = Mediachase.UI.Web.Util.CommonHelper.GetUserStatusUL(int.Parse(values[1], CultureInfo.InvariantCulture)); } } #endregion #region btnRefresh_Click void btnRefresh_Click(object sender, EventArgs e) { string arg = Request["__EVENTARGUMENT"]; string[] values = arg.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries); DataTable dt = null; ArrayList alUsers = new ArrayList(); if (ViewState["ResponsiblePool"] != null) dt = ((DataTable)ViewState["ResponsiblePool"]).Copy(); try { for (int i = 0; i < values.Length; i++) { string sUser = values[i].Substring(0, values[i].IndexOf("*")); string temp = values[i].Substring(values[i].IndexOf("*") + 1); string sStatus = temp.Substring(0, temp.IndexOf("*")); string sIsNew = temp.Substring(temp.IndexOf("*") + 1); alUsers.Add(int.Parse(sUser, CultureInfo.InvariantCulture)); DataRow[] dr_mas = dt.Select("PrincipalId=" + sUser); if (dr_mas.Length > 0) { dr_mas[0]["ResponsePending"] = (sStatus == "1"); if (sIsNew == "1") dr_mas[0]["IsNew"] = true; } else { DataRow newRow = dt.NewRow(); newRow["PrincipalId"] = int.Parse(sUser, CultureInfo.InvariantCulture); newRow["IsGroup"] = false; newRow["ResponsePending"] = (sStatus == "1"); newRow["IsNew"] = true; dt.Rows.Add(newRow); } } } catch { } ArrayList alDeleted = new ArrayList(); foreach (DataRow dr in dt.Rows) if (!alUsers.Contains((int)dr["PrincipalId"])) alDeleted.Add((int)dr["PrincipalId"]); foreach (int iDel in alDeleted) { DataRow[] dr_mas = dt.Select("PrincipalId = " + iDel); if (dr_mas.Length > 0) dt.Rows.Remove(dr_mas[0]); } ViewState["ResponsiblePool"] = dt.Copy(); CommandManager cm = CommandManager.GetCurrent(this.Page); if (IsAllDenied()) { if (!Mediachase.IBN.Business.Security.CurrentUser.IsExternal) { CommandParameters cp = new CommandParameters("MC_HDM_GroupResponsibilityInFrame"); cp.CommandArguments = new System.Collections.Generic.Dictionary<string, string>(); cp.AddCommandArgument("sUsersKey", arg); cp.AddCommandArgument("NotChangeKey", "0"); string cmd = cm.AddCommand("Incident", "", "IncidentView", cp); lblClient.Text = BuildLinkWithIconAndText("red_denied.gif", "tRespGroup", cmd); } else lblClient.Text = BuildIconAndText("red_denied.gif", "tRespGroup"); } else { if (!Mediachase.IBN.Business.Security.CurrentUser.IsExternal) { CommandParameters cp = new CommandParameters("MC_HDM_GroupResponsibilityInFrame"); cp.CommandArguments = new System.Collections.Generic.Dictionary<string, string>(); cp.AddCommandArgument("sUsersKey", arg); cp.AddCommandArgument("NotChangeKey", "0"); string cmd = cm.AddCommand("Incident", "", "IncidentView", cp); lblClient.Text = BuildLinkWithIconAndText("waiting.gif", "tRespGroup", cmd); } else lblClient.Text = BuildIconAndText("waiting.gif", "tRespGroup"); } } #endregion #region btnSave_ServerClick void btnSave_ServerClick(object sender, EventArgs e) { string values = hfValues.Value; if (!String.IsNullOrEmpty(values)) { DataTable dt = null; if (ViewState["ResponsiblePool"] != null) dt = ((DataTable)ViewState["ResponsiblePool"]).Copy(); int iRespId = -1; bool isRespGroup = false; switch (hidResp.Value) { case "-3": //not change iRespId = -3; isRespGroup = false; break; case "-2": //not set iRespId = -1; isRespGroup = false; break; case "-1": //group iRespId = -1; isRespGroup = true; break; default: //user try { iRespId = int.Parse(hidResp.Value, CultureInfo.InvariantCulture); isRespGroup = false; } catch { } break; } if (iRespId > -3) { string sMessage = txtComment.Text; sMessage = Mediachase.UI.Web.Util.CommonHelper.parsetext_br(sMessage); ArrayList errors = new ArrayList(); string[] elems = values.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in elems) { int id = Convert.ToInt32(s, CultureInfo.InvariantCulture); try { Issue2.UpdateQuickTracking(id, sMessage, iRespId, isRespGroup, dt); } catch { errors.Add(id); } } if (errors.Count > 0) { divErrors.Visible = true; tblMain.Visible = false; ShowErrors(errors); } else CloseThis(); } else CloseThis(); } else CloseThis(); } #endregion #region ShowErrors private void ShowErrors(ArrayList list) { string sIncs = String.Empty; foreach (int id in list) { sIncs += "<div style='padding-left:5px;'>-&nbsp;&nbsp;" + Incident.GetTitle(id) + "</div>"; } lblResult.Text = String.Format(GetGlobalResourceObject("IbnFramework.Incident", "ResponsibleNotChanged").ToString(), sIncs); } #endregion #region btnClose_ServerClick void btnClose_ServerClick(object sender, EventArgs e) { CloseThis(); } #endregion #region CloseThis private void CloseThis() { CHelper.RequireBindGrid(); if (!String.IsNullOrEmpty(Request["commandName"])) { string commandName = Request["commandName"]; CommandParameters cp = new CommandParameters(commandName); Mediachase.Ibn.Web.UI.WebControls.CommandHandler.RegisterCloseOpenedFrameScript(this.Page, cp.ToString()); } else Mediachase.Ibn.Web.UI.WebControls.CommandHandler.RegisterCloseOpenedFrameScript(this.Page, String.Empty); } #endregion #region IsAllDenied private bool IsAllDenied() { bool retVal = false; DataTable dt = ((DataTable)ViewState["ResponsiblePool"]).Copy(); foreach (DataRow dr in dt.Rows) if ((bool)dr["ResponsePending"]) { retVal = true; break; } return !retVal; } #endregion private string BuildIconAndText(string iconFileName, string textResourceName) { return string.Format(CultureInfo.InvariantCulture, "<span><img alt=\"\" src=\"{0}\" /></span> <span>{1}</span>", Page.ResolveUrl("~/Layouts/Images/" + iconFileName), HttpUtility.HtmlEncode(LocRM.GetString(textResourceName))); } private string BuildLinkWithIconAndText(string iconFileName, string textResourceName, string javaScriptCommand) { return string.Format(CultureInfo.InvariantCulture, "<a href=\"{0}\"><img alt=\"\" src=\"{1}\" /> {2}</a>", HttpUtility.HtmlAttributeEncode("javascript:" + javaScriptCommand), Page.ResolveUrl("~/Layouts/Images/" + iconFileName), HttpUtility.HtmlEncode(LocRM.GetString(textResourceName))); } } }
31.358407
182
0.672922
[ "MIT" ]
InstantBusinessNetwork/IBN
Source/Server/WebPortal/Apps/HelpDeskManagement/Modules/AssignResponsible.ascx.cs
14,174
C#
using System; using System.Linq; using UnityEngine.UI; namespace Nova { public class TitleController : ViewControllerBase { public Button exitButton; public AudioController bgmController; public string bgmName; public float bgmVolume = 0.5f; private const string SelectChapterFirstShownKey = ConfigManager.FirstShownKeyPrefix + "SelectChapter"; private GameState gameState; private ConfigManager configManager; private CheckpointManager checkpointManager; protected override void Awake() { base.Awake(); var controller = Utils.FindNovaGameController(); gameState = controller.GameState; configManager = controller.ConfigManager; checkpointManager = controller.CheckpointManager; exitButton.onClick.AddListener(() => Hide(Utils.Quit) ); } protected override void Start() { base.Start(); gameState.SaveInitialState(); Show(null); } public override void Show(Action onFinish) { base.Show(() => { viewManager.dialoguePanel.SetActive(false); viewManager.StopAllAnimations(); gameState.ResetGameState(); if (bgmController != null && !string.IsNullOrEmpty(bgmName)) { bgmController.scriptVolume = bgmVolume; bgmController.Play(bgmName); } if (configManager.GetInt(SelectChapterFirstShownKey) == 0) { var unlockedChapterCount = gameState.GetAllUnlockedStartNodeNames().Count; var reachedChapterCount = gameState.GetAllStartNodeNames() .Count(name => checkpointManager.IsReachedWithAnyHistory(name, 0)); if (unlockedChapterCount == 1 && reachedChapterCount > 1) { Alert.Show(I18n.__("title.first.selectchapter")); configManager.SetInt(SelectChapterFirstShownKey, 1); } } onFinish?.Invoke(); }); } protected override void Update() { } } }
32.068493
110
0.555745
[ "MIT" ]
ErQing/Nova
Assets/Nova/Sources/Scripts/UI/Views/TitleController.cs
2,343
C#
namespace AppAny.HotChocolate.FluentValidation { /// <summary> /// Context for <see cref="SkipValidation" /> /// </summary> public readonly struct SkipValidationContext { public SkipValidationContext( IMiddlewareContext middlewareContext, IInputField argument) { MiddlewareContext = middlewareContext; Argument = argument; } public IMiddlewareContext MiddlewareContext { get; } public IInputField Argument { get; } } }
23.9
56
0.694561
[ "MIT" ]
appany/AppAny.HotChocolate.FluentValidation
src/SkipValidation/SkipValidationContext.cs
478
C#
using System; using System.Diagnostics; using System.Globalization; namespace Octokit { /// <summary> /// Describes a new deployment key to create. /// </summary> /// <remarks> /// API: https://developer.github.com/v3/repos/keys/ /// </remarks> [DebuggerDisplay("{DebuggerDisplay,nq}")] public class NewDeployKey { /// <summary> /// Gets or sets a name for the deployment key. /// </summary> /// <value> /// The title. /// </value> public string Title { get; set; } /// <summary> /// Gets or sets the contents of the deployment key. /// </summary> /// <value> /// The key. /// </value> public string Key { get; set; } /// <summary> /// Gets or sets a value indicating whether the key will only be able to read repository contents. Otherwise, /// the key will be able to read and write. /// </summary> /// <value> /// <c>true</c> if [read only]; otherwise, <c>false</c>. /// </value> public bool ReadOnly { get; set; } internal string DebuggerDisplay { get { return String.Format(CultureInfo.InvariantCulture, "Key: {0}, Title: {1}", Key, Title); } } } }
27.957447
118
0.530441
[ "MIT" ]
ROBISKMAGICIAN/Desainer.net
Octokit/Models/Request/NewDeployKey.cs
1,316
C#
namespace VetOffice { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ageClients1HYrToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ageClients2HYrToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ageClients3HYrToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.button4 = new System.Windows.Forms.Button(); this.listBox1 = new System.Windows.Forms.ListBox(); this.btnNew = new System.Windows.Forms.Button(); this.btnReturn = new System.Windows.Forms.Button(); this.btnBrood = new System.Windows.Forms.Button(); this.btnLookUp = new System.Windows.Forms.Button(); this.txtBox1 = new System.Windows.Forms.TextBox(); this.lblPrompt = new System.Windows.Forms.Label(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.optionsToolStripMenuItem, this.helpToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(1024, 24); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.fileToolStripMenuItem.Text = "File"; // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(92, 22); this.exitToolStripMenuItem.Text = "Exit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // optionsToolStripMenuItem // this.optionsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.ageClients1HYrToolStripMenuItem, this.ageClients2HYrToolStripMenuItem, this.ageClients3HYrToolStripMenuItem}); this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem"; this.optionsToolStripMenuItem.Size = new System.Drawing.Size(61, 20); this.optionsToolStripMenuItem.Text = "Options"; // // ageClients1HYrToolStripMenuItem // this.ageClients1HYrToolStripMenuItem.Name = "ageClients1HYrToolStripMenuItem"; this.ageClients1HYrToolStripMenuItem.Size = new System.Drawing.Size(170, 22); this.ageClients1HYrToolStripMenuItem.Tag = "1"; this.ageClients1HYrToolStripMenuItem.Text = "Age Clients 1 H-Yr"; this.ageClients1HYrToolStripMenuItem.Click += new System.EventHandler(this.ageClients1HYrToolStripMenuItem_Click); // // ageClients2HYrToolStripMenuItem // this.ageClients2HYrToolStripMenuItem.Name = "ageClients2HYrToolStripMenuItem"; this.ageClients2HYrToolStripMenuItem.Size = new System.Drawing.Size(170, 22); this.ageClients2HYrToolStripMenuItem.Tag = "2"; this.ageClients2HYrToolStripMenuItem.Text = "Age Clients 2 H-Yr"; this.ageClients2HYrToolStripMenuItem.Click += new System.EventHandler(this.ageClients2HYrToolStripMenuItem_Click); // // ageClients3HYrToolStripMenuItem // this.ageClients3HYrToolStripMenuItem.Name = "ageClients3HYrToolStripMenuItem"; this.ageClients3HYrToolStripMenuItem.Size = new System.Drawing.Size(170, 22); this.ageClients3HYrToolStripMenuItem.Tag = "3"; this.ageClients3HYrToolStripMenuItem.Text = "Age Clients 3 H-Yr"; this.ageClients3HYrToolStripMenuItem.Click += new System.EventHandler(this.ageClients3HYrToolStripMenuItem_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.aboutToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.helpToolStripMenuItem.Text = "Help"; // // aboutToolStripMenuItem // this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; this.aboutToolStripMenuItem.Size = new System.Drawing.Size(180, 22); this.aboutToolStripMenuItem.Text = "About"; this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click); // // button1 // this.button1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button1.Location = new System.Drawing.Point(22, 57); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(167, 61); this.button1.TabIndex = 1; this.button1.Text = "Initial Year"; this.button1.UseVisualStyleBackColor = false; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(128))))); this.button2.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button2.Location = new System.Drawing.Point(22, 153); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(167, 61); this.button2.TabIndex = 2; this.button2.Text = "Begin 2nd Year"; this.button2.UseVisualStyleBackColor = false; this.button2.Click += new System.EventHandler(this.button2_Click); // // button3 // this.button3.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0))))); this.button3.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button3.Location = new System.Drawing.Point(22, 251); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(167, 61); this.button3.TabIndex = 3; this.button3.Text = "Process 3rd DataSet"; this.button3.UseVisualStyleBackColor = false; this.button3.Click += new System.EventHandler(this.button3_Click); // // button4 // this.button4.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(255))))); this.button4.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button4.Location = new System.Drawing.Point(22, 352); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(167, 61); this.button4.TabIndex = 4; this.button4.Text = "Display All Data"; this.button4.UseVisualStyleBackColor = false; this.button4.Click += new System.EventHandler(this.button4_Click); // // listBox1 // this.listBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.listBox1.ColumnWidth = 1; this.listBox1.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.listBox1.FormattingEnabled = true; this.listBox1.ItemHeight = 19; this.listBox1.Location = new System.Drawing.Point(264, 49); this.listBox1.Name = "listBox1"; this.listBox1.Size = new System.Drawing.Size(550, 422); this.listBox1.TabIndex = 5; // // btnNew // this.btnNew.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128))))); this.btnNew.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnNew.Location = new System.Drawing.Point(849, 57); this.btnNew.Name = "btnNew"; this.btnNew.Size = new System.Drawing.Size(167, 61); this.btnNew.TabIndex = 6; this.btnNew.Text = "New Patient"; this.btnNew.UseVisualStyleBackColor = false; this.btnNew.Click += new System.EventHandler(this.btnNew_Click); // // btnReturn // this.btnReturn.BackColor = System.Drawing.Color.Red; this.btnReturn.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnReturn.Location = new System.Drawing.Point(849, 352); this.btnReturn.Name = "btnReturn"; this.btnReturn.Size = new System.Drawing.Size(167, 61); this.btnReturn.TabIndex = 7; this.btnReturn.Text = "Patient Visit"; this.btnReturn.UseVisualStyleBackColor = false; this.btnReturn.Click += new System.EventHandler(this.btnReturn_Click); // // btnBrood // this.btnBrood.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))); this.btnBrood.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnBrood.Location = new System.Drawing.Point(849, 164); this.btnBrood.Name = "btnBrood"; this.btnBrood.Size = new System.Drawing.Size(167, 61); this.btnBrood.TabIndex = 8; this.btnBrood.Text = "New Brood"; this.btnBrood.UseVisualStyleBackColor = false; this.btnBrood.Click += new System.EventHandler(this.btnBrood_Click); // // btnLookUp // this.btnLookUp.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); this.btnLookUp.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnLookUp.Location = new System.Drawing.Point(849, 251); this.btnLookUp.Name = "btnLookUp"; this.btnLookUp.Size = new System.Drawing.Size(167, 61); this.btnLookUp.TabIndex = 9; this.btnLookUp.Text = "Find Patient"; this.btnLookUp.UseVisualStyleBackColor = false; this.btnLookUp.Click += new System.EventHandler(this.btnLookUp_Click); // // txtBox1 // this.txtBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtBox1.Location = new System.Drawing.Point(463, 499); this.txtBox1.Name = "txtBox1"; this.txtBox1.Size = new System.Drawing.Size(302, 29); this.txtBox1.TabIndex = 10; // // lblPrompt // this.lblPrompt.AutoSize = true; this.lblPrompt.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblPrompt.Location = new System.Drawing.Point(336, 504); this.lblPrompt.Name = "lblPrompt"; this.lblPrompt.Size = new System.Drawing.Size(121, 24); this.lblPrompt.TabIndex = 11; this.lblPrompt.Text = "Data Input -->"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.ClientSize = new System.Drawing.Size(1024, 608); this.Controls.Add(this.lblPrompt); this.Controls.Add(this.txtBox1); this.Controls.Add(this.btnLookUp); this.Controls.Add(this.btnBrood); this.Controls.Add(this.btnReturn); this.Controls.Add(this.btnNew); this.Controls.Add(this.listBox1); this.Controls.Add(this.button4); this.Controls.Add(this.button3); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.menuStrip1); this.MainMenuStrip = this.menuStrip1; this.Name = "Form1"; this.Text = "Doing Animals"; this.Load += new System.EventHandler(this.Form1_Load); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem ageClients1HYrToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem ageClients2HYrToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem ageClients3HYrToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button4; private System.Windows.Forms.ListBox listBox1; private System.Windows.Forms.Button btnNew; private System.Windows.Forms.Button btnReturn; private System.Windows.Forms.Button btnBrood; private System.Windows.Forms.Button btnLookUp; private System.Windows.Forms.TextBox txtBox1; private System.Windows.Forms.Label lblPrompt; } }
55.667742
172
0.618705
[ "MIT" ]
abhatia25/Computer-Programming-2
Honors Project/VetOffice_Plus/VetOffice/Form1.Designer.cs
17,259
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Threading.Tasks; namespace Microsoft.Fx.Portability.ObjectModel { public interface IStorage { Task<bool> SaveToBlobAsync(AnalyzeRequest analyzeRequest, string submissionId); Task<AnalyzeRequest> RetrieveRequestAsync(string uniqueId); Task<IEnumerable<string>> RetrieveSubmissionIdsAsync(); Task AddJobToQueueAsync(string submissionId); IEnumerable<ProjectSubmission> GetProjectSubmissions(); } }
29.681818
101
0.754977
[ "MIT" ]
AArnott/dotnet-apiport
src/lib/Microsoft.Fx.Portability/ObjectModel/IStorage.cs
655
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: IEntityRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The interface IUserExperienceAnalyticsBatteryHealthRuntimeDetailsRequestBuilder. /// </summary> public partial interface IUserExperienceAnalyticsBatteryHealthRuntimeDetailsRequestBuilder : IEntityRequestBuilder { /// <summary> /// Builds the request. /// </summary> /// <returns>The built request.</returns> new IUserExperienceAnalyticsBatteryHealthRuntimeDetailsRequest Request(); /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> new IUserExperienceAnalyticsBatteryHealthRuntimeDetailsRequest Request(IEnumerable<Option> options); } }
38.25
153
0.612927
[ "MIT" ]
ScriptBox99/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IUserExperienceAnalyticsBatteryHealthRuntimeDetailsRequestBuilder.cs
1,377
C#
// Copyright (c) 2021 .NET Foundation and Contributors. All rights reserved. // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for full license information. using System; using System.Collections.Generic; namespace Akavache { /// <summary> /// A interface that represents a mixin for providing HTTP functionality. /// </summary> public interface IAkavacheHttpMixin { /// <summary> /// Gets a observable for a download. /// </summary> /// <param name="blobCache">The blob cache where to get the value from if available.</param> /// <param name="url">The url where to get the resource if not available in the cache.</param> /// <param name="headers">The headers to use in the HTTP action.</param> /// <param name="fetchAlways">If we should just fetch and not bother checking the cache first.</param> /// <param name="absoluteExpiration">A optional expiration date time.</param> /// <returns>A observable that signals when there is byte data.</returns> IObservable<byte[]> DownloadUrl(IBlobCache blobCache, string url, IDictionary<string, string>? headers = null, bool fetchAlways = false, DateTimeOffset? absoluteExpiration = null); /// <summary> /// Gets a observable for a download. /// </summary> /// <param name="blobCache">The blob cache where to get the value from if available.</param> /// <param name="url">The url where to get the resource if not available in the cache.</param> /// <param name="headers">The headers to use in the HTTP action.</param> /// <param name="fetchAlways">If we should just fetch and not bother checking the cache first.</param> /// <param name="absoluteExpiration">A optional expiration date time.</param> /// <returns>A observable that signals when there is byte data.</returns> IObservable<byte[]> DownloadUrl(IBlobCache blobCache, Uri url, IDictionary<string, string>? headers = null, bool fetchAlways = false, DateTimeOffset? absoluteExpiration = null); /// <summary> /// Gets a observable for a download. /// </summary> /// <param name="blobCache">The blob cache where to get the value from if available.</param> /// <param name="key">The key to use for the download cache entry.</param> /// <param name="url">The url where to get the resource if not available in the cache.</param> /// <param name="headers">The headers to use in the HTTP action.</param> /// <param name="fetchAlways">If we should just fetch and not bother checking the cache first.</param> /// <param name="absoluteExpiration">A optional expiration date time.</param> /// <returns>A observable that signals when there is byte data.</returns> IObservable<byte[]> DownloadUrl(IBlobCache blobCache, string key, string url, IDictionary<string, string>? headers = null, bool fetchAlways = false, DateTimeOffset? absoluteExpiration = null); /// <summary> /// Gets a observable for a download. /// </summary> /// <param name="blobCache">The blob cache where to get the value from if available.</param> /// <param name="key">The key to use for the download cache entry.</param> /// <param name="url">The url where to get the resource if not available in the cache.</param> /// <param name="headers">The headers to use in the HTTP action.</param> /// <param name="fetchAlways">If we should just fetch and not bother checking the cache first.</param> /// <param name="absoluteExpiration">A optional expiration date time.</param> /// <returns>A observable that signals when there is byte data.</returns> IObservable<byte[]> DownloadUrl(IBlobCache blobCache, string key, Uri url, IDictionary<string, string>? headers = null, bool fetchAlways = false, DateTimeOffset? absoluteExpiration = null); } }
64.952381
200
0.672776
[ "MIT" ]
DennisWelu/Akavache
src/Akavache.Core/IAkavacheHttpMixin.cs
4,094
C#
using UnityEngine; using UnityEngine.UI; using System.Collections; public class LeftButton_PVP : MonoBehaviour { public Scrollbar bar; private float maxMove; private float final; public GameObject movie1; public GameObject movie2; public GameObject movie3; // Use this for initialization void Start () { maxMove = 0.005f; } public void OnClick () { if (bar.value >= 0.49f && bar.value <= 0.51f) { GameObject.Find ("Arena_PVP").GetComponent<Arena_PVP> ().CmdLBClick (0f); } else if (bar.value >= 0.99f && bar.value <= 1.01f) { GameObject.Find ("Arena_PVP").GetComponent<Arena_PVP> ().CmdLBClick (0.5f); } //if (GetComponentInParent<Canvas_PVP> ().isLocalPlayer) IsClick(); } public void IsClick (float V) { final = V; InvokeRepeating ("smoothMove", 0.0f, 0.01f); } private void smoothMove () { if (bar.value > final) { /*Debug.Log (bar.value); Debug.Log (final);*/ bar.value -= maxMove; } else { Debug.Log (final); bar.value = final; if (bar.value == 0f) { movie2.GetComponent<movie_PVP> ().movieSource.Stop (); movie2.GetComponent<movie_PVP> ().GetComponent<AudioSource> ().Stop (); movie1.GetComponent<movie_PVP> ().movieSource.Play (); movie1.GetComponent<movie_PVP> ().GetComponent<AudioSource> ().Play (); } else if (bar.value == 0.5f) { movie3.GetComponent<movie_PVP> ().movieSource.Stop (); movie3.GetComponent<movie_PVP> ().GetComponent<AudioSource> ().Stop (); movie2.GetComponent<movie_PVP> ().movieSource.Play (); movie2.GetComponent<movie_PVP> ().GetComponent<AudioSource> ().Play (); } CancelInvoke (); } } }
23.884058
78
0.663228
[ "MIT" ]
garykillyou/Voice-Fight
Assets/Scripts/ArenaChoose_PVP/LeftButton_PVP.cs
1,650
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.IO; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Http2Cat; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Net.Http.Headers; using Xunit; namespace Microsoft.AspNetCore.Server.HttpSys.FunctionalTests { public class Http2Tests { [ConditionalFact(Skip = "https://github.com/aspnet/AspNetCore/issues/17420")] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10, SkipReason = "Http2 requires Win10")] [MaximumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_19H1, SkipReason = "This is last version without GoAway support")] public async Task ConnectionClose_NoOSSupport_NoGoAway() { using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext => { httpContext.Response.Headers[HeaderNames.Connection] = "close"; return Task.FromResult(0); }); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => { await h2Connection.InitializeConnectionAsync(); h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1."); await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true); await h2Connection.ReceiveHeadersAsync(1, endStream: true, decodedHeaders => { // HTTP/2 filters out the connection header Assert.False(decodedHeaders.ContainsKey(HeaderNames.Connection)); Assert.Equal("200", decodedHeaders[HeaderNames.Status]); }); // Send and receive a second request to ensure there is no GoAway frame on the wire yet. await h2Connection.StartStreamAsync(3, Http2Utilities.BrowserRequestHeaders, endStream: true); await h2Connection.ReceiveHeadersAsync(3, endStream: true, decodedHeaders => { // HTTP/2 filters out the connection header Assert.False(decodedHeaders.ContainsKey(HeaderNames.Connection)); Assert.Equal("200", decodedHeaders[HeaderNames.Status]); }); await h2Connection.StopConnectionAsync(expectedLastStreamId: 1, ignoreNonGoAwayFrames: false); h2Connection.Logger.LogInformation("Connection stopped."); }) .Build().RunAsync(); } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_19H2, SkipReason = "GoAway support was added in Win10_19H2.")] public async Task ConnectionClose_OSSupport_SendsGoAway() { using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext => { httpContext.Response.Headers[HeaderNames.Connection] = "close"; return Task.FromResult(0); }); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => { await h2Connection.InitializeConnectionAsync(); h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1."); await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true); var goAwayFrame = await h2Connection.ReceiveFrameAsync(); h2Connection.VerifyGoAway(goAwayFrame, int.MaxValue, Http2ErrorCode.NO_ERROR); await h2Connection.ReceiveHeadersAsync(1, decodedHeaders => { // HTTP/2 filters out the connection header Assert.False(decodedHeaders.ContainsKey(HeaderNames.Connection)); Assert.Equal("200", decodedHeaders[HeaderNames.Status]); }); var dataFrame = await h2Connection.ReceiveFrameAsync(); Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0); // Http.Sys doesn't send a final GoAway unless we ignore the first one and send 200 additional streams. h2Connection.Logger.LogInformation("Connection stopped."); }) .Build().RunAsync(); } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_19H2, SkipReason = "GoAway support was added in Win10_19H2.")] public async Task ConnectionClose_AdditionalRequests_ReceivesSecondGoAway() { using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext => { httpContext.Response.Headers[HeaderNames.Connection] = "close"; return Task.FromResult(0); }); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => { await h2Connection.InitializeConnectionAsync(); h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1."); var streamId = 1; await h2Connection.StartStreamAsync(streamId, Http2Utilities.BrowserRequestHeaders, endStream: true); var goAwayFrame = await h2Connection.ReceiveFrameAsync(); h2Connection.VerifyGoAway(goAwayFrame, int.MaxValue, Http2ErrorCode.NO_ERROR); await h2Connection.ReceiveHeadersAsync(streamId, decodedHeaders => { // HTTP/2 filters out the connection header Assert.False(decodedHeaders.ContainsKey(HeaderNames.Connection)); Assert.Equal("200", decodedHeaders[HeaderNames.Status]); }); var dataFrame = await h2Connection.ReceiveFrameAsync(); Http2Utilities.VerifyDataFrame(dataFrame, streamId, endOfStream: true, length: 0); // Http.Sys doesn't send a final GoAway unless we ignore the first one and send 200 additional streams. for (var i = 1; i < 200; i++) { streamId = 1 + (i * 2); // Odds. await h2Connection.StartStreamAsync(streamId, Http2Utilities.BrowserRequestHeaders, endStream: true); await h2Connection.ReceiveHeadersAsync(streamId, decodedHeaders => { // HTTP/2 filters out the connection header Assert.False(decodedHeaders.ContainsKey(HeaderNames.Connection)); Assert.Equal("200", decodedHeaders[HeaderNames.Status]); }); dataFrame = await h2Connection.ReceiveFrameAsync(); Http2Utilities.VerifyDataFrame(dataFrame, streamId, endOfStream: true, length: 0); } streamId = 1 + (200 * 2); // Odds. await h2Connection.StartStreamAsync(streamId, Http2Utilities.BrowserRequestHeaders, endStream: true); // Final GoAway goAwayFrame = await h2Connection.ReceiveFrameAsync(); h2Connection.VerifyGoAway(goAwayFrame, streamId, Http2ErrorCode.NO_ERROR); // Normal response await h2Connection.ReceiveHeadersAsync(streamId, decodedHeaders => { // HTTP/2 filters out the connection header Assert.False(decodedHeaders.ContainsKey(HeaderNames.Connection)); Assert.Equal("200", decodedHeaders[HeaderNames.Status]); }); dataFrame = await h2Connection.ReceiveFrameAsync(); Http2Utilities.VerifyDataFrame(dataFrame, streamId, endOfStream: true, length: 0); h2Connection.Logger.LogInformation("Connection stopped."); }) .Build().RunAsync(); } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10, SkipReason = "Http2 requires Win10")] public async Task AppException_BeforeHeaders_500() { using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext => { throw new Exception("Application exception"); }); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => { await h2Connection.InitializeConnectionAsync(); h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1."); await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true); await h2Connection.ReceiveHeadersAsync(1, decodedHeaders => { Assert.Equal("500", decodedHeaders[HeaderNames.Status]); }); var dataFrame = await h2Connection.ReceiveFrameAsync(); Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0); h2Connection.Logger.LogInformation("Connection stopped."); }) .Build().RunAsync(); } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10, SkipReason = "Http2 requires Win10")] [MaximumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_20H1, SkipReason = "This is last version without custom Reset support")] public async Task AppException_AfterHeaders_PriorOSVersions_ResetCancel() { using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext => { await httpContext.Response.Body.FlushAsync(); throw new Exception("Application exception"); }); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => { await h2Connection.InitializeConnectionAsync(); h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1."); await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true); await h2Connection.ReceiveHeadersAsync(1, decodedHeaders => { Assert.Equal("200", decodedHeaders[HeaderNames.Status]); }); var resetFrame = await h2Connection.ReceiveFrameAsync(); Http2Utilities.VerifyResetFrame(resetFrame, expectedStreamId: 1, Http2ErrorCode.CANCEL); h2Connection.Logger.LogInformation("Connection stopped."); }) .Build().RunAsync(); } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, "10.0.19529", SkipReason = "Custom Reset support was added in Win10_20H2.")] public async Task AppException_AfterHeaders_ResetInternalError() { using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext => { await httpContext.Response.Body.FlushAsync(); throw new Exception("Application exception"); }); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => { await h2Connection.InitializeConnectionAsync(); h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1."); await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true); await h2Connection.ReceiveHeadersAsync(1, decodedHeaders => { Assert.Equal("200", decodedHeaders[HeaderNames.Status]); }); var resetFrame = await h2Connection.ReceiveFrameAsync(); Http2Utilities.VerifyResetFrame(resetFrame, expectedStreamId: 1, Http2ErrorCode.INTERNAL_ERROR); h2Connection.Logger.LogInformation("Connection stopped."); }) .Build().RunAsync(); } [ConditionalFact] public async Task Reset_Http1_NotSupported() { using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext => { Assert.Equal("HTTP/1.1", httpContext.Request.Protocol); var feature = httpContext.Features.Get<IHttpResetFeature>(); Assert.Null(feature); return httpContext.Response.WriteAsync("Hello World"); }); var handler = new HttpClientHandler(); handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; using HttpClient client = new HttpClient(handler); client.DefaultRequestVersion = HttpVersion.Version11; var response = await client.GetStringAsync(address); Assert.Equal("Hello World", response); } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10, SkipReason = "Http2 requires Win10")] [MaximumOSVersion(OperatingSystems.Windows, WindowsVersions.Win10_20H1, SkipReason = "This is last version without Reset support")] public async Task Reset_PriorOSVersions_NotSupported() { using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext => { Assert.Equal("HTTP/2", httpContext.Request.Protocol); var feature = httpContext.Features.Get<IHttpResetFeature>(); Assert.Null(feature); return httpContext.Response.WriteAsync("Hello World"); }); var handler = new HttpClientHandler(); handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; using HttpClient client = new HttpClient(handler); client.DefaultRequestVersion = HttpVersion.Version20; var response = await client.GetStringAsync(address); Assert.Equal("Hello World", response); } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, "10.0.19529", SkipReason = "Reset support was added in Win10_20H2.")] public async Task Reset_BeforeResponse_Resets() { var appResult = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); using var server = Utilities.CreateDynamicHttpsServer(out var address, httpContext => { try { Assert.Equal("HTTP/2", httpContext.Request.Protocol); var feature = httpContext.Features.Get<IHttpResetFeature>(); Assert.NotNull(feature); feature.Reset(1111); // Custom appResult.SetResult(0); } catch (Exception ex) { appResult.SetException(ex); } return Task.FromResult(0); }); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => { await h2Connection.InitializeConnectionAsync(); h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1."); await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true); var resetFrame = await h2Connection.ReceiveFrameAsync(); Http2Utilities.VerifyResetFrame(resetFrame, expectedStreamId: 1, expectedErrorCode: (Http2ErrorCode)1111); // Any app errors? Assert.Equal(0, await appResult.Task.DefaultTimeout()); h2Connection.Logger.LogInformation("Connection stopped."); }) .Build().RunAsync(); } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, "10.0.19529", SkipReason = "Reset support was added in Win10_20H2.")] public async Task Reset_AfterResponseHeaders_Resets() { var appResult = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext => { try { Assert.Equal("HTTP/2", httpContext.Request.Protocol); var feature = httpContext.Features.Get<IHttpResetFeature>(); Assert.NotNull(feature); await httpContext.Response.Body.FlushAsync(); feature.Reset(1111); // Custom appResult.SetResult(0); } catch (Exception ex) { appResult.SetException(ex); } }); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => { await h2Connection.InitializeConnectionAsync(); h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1."); await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true); // Any app errors? Assert.Equal(0, await appResult.Task.DefaultTimeout()); await h2Connection.ReceiveHeadersAsync(1, decodedHeaders => { Assert.Equal("200", decodedHeaders[HeaderNames.Status]); }); var resetFrame = await h2Connection.ReceiveFrameAsync(); Http2Utilities.VerifyResetFrame(resetFrame, expectedStreamId: 1, expectedErrorCode: (Http2ErrorCode)1111); h2Connection.Logger.LogInformation("Connection stopped."); }) .Build().RunAsync(); } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, "10.0.19529", SkipReason = "Reset support was added in Win10_20H2.")] public async Task Reset_DurringResponseBody_Resets() { var appResult = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext => { try { Assert.Equal("HTTP/2", httpContext.Request.Protocol); var feature = httpContext.Features.Get<IHttpResetFeature>(); Assert.NotNull(feature); await httpContext.Response.WriteAsync("Hello World"); feature.Reset(1111); // Custom appResult.SetResult(0); } catch (Exception ex) { appResult.SetException(ex); } }); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => { await h2Connection.InitializeConnectionAsync(); h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1."); await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true); // Any app errors? Assert.Equal(0, await appResult.Task.DefaultTimeout()); await h2Connection.ReceiveHeadersAsync(1, decodedHeaders => { Assert.Equal("200", decodedHeaders[HeaderNames.Status]); }); var dataFrame = await h2Connection.ReceiveFrameAsync(); Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: false, length: 11); var resetFrame = await h2Connection.ReceiveFrameAsync(); Http2Utilities.VerifyResetFrame(resetFrame, expectedStreamId: 1, expectedErrorCode: (Http2ErrorCode)1111); h2Connection.Logger.LogInformation("Connection stopped."); }) .Build().RunAsync(); } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, "10.0.19529", SkipReason = "Reset support was added in Win10_20H2.")] public async Task Reset_AfterCompleteAsync_NoReset() { var appResult = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext => { try { Assert.Equal("HTTP/2", httpContext.Request.Protocol); var feature = httpContext.Features.Get<IHttpResetFeature>(); Assert.NotNull(feature); await httpContext.Response.WriteAsync("Hello World"); await httpContext.Response.CompleteAsync(); // The request and response are fully complete, the reset doesn't get sent. feature.Reset(1111); appResult.SetResult(0); } catch (Exception ex) { appResult.SetException(ex); } }); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => { await h2Connection.InitializeConnectionAsync(); h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1."); await h2Connection.StartStreamAsync(1, Http2Utilities.BrowserRequestHeaders, endStream: true); // Any app errors? Assert.Equal(0, await appResult.Task.DefaultTimeout()); await h2Connection.ReceiveHeadersAsync(1, decodedHeaders => { Assert.Equal("200", decodedHeaders[HeaderNames.Status]); }); var dataFrame = await h2Connection.ReceiveFrameAsync(); Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: false, length: 11); dataFrame = await h2Connection.ReceiveFrameAsync(); Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0); h2Connection.Logger.LogInformation("Connection stopped."); }) .Build().RunAsync(); } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, "10.0.19529", SkipReason = "Reset support was added in Win10_20H2.")] public async Task Reset_BeforeRequestBody_Resets() { var appResult = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext => { try { Assert.Equal("HTTP/2", httpContext.Request.Protocol); var feature = httpContext.Features.Get<IHttpResetFeature>(); Assert.NotNull(feature); var readTask = httpContext.Request.Body.ReadAsync(new byte[10], 0, 10); feature.Reset(1111); await Assert.ThrowsAsync<IOException>(() => readTask); appResult.SetResult(0); } catch (Exception ex) { appResult.SetException(ex); } }); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => { await h2Connection.InitializeConnectionAsync(); h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1."); await h2Connection.StartStreamAsync(1, Http2Utilities.PostRequestHeaders, endStream: false); // Any app errors? Assert.Equal(0, await appResult.Task.DefaultTimeout()); var resetFrame = await h2Connection.ReceiveFrameAsync(); Http2Utilities.VerifyResetFrame(resetFrame, expectedStreamId: 1, expectedErrorCode: (Http2ErrorCode)1111); h2Connection.Logger.LogInformation("Connection stopped."); }) .Build().RunAsync(); } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, "10.0.19529", SkipReason = "Reset support was added in Win10_20H2.")] public async Task Reset_DurringRequestBody_Resets() { var appResult = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext => { try { Assert.Equal("HTTP/2", httpContext.Request.Protocol); var feature = httpContext.Features.Get<IHttpResetFeature>(); Assert.NotNull(feature); var read = await httpContext.Request.Body.ReadAsync(new byte[10], 0, 10); Assert.Equal(10, read); var readTask = httpContext.Request.Body.ReadAsync(new byte[10], 0, 10); feature.Reset(1111); await Assert.ThrowsAsync<IOException>(() => readTask); appResult.SetResult(0); } catch (Exception ex) { appResult.SetException(ex); } }); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => { await h2Connection.InitializeConnectionAsync(); h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1."); await h2Connection.StartStreamAsync(1, Http2Utilities.PostRequestHeaders, endStream: false); await h2Connection.SendDataAsync(1, new byte[10], endStream: false); // Any app errors? Assert.Equal(0, await appResult.Task.DefaultTimeout()); var resetFrame = await h2Connection.ReceiveFrameAsync(); Http2Utilities.VerifyResetFrame(resetFrame, expectedStreamId: 1, expectedErrorCode: (Http2ErrorCode)1111); h2Connection.Logger.LogInformation("Connection stopped."); }) .Build().RunAsync(); } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, "10.0.19529", SkipReason = "Reset support was added in Win10_20H2.")] public async Task Reset_CompleteAsyncDurringRequestBody_Resets() { var appResult = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); using var server = Utilities.CreateDynamicHttpsServer(out var address, async httpContext => { try { Assert.Equal("HTTP/2", httpContext.Request.Protocol); var feature = httpContext.Features.Get<IHttpResetFeature>(); Assert.NotNull(feature); var read = await httpContext.Request.Body.ReadAsync(new byte[10], 0, 10); Assert.Equal(10, read); var readTask = httpContext.Request.Body.ReadAsync(new byte[10], 0, 10); await httpContext.Response.CompleteAsync(); feature.Reset((int)Http2ErrorCode.NO_ERROR); // GRPC does this await Assert.ThrowsAsync<IOException>(() => readTask); appResult.SetResult(0); } catch (Exception ex) { appResult.SetException(ex); } }); await new HostBuilder() .UseHttp2Cat(address, async h2Connection => { await h2Connection.InitializeConnectionAsync(); h2Connection.Logger.LogInformation("Initialized http2 connection. Starting stream 1."); await h2Connection.StartStreamAsync(1, Http2Utilities.PostRequestHeaders, endStream: false); await h2Connection.SendDataAsync(1, new byte[10], endStream: false); // Any app errors? Assert.Equal(0, await appResult.Task.DefaultTimeout()); await h2Connection.ReceiveHeadersAsync(1, decodedHeaders => { Assert.Equal("200", decodedHeaders[HeaderNames.Status]); }); var dataFrame = await h2Connection.ReceiveFrameAsync(); Http2Utilities.VerifyDataFrame(dataFrame, 1, endOfStream: true, length: 0); var resetFrame = await h2Connection.ReceiveFrameAsync(); Http2Utilities.VerifyResetFrame(resetFrame, expectedStreamId: 1, expectedErrorCode: Http2ErrorCode.NO_ERROR); h2Connection.Logger.LogInformation("Connection stopped."); }) .Build().RunAsync(); } } }
46.253776
146
0.581385
[ "Apache-2.0" ]
C13790016DGFE/AspNetCore
src/Servers/HttpSys/test/FunctionalTests/Http2Tests.cs
30,620
C#
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Algo File: EntityCache.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo { using System; using System.Collections.Generic; using System.Linq; using Ecng.Common; using Ecng.Collections; using MoreLinq; using StockSharp.BusinessEntities; using StockSharp.Logging; using StockSharp.Messages; using StockSharp.Localization; class EntityCache { private static readonly MemoryStatisticsValue<Trade> _tradeStat = new MemoryStatisticsValue<Trade>(LocalizedStrings.Ticks); private sealed class OrderInfo { private bool _raiseNewOrder; public OrderInfo(Order order, bool raiseNewOrder = true) { if (order == null) throw new ArgumentNullException(nameof(order)); Order = order; _raiseNewOrder = raiseNewOrder; } public Order Order { get; } public Tuple<Order, bool, bool> ApplyChanges(ExecutionMessage message, bool isCancel) { var order = Order; Tuple<Order, bool, bool> retVal; if (order.State == OrderStates.Done) { // данные о заявке могут приходить из маркет-дата и транзакционного адаптеров retVal = Tuple.Create(order, _raiseNewOrder, false); _raiseNewOrder = false; return retVal; //throw new InvalidOperationException("Изменение заявки в состоянии Done невозможно."); } else if (order.State == OrderStates.Failed) { // some adapters can resend order's info //throw new InvalidOperationException(); return null; } var isPending = order.State == OrderStates.Pending; if (message.OrderId != null) order.Id = message.OrderId.Value; if (!message.OrderStringId.IsEmpty()) order.StringId = message.OrderStringId; if (!message.OrderBoardId.IsEmpty()) order.BoardId = message.OrderBoardId; //// некоторые коннекторы не транслируют при отмене отмененный объем //// esper. при перерегистрации заявок необходимо обновлять баланс //if (message.Balance > 0 || !isCancelled || isReRegisterCancelled) //{ // // BTCE коннектор не транслирует баланс заявки // if (!(message.OrderState == OrderStates.Active && message.Balance == 0)) // order.Balance = message.Balance; //} if (message.Balance != null) order.Balance = message.Balance.Value; // IB коннектор не транслирует состояние заявки в одном из своих сообщений if (message.OrderState != null) order.State = order.State.CheckModification(message.OrderState.Value); if (order.Time == DateTimeOffset.MinValue) order.Time = message.ServerTime; // для новых заявок используем серверное время, // т.к. заявка получена первый раз и не менялась // ServerTime для заявки - это время регистрации order.LastChangeTime = _raiseNewOrder ? message.ServerTime : message.LocalTime; order.LocalTime = message.LocalTime; //нулевой объем может быть при перерегистрации if (order.Volume == 0 && message.OrderVolume != null) order.Volume = message.OrderVolume.Value; if (message.Commission != null) order.Commission = message.Commission; if (message.TimeInForce != null) order.TimeInForce = message.TimeInForce.Value; if (message.Latency != null) { if (isCancel) order.LatencyCancellation = message.Latency.Value; else if (isPending) { if (order.State != OrderStates.Pending) order.LatencyRegistration = message.Latency.Value; } } message.CopyExtensionInfo(order); retVal = Tuple.Create(order, _raiseNewOrder, true); _raiseNewOrder = false; return retVal; } } private class SecurityData { public readonly CachedSynchronizedDictionary<Tuple<long, long>, MyTrade> MyTrades = new CachedSynchronizedDictionary<Tuple<long, long>, MyTrade>(); public readonly CachedSynchronizedDictionary<Tuple<long, bool, bool>, OrderInfo> Orders = new CachedSynchronizedDictionary<Tuple<long, bool, bool>, OrderInfo>(); public readonly SynchronizedDictionary<long, Trade> TradesById = new SynchronizedDictionary<long, Trade>(); public readonly SynchronizedDictionary<string, Trade> TradesByStringId = new SynchronizedDictionary<string, Trade>(StringComparer.InvariantCultureIgnoreCase); public readonly SynchronizedList<Trade> Trades = new SynchronizedList<Trade>(); public readonly SynchronizedDictionary<long, Order> OrdersById = new SynchronizedDictionary<long, Order>(); public readonly SynchronizedDictionary<string, Order> OrdersByStringId = new SynchronizedDictionary<string, Order>(StringComparer.InvariantCultureIgnoreCase); } private readonly SynchronizedDictionary<Security, SecurityData> _securityData = new SynchronizedDictionary<Security, SecurityData>(); private SecurityData GetData(Security security) { return _securityData.SafeAdd(security); } private readonly CachedSynchronizedList<Trade> _trades = new CachedSynchronizedList<Trade>(); public IEnumerable<Trade> Trades { get { return _securityData.SyncGet(d => d.SelectMany(p => p.Value.Trades.SyncGet(t => t.ToArray()).Concat(p.Value.TradesById.SyncGet(t => t.Values.ToArray())).Concat(p.Value.TradesByStringId.SyncGet(t => t.Values.ToArray()))).ToArray()); } } private readonly SynchronizedDictionary<Tuple<long, bool>, Order> _allOrdersByTransactionId = new SynchronizedDictionary<Tuple<long, bool>, Order>(); private readonly SynchronizedDictionary<long, Order> _allOrdersById = new SynchronizedDictionary<long, Order>(); private readonly SynchronizedDictionary<string, Order> _allOrdersByStringId = new SynchronizedDictionary<string, Order>(StringComparer.InvariantCultureIgnoreCase); private readonly SynchronizedDictionary<string, News> _newsById = new SynchronizedDictionary<string, News>(StringComparer.InvariantCultureIgnoreCase); private readonly SynchronizedList<News> _newsWithoutId = new SynchronizedList<News>(); public IEnumerable<News> News { get { return _newsWithoutId.SyncGet(t => t.ToArray()).Concat(_newsById.SyncGet(t => t.Values.ToArray())).ToArray(); } } private int _tradesKeepCount = 100000; public int TradesKeepCount { get { return _tradesKeepCount; } set { if (_tradesKeepCount == value) return; if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.NegativeTickCountStorage); _tradesKeepCount = value; RecycleTrades(); } } private int _ordersKeepCount = 1000; public int OrdersKeepCount { get { return _ordersKeepCount; } set { if (_ordersKeepCount == value) return; if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.NegativeOrderCountStorage); _ordersKeepCount = value; RecycleOrders(); } } private void AddTrade(Trade trade) { if (TradesKeepCount == 0) return; _tradeStat.Add(trade); _trades.Add(trade); RecycleTrades(); } private void AddOrder(Order order) { if (order == null) throw new ArgumentNullException(nameof(order)); if (OrdersKeepCount > 0) _orders.Add(order); RecycleOrders(); } private readonly CachedSynchronizedDictionary<string, Portfolio> _portfolios = new CachedSynchronizedDictionary<string, Portfolio>(); private readonly HashSet<long> _orderStatusTransactions = new HashSet<long>(); private readonly HashSet<long> _massCancelationTransactions = new HashSet<long>(); private IEntityFactory _entityFactory = new EntityFactory(); public IEntityFactory EntityFactory { get { return _entityFactory; } set { if (value == null) throw new ArgumentNullException(nameof(value)); _entityFactory = value; } } private readonly CachedSynchronizedList<Order> _orders = new CachedSynchronizedList<Order>(); public IEnumerable<Order> Orders => _orders.Cache; private readonly CachedSynchronizedList<MyTrade> _myTrades = new CachedSynchronizedList<MyTrade>(); public IEnumerable<MyTrade> MyTrades => _myTrades.Cache; public virtual IEnumerable<Portfolio> Portfolios => _portfolios.CachedValues; private readonly CachedSynchronizedSet<ExchangeBoard> _exchangeBoards = new CachedSynchronizedSet<ExchangeBoard>(); public IEnumerable<ExchangeBoard> ExchangeBoards => _exchangeBoards.Cache; private readonly CachedSynchronizedDictionary<string, Security> _securities = new CachedSynchronizedDictionary<string, Security>(StringComparer.InvariantCultureIgnoreCase); public IEnumerable<Security> Securities => _securities.CachedValues; private readonly SynchronizedList<OrderFail> _orderRegisterFails = new SynchronizedList<OrderFail>(); public IEnumerable<OrderFail> OrderRegisterFails { get { return _orderRegisterFails.SyncGet(c => c.ToArray()); } } private readonly SynchronizedList<OrderFail> _orderCancelFails = new SynchronizedList<OrderFail>(); public IEnumerable<OrderFail> OrderCancelFails { get { return _orderCancelFails.SyncGet(c => c.ToArray()); } } private readonly CachedSynchronizedDictionary<Tuple<Portfolio, Security, string, string, TPlusLimits?>, Position> _positions = new CachedSynchronizedDictionary<Tuple<Portfolio, Security, string, string, TPlusLimits?>, Position>(); public IEnumerable<Position> Positions => _positions.CachedValues; public int SecurityCount => _securities.Count; public void Clear() { _securityData.Clear(); _allOrdersById.Clear(); _allOrdersByStringId.Clear(); _allOrdersByTransactionId.Clear(); _orders.Clear(); _newsById.Clear(); _newsWithoutId.Clear(); _myTrades.Clear(); _trades.Clear(); _tradeStat.Clear(true); _orderStatusTransactions.Clear(); _massCancelationTransactions.Clear(); _exchangeBoards.Clear(); _securities.Clear(); _orderCancelFails.Clear(); _orderRegisterFails.Clear(); _positions.Clear(); } public void AddOrderStatusTransactionId(long transactionId) { if (!_orderStatusTransactions.Add(transactionId)) throw new InvalidOperationException(); } public IEnumerable<Order> GetOrders(Security security, OrderStates state) { if (security == null) throw new ArgumentNullException(nameof(security)); return GetData(security).Orders.CachedValues.Select(info => info.Order).Filter(state); } public void AddMassCancelationId(long transactionId) { if (!_massCancelationTransactions.Add(transactionId)) throw new InvalidOperationException(); } public bool IsMassCancelation(long transactionId) => _massCancelationTransactions.Contains(transactionId); public void AddOrderByCancelationId(Order order, long transactionId) { AddOrderByTransactionId(order, transactionId, true); } public void AddOrderByRegistrationId(Order order) { AddOrder(order); AddOrderByTransactionId(order, order.TransactionId, false); } private void AddOrderByTransactionId(Order order, long transactionId, bool isCancel) { if (order == null) throw new ArgumentNullException(nameof(order)); GetData(order.Security).Orders.Add(CreateOrderKey(order.Type, transactionId, isCancel), new OrderInfo(order, !isCancel)); _allOrdersByTransactionId.Add(Tuple.Create(transactionId, isCancel), order); } private void UpdateOrderIds(Order order, SecurityData securityData) { // так как биржевые идентифиаторы могут повторяться, то переписываем старые заявки новыми как наиболее актуальными if (order.Id != null) { securityData.OrdersById[order.Id.Value] = order; _allOrdersById[order.Id.Value] = order; } if (!order.StringId.IsEmpty()) { securityData.OrdersByStringId[order.StringId] = order; _allOrdersByStringId[order.StringId] = order; } } public IEnumerable<Tuple<Order, bool, bool>> ProcessOrderMessage(Order order, Security security, ExecutionMessage message, long transactionId, out Tuple<Portfolio, bool, bool> pfInfo) { if (security == null) throw new ArgumentNullException(nameof(security)); if (message == null) throw new ArgumentNullException(nameof(message)); if (message.Error != null) throw new ArgumentException(LocalizedStrings.Str714Params.PutEx(message)); var securityData = GetData(security); if (transactionId == 0 && message.OrderId == null && message.OrderStringId.IsEmpty()) throw new ArgumentException(LocalizedStrings.Str719); pfInfo = null; var orders = securityData.Orders; if (transactionId == 0) { var info = orders.CachedValues.FirstOrDefault(i => { if (order != null) return i.Order == order; if (message.OrderId != null) return i.Order.Id == message.OrderId; else return i.Order.StringId.CompareIgnoreCase(message.OrderStringId); }); if (info == null) { return null; //throw new InvalidOperationException(LocalizedStrings.Str1156Params.Put(orderId.To<string>() ?? orderStringId)); } var orderInfo = info.ApplyChanges(message, false); UpdateOrderIds(info.Order, securityData); return new[] { orderInfo }; } else { var cancelKey = CreateOrderKey(message.OrderType, transactionId, true); var registerKey = CreateOrderKey(message.OrderType, transactionId, false); var cancelledInfo = orders.TryGetValue(cancelKey); var registetedInfo = orders.TryGetValue(registerKey); // проверяем не отмененная ли заявка пришла if (cancelledInfo != null) // && (cancelledOrder.Id == orderId || (!cancelledOrder.StringId.IsEmpty() && cancelledOrder.StringId.CompareIgnoreCase(orderStringId)))) { var cancellationOrder = cancelledInfo.Order; if (registetedInfo == null) { var i = cancelledInfo.ApplyChanges(message, true); UpdateOrderIds(cancellationOrder, securityData); return new[] { i }; } var retVal = new List<Tuple<Order, bool, bool>>(); var orderState = message.OrderState; if (orderState != null && cancellationOrder.State != OrderStates.Done && orderState != OrderStates.None && orderState != OrderStates.Pending) { cancellationOrder.State = cancellationOrder.State.CheckModification(OrderStates.Done); if (message.Latency != null) cancellationOrder.LatencyCancellation = message.Latency.Value; retVal.Add(Tuple.Create(cancellationOrder, false, true)); } var isCancelOrder = (message.OrderId != null && message.OrderId == cancellationOrder.Id) || (message.OrderStringId != null && message.OrderStringId == cancellationOrder.StringId) || (message.OrderBoardId != null && message.OrderBoardId == cancellationOrder.BoardId); var regOrder = registetedInfo.Order; if (!isCancelOrder) { var replacedInfo = registetedInfo.ApplyChanges(message, false); UpdateOrderIds(regOrder, securityData); retVal.Add(replacedInfo); } return retVal; } if (registetedInfo == null) { var o = EntityFactory.CreateOrder(security, message.OrderType, registerKey.Item1); if (o == null) throw new InvalidOperationException(LocalizedStrings.Str720Params.Put(registerKey.Item1)); o.Time = message.ServerTime; o.Price = message.OrderPrice; o.Volume = message.OrderVolume ?? 0; o.Direction = message.Side; o.Comment = message.Comment; o.ExpiryDate = message.ExpiryDate; o.Condition = message.Condition; o.UserOrderId = message.UserOrderId; o.ClientCode = message.ClientCode; o.BrokerCode = message.BrokerCode; if (message.PortfolioName.IsEmpty()) o.Portfolio = _portfolios.FirstOrDefault().Value; else { pfInfo = ProcessPortfolio(message.PortfolioName); o.Portfolio = ProcessPortfolio(message.PortfolioName).Item1; } if (o.ExtensionInfo == null) o.ExtensionInfo = new Dictionary<object, object>(); AddOrder(o); _allOrdersByTransactionId.Add(Tuple.Create(transactionId, false), o); registetedInfo = new OrderInfo(o); orders.Add(registerKey, registetedInfo); } var orderInfo = registetedInfo.ApplyChanges(message, false); if (orderInfo != null) { UpdateOrderIds(registetedInfo.Order, securityData); return new[] { orderInfo }; } else return Enumerable.Empty<Tuple<Order, bool, bool>>(); } } public IEnumerable<Tuple<OrderFail, bool>> ProcessOrderFailMessage(Order order, Security security, ExecutionMessage message) { if (security == null) throw new ArgumentNullException(nameof(security)); if (message == null) throw new ArgumentNullException(nameof(message)); var data = GetData(security); var orders = new List<Tuple<Order, bool>>(); if (message.OriginalTransactionId == 0) throw new ArgumentOutOfRangeException(nameof(message), message.OriginalTransactionId, LocalizedStrings.Str715); var orderType = message.OrderType; if (order == null) { var cancelledOrder = data.Orders.TryGetValue(CreateOrderKey(orderType, message.OriginalTransactionId, true))?.Order; if (cancelledOrder == null && orderType == null) { cancelledOrder = data.Orders.TryGetValue(CreateOrderKey(OrderTypes.Conditional, message.OriginalTransactionId, true))?.Order; if (cancelledOrder != null) orderType = OrderTypes.Conditional; } if (cancelledOrder != null /*&& order.Id == message.OrderId*/) orders.Add(Tuple.Create(cancelledOrder, true)); var registeredOrder = data.Orders.TryGetValue(CreateOrderKey(orderType, message.OriginalTransactionId, false))?.Order; if (registeredOrder == null && orderType == null) registeredOrder = data.Orders.TryGetValue(CreateOrderKey(OrderTypes.Conditional, message.OriginalTransactionId, false))?.Order; if (registeredOrder != null) orders.Add(Tuple.Create(registeredOrder, false)); if (cancelledOrder == null && registeredOrder == null) { if (!message.OrderStringId.IsEmpty()) { order = data.OrdersByStringId.TryGetValue(message.OrderStringId); if (order != null) { var pair = data.Orders.LastOrDefault(p => p.Value.Order == order); if (pair.Key != null) orders.Add(Tuple.Create(pair.Value.Order, pair.Key.Item3)); } } } } else { if (data.Orders.ContainsKey(CreateOrderKey(order.Type, message.OriginalTransactionId, true))) orders.Add(Tuple.Create(order, true)); var registeredOrder = data.Orders.TryGetValue(CreateOrderKey(order.Type, message.OriginalTransactionId, false))?.Order; if (registeredOrder != null) orders.Add(Tuple.Create(registeredOrder, false)); } if (orders.Count == 0) return Enumerable.Empty<Tuple<OrderFail, bool>>(); return orders.Select(t => { var o = t.Item1; var isCancelTransaction = t.Item2; o.LastChangeTime = message.ServerTime; o.LocalTime = message.LocalTime; if (message.OrderStatus != null) o.Status = message.OrderStatus; //для ошибок снятия не надо менять состояние заявки if (!isCancelTransaction) o.State = o.State.CheckModification(OrderStates.Failed); if (message.Commission != null) o.Commission = message.Commission; message.CopyExtensionInfo(o); var error = message.Error ?? new InvalidOperationException(isCancelTransaction ? LocalizedStrings.Str716 : LocalizedStrings.Str717); var fail = EntityFactory.CreateOrderFail(o, error); fail.ServerTime = message.ServerTime; fail.LocalTime = message.LocalTime; return Tuple.Create(fail, isCancelTransaction); }); } public Tuple<MyTrade, bool> ProcessMyTradeMessage(Order order, Security security, ExecutionMessage message, long transactionId) { if (security == null) throw new ArgumentNullException(nameof(security)); if (message == null) throw new ArgumentNullException(nameof(message)); var securityData = GetData(security); if (transactionId == 0 && message.OrderId == null && message.OrderStringId.IsEmpty()) throw new ArgumentOutOfRangeException(nameof(message), transactionId, LocalizedStrings.Str715); var myTrade = securityData.MyTrades.TryGetValue(Tuple.Create(transactionId, message.TradeId ?? 0)); if (myTrade != null) return Tuple.Create(myTrade, false); if (order == null) { order = GetOrder(security, transactionId, message.OrderId, message.OrderStringId); if (order == null) return null; } var trade = message.ToTrade(EntityFactory.CreateTrade(security, message.TradeId, message.TradeStringId)); var isNew = false; myTrade = securityData.MyTrades.SafeAdd(Tuple.Create(order.TransactionId, trade.Id), key => { isNew = true; var t = EntityFactory.CreateMyTrade(order, trade); if (t.ExtensionInfo == null) t.ExtensionInfo = new Dictionary<object, object>(); if (message.Commission != null) t.Commission = message.Commission; if (message.Slippage != null) t.Slippage = message.Slippage; if (message.PnL != null) t.PnL = message.PnL; if (message.Position != null) t.Position = message.Position; message.CopyExtensionInfo(t); _myTrades.Add(t); return t; }); return Tuple.Create(myTrade, isNew); } public Tuple<Trade, bool> ProcessTradeMessage(Security security, ExecutionMessage message) { if (security == null) throw new ArgumentNullException(nameof(security)); if (message == null) throw new ArgumentNullException(nameof(message)); var trade = GetTrade(security, message.TradeId, message.TradeStringId, (id, stringId) => { var t = message.ToTrade(EntityFactory.CreateTrade(security, id, stringId)); t.LocalTime = message.LocalTime; t.Time = message.ServerTime; message.CopyExtensionInfo(t); return t; }); return trade; } public Tuple<News, bool> ProcessNewsMessage(Security security, NewsMessage message) { if (message == null) throw new ArgumentNullException(nameof(message)); var isNew = false; News news; if (!message.Id.IsEmpty()) { news = _newsById.SafeAdd(message.Id, key => { isNew = true; var n = EntityFactory.CreateNews(); n.Id = key; return n; }); } else { isNew = true; news = EntityFactory.CreateNews(); _newsWithoutId.Add(news); } if (isNew) { news.ServerTime = message.ServerTime; news.LocalTime = message.LocalTime; } if (!message.Source.IsEmpty()) news.Source = message.Source; if (!message.Headline.IsEmpty()) news.Headline = message.Headline; if (security != null) news.Security = security; if (!message.Story.IsEmpty()) news.Story = message.Story; if (!message.BoardCode.IsEmpty()) news.Board = ExchangeBoard.GetOrCreateBoard(message.BoardCode); if (message.Url != null) news.Url = message.Url; message.CopyExtensionInfo(news); return Tuple.Create(news, isNew); } private static Tuple<long, bool, bool> CreateOrderKey(OrderTypes? type, long transactionId, bool isCancel) { if (transactionId <= 0) throw new ArgumentOutOfRangeException(nameof(transactionId), transactionId, LocalizedStrings.Str718); return Tuple.Create(transactionId, type == OrderTypes.Conditional, isCancel); } public Order GetOrder(Security security, long transactionId, long? orderId, string orderStringId, OrderTypes orderType = OrderTypes.Limit, bool isCancel = false) { if (security == null) throw new ArgumentNullException(nameof(security)); if (transactionId == 0 && orderId == null && orderStringId.IsEmpty()) throw new ArgumentException(LocalizedStrings.Str719); var data = GetData(security); Order order = null; if (transactionId != 0) order = data.Orders.TryGetValue(CreateOrderKey(orderType, transactionId, isCancel))?.Order; if (order != null) return order; if (orderId != null) order = data.OrdersById.TryGetValue(orderId.Value); if (order != null) return order; return orderStringId == null ? null : data.OrdersByStringId.TryGetValue(orderStringId); } public long GetTransactionId(long originalTransactionId) { // ExecMsg.OriginalTransactionId == OrderStatMsg.TransactionId when orders info requested by OrderStatMsg return _orderStatusTransactions.Contains(originalTransactionId) || IsMassCancelation(originalTransactionId) ? 0 : originalTransactionId; } public Order GetOrder(ExecutionMessage message, out long transactionId) { transactionId = message.TransactionId; if (transactionId == 0) transactionId = GetTransactionId(message.OriginalTransactionId); if (transactionId == 0) return null; return _allOrdersByTransactionId.TryGetValue(Tuple.Create(transactionId, true)) ?? _allOrdersByTransactionId.TryGetValue(Tuple.Create(transactionId, false)); } public Tuple<Trade, bool> GetTrade(Security security, long? id, string strId, Func<long?, string, Trade> createTrade) { if (security == null) throw new ArgumentNullException(nameof(security)); if (createTrade == null) throw new ArgumentNullException(nameof(createTrade)); var isNew = false; Trade trade; if (TradesKeepCount > 0) { var securityData = GetData(security); if (id != null) { trade = securityData.TradesById.SafeAdd(id.Value, k => { isNew = true; var t = createTrade(id.Value, strId); AddTrade(t); return t; }); } else if (!strId.IsEmpty()) { trade = securityData.TradesByStringId.SafeAdd(strId, k => { isNew = true; var t = createTrade(null, strId); AddTrade(t); return t; }); } else { isNew = true; trade = createTrade(null, null); AddTrade(trade); securityData.Trades.Add(trade); } } else { isNew = true; trade = createTrade(id, strId); } return Tuple.Create(trade, isNew); } public Tuple<Portfolio, bool, bool> ProcessPortfolio(string name, Func<Portfolio, bool> changePortfolio = null) { if (name.IsEmpty()) throw new ArgumentNullException(nameof(name)); bool isNew; var portfolio = _portfolios.SafeAdd(name, key => { var p = EntityFactory.CreatePortfolio(key); if (p == null) throw new InvalidOperationException(LocalizedStrings.Str1104Params.Put(name)); if (p.ExtensionInfo == null) p.ExtensionInfo = new Dictionary<object, object>(); return p; }, out isNew); var isChanged = false; if (changePortfolio != null) isChanged = changePortfolio(portfolio); if (isNew) return Tuple.Create(portfolio, true, false); if (changePortfolio != null && isChanged) return Tuple.Create(portfolio, false, true); return Tuple.Create(portfolio, false, false); } public Security GetSecurityById(string id) { return _securities.TryGetValue(id); } public Security TryAddSecurity(string id, Func<string, Tuple<string, ExchangeBoard>> idConvert, out bool isNew) { if (idConvert == null) throw new ArgumentNullException(nameof(idConvert)); return _securities.SafeAdd(id, key => { var s = EntityFactory.CreateSecurity(key); if (s == null) throw new InvalidOperationException(LocalizedStrings.Str1102Params.Put(key)); if (s.ExtensionInfo == null) s.ExtensionInfo = new Dictionary<object, object>(); var info = idConvert(key); if (s.Board == null) s.Board = info.Item2; if (s.Code.IsEmpty()) s.Code = info.Item1; if (s.Name.IsEmpty()) s.Name = info.Item1; if (s.Class.IsEmpty()) s.Class = info.Item2.Code; return s; }, out isNew); } public Security TryRemoveSecurity(string id) { lock (_securities.SyncRoot) { var security = _securities.TryGetValue(id); _securities.Remove(id); return security; } } public void TryAddBoard(ExchangeBoard board) { _exchangeBoards.TryAdd(board); } public void AddRegisterFail(OrderFail fail) { _orderRegisterFails.Add(fail); } public void AddCancelFail(OrderFail fail) { _orderCancelFails.Add(fail); } public Position TryAddPosition(Portfolio portfolio, Security security, string clientCode, string depoName, TPlusLimits? limitType, string description, out bool isNew) { isNew = false; Position position; lock (_positions.SyncRoot) { if (depoName == null) depoName = string.Empty; if (clientCode == null) clientCode = string.Empty; var key = Tuple.Create(portfolio, security, clientCode, depoName, limitType); if (!_positions.TryGetValue(key, out position)) { isNew = true; position = EntityFactory.CreatePosition(portfolio, security); position.DepoName = depoName; position.LimitType = limitType; position.Description = description; _positions.Add(key, position); } } return position; } private void RecycleTrades() { if (TradesKeepCount == 0) { _trades.Clear(); _tradeStat.Clear(true); _securityData.SyncDo(d => d.Values.ForEach(v => { v.Trades.Clear(); v.TradesById.Clear(); v.TradesByStringId.Clear(); })); return; } else if (TradesKeepCount == int.MaxValue) return; var totalCount = _trades.Count; if (totalCount < (1.5 * TradesKeepCount)) return; var countToRemove = totalCount - TradesKeepCount; lock (_securityData.SyncRoot) { var toRemove = _trades.SyncGet(d => { var tmp = d.Take(countToRemove).ToArray(); d.RemoveRange(0, countToRemove); return tmp; }); foreach (var trade in toRemove) { _tradeStat.Remove(trade); var data = GetData(trade.Security); if (trade.Id != 0) data.TradesById.Remove(trade.Id); else if (!trade.StringId.IsEmpty()) data.TradesByStringId.Remove(trade.StringId); else data.Trades.Remove(trade); } } } private void RecycleOrders() { if (OrdersKeepCount == 0) { _orders.Clear(); _allOrdersByTransactionId.Clear(); _allOrdersById.Clear(); _allOrdersByStringId.Clear(); _securityData.SyncDo(d => d.Values.ForEach(v => { v.Orders.Clear(); v.OrdersById.Clear(); v.OrdersByStringId.Clear(); })); return; } else if (OrdersKeepCount == int.MaxValue) return; var totalCount = _orders.Count; if (totalCount < (1.5 * OrdersKeepCount)) return; var countToRemove = totalCount - OrdersKeepCount; lock (_securityData.SyncRoot) { var toRemove = _orders.SyncGet(d => { var tmp = d.Where(o => o.State == OrderStates.Done || o.State == OrderStates.Failed).Take(countToRemove).ToHashSet(); d.RemoveRange(tmp); return tmp; }); _myTrades.SyncDo(d => d.RemoveWhere(t => toRemove.Contains(t.Order))); _allOrdersByTransactionId.SyncDo(d => d.RemoveWhere(t => toRemove.Contains(t.Value))); _allOrdersById.SyncDo(d => d.RemoveWhere(t => toRemove.Contains(t.Value))); _allOrdersByStringId.SyncDo(d => d.RemoveWhere(t => toRemove.Contains(t.Value))); foreach (var pair in _securityData) { pair.Value.Orders.SyncDo(d => d.RemoveWhere(t => toRemove.Contains(t.Value.Order))); pair.Value.MyTrades.SyncDo(d => d.RemoveWhere(t => toRemove.Contains(t.Value.Order))); pair.Value.OrdersById.SyncDo(d => d.RemoveWhere(t => toRemove.Contains(t.Value))); pair.Value.OrdersByStringId.SyncDo(d => d.RemoveWhere(t => toRemove.Contains(t.Value))); } } } } }
29.253199
242
0.698216
[ "Apache-2.0" ]
cuihantao/StockSharp
Algo/EntityCache.cs
32,615
C#
#pragma checksum "E:\Projects\BlazorUpdates\Facebook-Authentication-with-server-side-Blazor\BlazorFbAuth\BlazorFbAuth\Pages\Index.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "8111c2d9402235558347a3479403feaf0c83b516" // <auto-generated/> #pragma warning disable 1591 namespace BlazorFbAuth.Pages { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; #nullable restore #line 1 "E:\Projects\BlazorUpdates\Facebook-Authentication-with-server-side-Blazor\BlazorFbAuth\BlazorFbAuth\_Imports.razor" using System.Net.Http; #line default #line hidden #nullable disable #nullable restore #line 2 "E:\Projects\BlazorUpdates\Facebook-Authentication-with-server-side-Blazor\BlazorFbAuth\BlazorFbAuth\_Imports.razor" using Microsoft.AspNetCore.Authorization; #line default #line hidden #nullable disable #nullable restore #line 3 "E:\Projects\BlazorUpdates\Facebook-Authentication-with-server-side-Blazor\BlazorFbAuth\BlazorFbAuth\_Imports.razor" using Microsoft.AspNetCore.Components.Authorization; #line default #line hidden #nullable disable #nullable restore #line 4 "E:\Projects\BlazorUpdates\Facebook-Authentication-with-server-side-Blazor\BlazorFbAuth\BlazorFbAuth\_Imports.razor" using Microsoft.AspNetCore.Components.Forms; #line default #line hidden #nullable disable #nullable restore #line 5 "E:\Projects\BlazorUpdates\Facebook-Authentication-with-server-side-Blazor\BlazorFbAuth\BlazorFbAuth\_Imports.razor" using Microsoft.AspNetCore.Components.Routing; #line default #line hidden #nullable disable #nullable restore #line 6 "E:\Projects\BlazorUpdates\Facebook-Authentication-with-server-side-Blazor\BlazorFbAuth\BlazorFbAuth\_Imports.razor" using Microsoft.AspNetCore.Components.Web; #line default #line hidden #nullable disable #nullable restore #line 7 "E:\Projects\BlazorUpdates\Facebook-Authentication-with-server-side-Blazor\BlazorFbAuth\BlazorFbAuth\_Imports.razor" using Microsoft.JSInterop; #line default #line hidden #nullable disable #nullable restore #line 8 "E:\Projects\BlazorUpdates\Facebook-Authentication-with-server-side-Blazor\BlazorFbAuth\BlazorFbAuth\_Imports.razor" using BlazorFbAuth; #line default #line hidden #nullable disable #nullable restore #line 9 "E:\Projects\BlazorUpdates\Facebook-Authentication-with-server-side-Blazor\BlazorFbAuth\BlazorFbAuth\_Imports.razor" using BlazorFbAuth.Shared; #line default #line hidden #nullable disable [Microsoft.AspNetCore.Components.RouteAttribute("/")] public partial class Index : Microsoft.AspNetCore.Components.ComponentBase { #pragma warning disable 1998 protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) { __builder.AddMarkupContent(0, "<h1>Hello, world!</h1>\r\n\r\nWelcome to your new app.\r\n"); } #pragma warning restore 1998 } } #pragma warning restore 1591
34.494253
220
0.805065
[ "MIT" ]
AnkitSharma-007/Facebook-Authentication-with-server-side-Blazor
BlazorFbAuth/BlazorFbAuth/obj/Debug/netcoreapp3.1/Razor/Pages/Index.razor.g.cs
3,001
C#
namespace _03.NetherRealms { using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; public class Demon { public string Name { get; set; } public int Health { get; set; } public double Damage { get; set; } } public class Program { public static void Main() { var demons = Console.ReadLine() .Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); var sortedDemons = new SortedDictionary<string, Demon>(); foreach (var demon in demons) { var healthSymbols = demon.Where(s => !char.IsDigit(s) && s != '+' && s != '-' && s != '*' && s != '/' && s != '.'); var health = 0; foreach (var healthSymbol in healthSymbols) { health += healthSymbol; } var regex = new Regex(@"-?\d+\.?\d*"); var matches = regex.Matches(demon); var damage = 0.0; foreach (Match match in matches) { var number = double.Parse(match.Value); damage += number; } var specialSymbols = demon.Where(s => s == '*' || s == '/'); foreach (var symbol in specialSymbols) { if (symbol == '*') { damage *= 2; } else { damage /= 2; } } sortedDemons.Add(demon, new Demon { Name = demon, Health = health, Damage = damage }); } foreach (var sortedDemon in sortedDemons) { var demon = sortedDemon.Value; Console.WriteLine($"{demon.Name} - {demon.Health} health, {demon.Damage:F2} damage"); } } } }
19.3125
89
0.563754
[ "MIT" ]
stanislaviv/Programming-Fundamentals-May-2017
16_ExamPreparations/16_ExamPrep1/II.03. Nether Realms/II.04. Roli The Coder .cs
1,547
C#
using System.ComponentModel.Composition; using Csla.Reflection; using Csla.Server; using MEFSample.Business; using MEFSample.ObjectFactoryDAL.ChildInterfaces; namespace MEFSample.ObjectFactoryDAL.ChildFactories { [Export(typeof(ICustomerInfoFactory))] public class CustomerInfoFactory : ObjectFactory, ICustomerInfoFactory { public CustomerInfo GetCustomerInfo(DataEntitites.CustomerData data) { var customer = (CustomerInfo) MethodCaller.CreateInstance(typeof(CustomerInfo)); LoadProperty(customer, CustomerInfo.IdProperty, data.Id); LoadProperty(customer, CustomerInfo.NameProperty, data.Name); return customer; } } }
30.318182
86
0.784108
[ "MIT" ]
MarimerLLC/cslacontrib
trunk/samples/MEFSamples/ObjectFactory/MEFSample.ObjectFactory.DAL/ChildFactories/CustomerInfoFactory.cs
669
C#
// this code is generated. don't modify this code. using System.Text.Json; namespace VrmValidator { // .materials[{0}].occlusionTexture public class gltf__materials_ITEM__occlusionTexture__Validator { ValidationContext m_context; public gltf__materials_ITEM__occlusionTexture__Validator(ValidationContext context) { m_context = context; } public void Validate(JsonElement json) { foreach(var kv in json.EnumerateObject()) { if(kv.Name == "extensions") { new gltf__materials_ITEM__occlusionTexture__extensions__Validator(m_context).Validate(kv.Value); continue; } if(kv.Name == "extras") { new gltf__materials_ITEM__occlusionTexture__extras__Validator(m_context).Validate(kv.Value); continue; } if(kv.Name == "index") { continue; } if(kv.Name == "texCoord") { { if(kv.Value.ValueKind == JsonValueKind.Number) { var value = kv.Value.GetInt32(); if(value < 0) { m_context.AddMessage(MessageTypes.MinimumException, value, ".materials[{0}].occlusionTexture.texCoord", null); } else{ // OK } } else{ m_context.AddMessage(MessageTypes.InvalidType, kv.Value, ".materials[{0}].occlusionTexture.texCoord", null); } } continue; } if(kv.Name == "strength") { continue; } // unknown key m_context.AddMessage(MessageTypes.UnknownProperty, kv.Value, ".materials[{0}].occlusionTexture", kv.Name); } } } }
30.402597
139
0.422469
[ "MIT" ]
ousttrue/vrm-protobuf
VrmJsonScheme/Validator/Generated/gltf__materials_ITEM__occlusionTexture__Validator.cs
2,343
C#
using SmartThingsNet.Model; using System; using System.Collections.Generic; using System.Linq; namespace SmartThingsTerminal.Scenarios { [ScenarioMetadata(Name: "InstalledApps", Description: "SmartThings installed applications")] [ScenarioCategory("Installed Apps")] class InstalledApps : Scenario { public override void Setup() { Dictionary<string, dynamic> dataItemList = null; Dictionary<string, string> displayItemList = null; try { if (STClient.GetAllInstalledApps().Items?.Count > 0) { dataItemList = STClient.GetAllInstalledApps().Items .OrderBy(t => t.DisplayName) .Select(t => new KeyValuePair<string, dynamic>(t.InstalledAppId.ToString(), t)) .ToDictionary(t => t.Key, t => t.Value); displayItemList = STClient.GetAllInstalledApps().Items .OrderBy(o => o.DisplayName) .Select(t => new KeyValuePair<string, string>(t.InstalledAppId.ToString(), t.DisplayName)) .ToDictionary(t => t.Key, t => t.Value); } } catch (SmartThingsNet.Client.ApiException exp) { ShowErrorMessage($"Error {exp.ErrorCode}{Environment.NewLine}{exp.Message}"); } catch (Exception exp) { ShowErrorMessage($"Error {exp.Message}"); } ConfigureWindows<InstalledApp>(displayItemList, dataItemList); } } }
36.377778
114
0.55223
[ "MIT" ]
daltskin/SmartThingsTerminal
SmartThingsTerminal/Scenarios/InstalledApps.cs
1,639
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace REST_Parser.Exceptions { public class REST_InvalidOperatorException : Exception { public REST_InvalidOperatorException() { } public REST_InvalidOperatorException(string fieldname, string op) : base(string.Format("The REST request contained an invalid operator ({1}) for field ({0})", fieldname, op)) { } } }
26.105263
182
0.693548
[ "MIT" ]
BigBadJock/REST-Parser
REST-Parser/REST-Parser/Exceptions/REST_InvalidOperatorException.cs
498
C#
using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Animation; using Nostrum.Extensions; using Nostrum.WPF.Extensions; using Nostrum.WPF.Factories; namespace TCC.UI.Windows { public class TccWindow : Window { private static readonly List<TccWindow> _createdWindows = new(); public event Action? Hidden; public event Action? Showed; private readonly bool _canClose; private readonly DoubleAnimation _showAnim; private readonly DoubleAnimation _hideAnim; public IntPtr Handle { get; private set; } protected TccWindow(bool canClose) { _createdWindows.Add(this); _canClose = canClose; Closing += OnClosing; Loaded += OnLoaded; _showAnim = AnimationFactory.CreateDoubleAnimation(150, 1); _hideAnim = AnimationFactory.CreateDoubleAnimation(150, 0, completed: (_, _) => { Hide(); if (App.Settings.ForceSoftwareRendering) RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly; Hidden?.Invoke(); }); } public virtual void HideWindow() { Dispatcher?.InvokeAsync(() => { BeginAnimation(OpacityProperty, _hideAnim); }); } public virtual void ShowWindow() { if (App.Settings.ForceSoftwareRendering) RenderOptions.ProcessRenderMode = RenderMode.Default; Dispatcher?.InvokeAsync(() => { BeginAnimation(OpacityProperty, null); Opacity = 0; Show(); Showed?.Invoke(); RefreshTopmost(); BeginAnimation(OpacityProperty, _showAnim); }); } protected virtual void OnLoaded(object sender, RoutedEventArgs e) { Handle = new WindowInteropHelper(this).Handle; } protected virtual void OnClosing(object sender, System.ComponentModel.CancelEventArgs e) { if (_canClose) { _createdWindows.Remove(this); return; } e.Cancel = true; HideWindow(); } protected void Drag(object sender, MouseButtonEventArgs e) { ((UIElement)Content).Opacity = .7; this.TryDragMove(); ((UIElement)Content).Opacity = 1; } protected void RefreshTopmost() { if (FocusManager.PauseTopmost) return; Dispatcher?.InvokeAsync(() => { Topmost = false; Topmost = true; }); } public static bool Exists(Type type) { return _createdWindows.Any(w => w.GetType() == type); } public static bool Exists(IntPtr handle) { return _createdWindows.Any(w => w.Handle == handle && w.Handle != IntPtr.Zero); } } }
29.110092
115
0.558777
[ "MIT" ]
Foglio1024/Tera-custom-cooldowns
TCC.Core/UI/Windows/TccWindow.cs
3,175
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; namespace System.Security.Cryptography { /// <summary> /// Maps to the "dwFlags" parameter of the NCryptCreatePersistedKey() api. /// </summary> [Flags] public enum CngKeyCreationOptions : int { None = 0x00000000, MachineKey = 0x00000020, // NCRYPT_MACHINE_KEY_FLAG OverwriteExistingKey = 0x00000080, // NCRYPT_OVERWRITE_KEY_FLAG } }
28.380952
101
0.682886
[ "MIT" ]
690486439/corefx
src/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKeyCreationOptions.cs
596
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the dms-2016-01-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DatabaseMigrationService.Model { /// <summary> /// Container for the parameters to the DescribeEndpoints operation. /// Returns information about the endpoints for your account in the current region. /// </summary> public partial class DescribeEndpointsRequest : AmazonDatabaseMigrationServiceRequest { private List<Filter> _filters = new List<Filter>(); private string _marker; private int? _maxRecords; /// <summary> /// Gets and sets the property Filters. /// <para> /// Filters applied to the describe action. /// </para> /// /// <para> /// Valid filter names: endpoint-arn | endpoint-type | endpoint-id | engine-name /// </para> /// </summary> public List<Filter> Filters { get { return this._filters; } set { this._filters = value; } } // Check to see if Filters property is set internal bool IsSetFilters() { return this._filters != null && this._filters.Count > 0; } /// <summary> /// Gets and sets the property Marker. /// <para> /// An optional pagination token provided by a previous request. If this parameter is /// specified, the response includes only records beyond the marker, up to the value specified /// by <code>MaxRecords</code>. /// </para> /// </summary> public string Marker { get { return this._marker; } set { this._marker = value; } } // Check to see if Marker property is set internal bool IsSetMarker() { return this._marker != null; } /// <summary> /// Gets and sets the property MaxRecords. /// <para> /// The maximum number of records to include in the response. If more records exist than /// the specified <code>MaxRecords</code> value, a pagination token called a marker is /// included in the response so that the remaining results can be retrieved. /// </para> /// /// <para> /// Default: 100 /// </para> /// /// <para> /// Constraints: Minimum 20, maximum 100. /// </para> /// </summary> public int MaxRecords { get { return this._maxRecords.GetValueOrDefault(); } set { this._maxRecords = value; } } // Check to see if MaxRecords property is set internal bool IsSetMaxRecords() { return this._maxRecords.HasValue; } } }
32.135135
102
0.594337
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/DatabaseMigrationService/Generated/Model/DescribeEndpointsRequest.cs
3,567
C#
using RichHudFramework.Internal; using RichHudFramework.UI; using RichHudFramework; using Sandbox.ModAPI; using System; using System.Collections.Generic; using VRage.ModAPI; using VRageMath; using MySpaceTexts = Sandbox.Game.Localization.MySpaceTexts; using IMyAirVent = SpaceEngineers.Game.ModAPI.IMyAirVent; using IMyGunBaseUser = Sandbox.Game.Entities.IMyGunBaseUser; using IMyLandingGear = SpaceEngineers.Game.ModAPI.IMyLandingGear; using IMyGravityGeneratorBase = SpaceEngineers.Game.ModAPI.IMyGravityGeneratorBase; using IMyTimerBlock = SpaceEngineers.Game.ModAPI.IMyTimerBlock; namespace DarkHelmet.BuildVision2 { [Flags] public enum TBlockSubtypes : int { None = 0, Functional = 0x1, Powered = 0x2, Battery = 0x4, Inventory = 0x8, Production = 0x10, GasTank = 0x20, AirVent = 0x40, Door = 0x80, Parachute = 0x100, LandingGear = 0x200, Connector = 0x400, MechanicalConnection = 0x800, Suspension = 0x1000, Piston = 0x2000, Rotor = 0x4000, Light = 0x8000, JumpDrive = 0x10000, Thruster = 0x20000, Beacon = 0x40000, LaserAntenna = 0x80000, RadioAntenna = 0x100000, OreDetector = 0x200000, Gyroscope = 0x400000, Warhead = 0x800000, GunBase = 0x1000000, Turret = 0x2000000, GravityGen = 0x4000000, Sensor = 0x8000000, Projector = 0x10000000, Timer = 0x20000000, Programmable = 0x40000000 } /// <summary> /// General purpose terminal block wrapper used to provide easy access to block subtype members. /// </summary> public partial class SuperBlock { /// <summary> /// Associated terminal block /// </summary> public IMyTerminalBlock TBlock { get; private set; } public TerminalGrid TerminalGrid { get; private set; } /// <summary> /// Block type identifier. Uses IMyCubeBlock.BlockDefinition.TypeIdString. /// </summary> public string TypeID { get; private set; } /// <summary> /// Returns the position of the block in world space. /// </summary> public Vector3D Position => TBlock != null ? TBlock.GetPosition() : Vector3D.Zero; /// <summary> /// True if the block integrity is above its breaking threshold /// </summary> public bool IsFunctional => TBlock != null && TBlock.IsFunctional; /// <summary> /// True if the block is functional and able to do work. /// </summary> public bool IsWorking => TBlock != null && TBlock.IsWorking; /// <summary> /// True if the local player has terminal access permissions /// </summary> public bool CanLocalPlayerAccess => TBlock != null && TBlock.HasLocalPlayerAccess(); /// <summary> /// Indicates the subtypes supported by the block. /// </summary> public TBlockSubtypes SubtypeId { get; private set; } /// <summary> /// List of subtype accessors /// </summary> public IReadOnlyList<SubtypeAccessorBase> SubtypeAccessors => subtypeAccessors; private readonly List<SubtypeAccessorBase> subtypeAccessors; public SuperBlock() { subtypeAccessors = new List<SubtypeAccessorBase>(); } public virtual void SetBlock(TerminalGrid grid, IMyTerminalBlock tBlock) { Utils.Debug.AssertNotNull(tBlock); Utils.Debug.AssertNotNull(grid); Reset(); TBlock = tBlock; TerminalGrid = grid; TypeID = tBlock.BlockDefinition.TypeIdString; TBlock.OnMarkForClose += BlockClosing; AddBlockSubtypes(); } public virtual void Reset() { for (int i = 0; i < subtypeAccessors.Count; i++) subtypeAccessors[i].Reset(); if (TBlock != null) TBlock.OnMarkForClose -= BlockClosing; subtypeAccessors.Clear(); TypeID = null; TBlock = null; TerminalGrid = null; SubtypeId = 0; } /// <summary> /// Clears all references to the <see cref="IMyTerminalBlock"/> held by the <see cref="SuperBlock"/>. /// </summary> private void BlockClosing(IMyEntity entity) { Reset(); } private void AddBlockSubtypes() { SetOrCreateAccessor(ref _general, this); SetOrCreateAccessor(ref _power, this); SetOrCreateAccessor(ref _battery, this); SetOrCreateAccessor(ref _inventory, this); SetOrCreateAccessor(ref _production, this); SetOrCreateAccessor(ref _gasTank, this); SetOrCreateAccessor(ref _airVent, this); SetOrCreateAccessor(ref _door, this); SetOrCreateAccessor(ref _landingGear, this); SetOrCreateAccessor(ref _connector, this); SetOrCreateAccessor(ref _mechConnection, this); SetOrCreateAccessor(ref _piston, this); SetOrCreateAccessor(ref _rotor, this); SetOrCreateAccessor(ref _light, this); SetOrCreateAccessor(ref _jumpDrive, this); SetOrCreateAccessor(ref _thruster, this); SetOrCreateAccessor(ref _beacon, this); SetOrCreateAccessor(ref _laserAntenna, this); SetOrCreateAccessor(ref _radioAntenna, this); SetOrCreateAccessor(ref _oreDetector, this); SetOrCreateAccessor(ref _warhead, this); SetOrCreateAccessor(ref _weapon, this); SetOrCreateAccessor(ref _turret, this); SetOrCreateAccessor(ref _gyroscope, this); SetOrCreateAccessor(ref _gravityGen, this); SetOrCreateAccessor(ref _sensor, this); SetOrCreateAccessor(ref _projector, this); SetOrCreateAccessor(ref _timer, this); SetOrCreateAccessor(ref _program, this); } public void GetGroupNamesForBlock(List<string> groups) => TerminalGrid.GetGroupNamesForBlock(TBlock, groups); public void GetGroupsForBlock(List<IMyBlockGroup> groups) => TerminalGrid.GetGroupsForBlock(TBlock, groups); private static void SetOrCreateAccessor<T>(ref T accessor, SuperBlock block) where T : SubtypeAccessorBase, new() { if (accessor == null) accessor = new T(); accessor.SetBlock(block); } public abstract class SubtypeAccessorBase { public TBlockSubtypes SubtypeId { get; protected set; } protected SuperBlock block; public abstract void SetBlock(SuperBlock block); public virtual void Reset() { SubtypeId = TBlockSubtypes.None; block = null; } protected virtual void SetBlock(SuperBlock block, TBlockSubtypes subtypeId, bool addSubtype = true) { this.block = block; this.SubtypeId = subtypeId; if (addSubtype) { block.SubtypeId |= subtypeId; block.subtypeAccessors.Add(this); } } protected virtual void SetBlock(SuperBlock block, TBlockSubtypes subtypeId, TBlockSubtypes prerequsites) => SetBlock(block, subtypeId, block.SubtypeId.UsesSubtype(prerequsites)); public abstract void GetSummary(RichText builder, GlyphFormat nameFormat, GlyphFormat valueFormat); } public abstract class SubtypeAccessor<T> : SubtypeAccessorBase where T : class { protected T subtype; protected override void SetBlock(SuperBlock block, TBlockSubtypes subtypeId, bool addSubtype = true) { this.block = block; subtype = block.TBlock as T; this.SubtypeId = subtypeId; if (addSubtype && subtype != null) { block.SubtypeId |= subtypeId; block.subtypeAccessors.Add(this); } } public override void Reset() { block = null; subtype = null; SubtypeId = 0; } } } public static class SubtypeEnumExtensions { private static readonly IReadOnlyList<TBlockSubtypes> subtypes; static SubtypeEnumExtensions() { subtypes = Enum.GetValues(typeof(TBlockSubtypes)) as IReadOnlyList<TBlockSubtypes>; } public static TBlockSubtypes GetLargestSubtype(this TBlockSubtypes subtypeId) { for (int n = subtypes.Count - 1; n >= 0; n--) { if ((subtypeId & subtypes[n]) == subtypes[n]) return subtypes[n]; } return TBlockSubtypes.None; } public static bool UsesSubtype(this TBlockSubtypes subtypeId, TBlockSubtypes flag) => (subtypeId & flag) == flag; } }
31.735974
122
0.570196
[ "MIT" ]
ZachHembree/BuildVision2
BuildVision2/Data/Scripts/BuildVision2/Terminal/BlockData/SuperBlock/SuperBlock.cs
9,618
C#
using System.Linq; using ProApiLibrary.Api.Queries; using ProApiLibrary.Data.Entities; namespace ProApiLibrary.Api.Clients { /// <summary> /// Strongly typed <seealso cref="EntityProxy"/> for <seealso cref="Location"/> entities /// </summary> /// <remarks> /// <seealso cref="EntityProxy"/> /// <seealso cref="Location"/> /// <seealso cref="IEntity"/> /// </remarks> public class LocationProxy : EntityProxy, ILocation { private ILocation _location; public LocationProxy(EntityId entityId, Client client, ResponseDictionary responseDictionary) : base(entityId, client, responseDictionary) { } public override IEntity Entity { get { return _location; } } public override void Load() { if (!IsLoaded) { var response = this.Client.FindLocations(new LocationQuery(this.Id)); var results = response.Results; _location = ((results == null || !results.Any()) ? null : results.First()); this.IsLoaded = true; } } public Location.LocationType? Type { get { return _location == null ? null : _location.Type; } } public string Address { get { return _location == null ? null : _location.Address; } } public string StandardAddressLine1 { get { return _location == null ? null : _location.StandardAddressLine1; } } public string StandardAddressLine2 { get { return _location == null ? null : _location.StandardAddressLine2; } } public string StandardAddressLocation { get { return _location == null ? null : _location.StandardAddressLocation; } } public string City { get { return _location == null ? null : _location.City; } } public string StateCode { get { return _location == null ? null : _location.StateCode; } } public string PostalCode { get { return _location == null ? null : _location.PostalCode; } } public string CountryCode { get { return _location == null ? null : _location.CountryCode; } } public string AptType { get { return _location == null ? null : _location.AptType; } } public string Zip4 { get { return _location == null ? null : _location.Zip4; } } public string House { get { return _location == null ? null : _location.House; } } public string StreetName { get { return _location == null ? null : _location.StreetName; } } public string StreetType { get { return _location == null ? null : _location.StreetType; } } public string PreDir { get { return _location == null ? null : _location.PreDir; } } public string PostDir { get { return _location == null ? null : _location.PostDir; } } public string AptNumber { get { return _location == null ? null : _location.AptNumber; } } public string BoxNumber { get { return _location == null ? null : _location.BoxNumber; } } public TimePeriod ValidFor { get { return _location == null ? null : _location.ValidFor; } } public bool IsHistorical { get { return _location != null && _location.IsHistorical; } } public bool? IsReceivingMail { get { return _location == null ? null : _location.IsReceivingMail; } } public Location.LocationNotReceivingMailReason? NotReceivingMailReason { get { return _location == null ? null : _location.NotReceivingMailReason; } } public Location.AddressUsage? Usage { get { return _location == null ? null : _location.Usage; } } public Location.LocationDeliveryPoint? DeliveryPoint { get { return _location == null ? null : _location.DeliveryPoint; } } public Location.LocationBoxType? BoxType { get { return _location == null ? null : _location.BoxType; } } public Location.LocationAddressType? AddressType { get { return _location == null ? null : _location.AddressType; } } public LatLong LatLong { get { return _location == null ? null : _location.LatLong; } } public bool? IsDeliverable { get { return _location == null ? null : _location.IsDeliverable; } } } }
22.438503
96
0.637035
[ "MIT" ]
whitepages/proapi-client-csharp
ProApiLibrary/Api/Clients/LocationProxy.cs
4,198
C#
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using Santolibre.GoogleMailBackup.Services; namespace Santolibre.GoogleMailBackup { class Program { public static void Main(string[] args) { var servicesProvider = SetupServices(); var app = servicesProvider.GetRequiredService<App>(); app.Run(args); NLog.LogManager.Shutdown(); } private static ServiceProvider SetupServices() { return new ServiceCollection() .AddSingleton<IGoogleApiService, GoogleApiService>() .AddSingleton<IGoogleMailBackupService, GoogleMailBackupService>() .AddSingleton<IConfiguration>(new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).Build()) .AddLogging(builder => { builder.SetMinimumLevel(LogLevel.Trace); builder.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true }); }) .AddTransient<App>() .BuildServiceProvider(); } } }
33.780488
151
0.591336
[ "MIT" ]
Andy9FromSpace/google-mail-backup-core
Santolibre.GoogleMailBackup/Program.cs
1,387
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. namespace Microsoft.MixedReality.Toolkit.Utilities { /// <summary> /// The AxisType identifies the type of button or input being sent to the framework from a controller. /// This is mainly information only or for advanced users to understand the input coming directly from the controller. /// </summary> public enum AxisType { /// <summary> /// No Specified type. /// </summary> None = 0, /// <summary> /// Raw stream from input (proxy only). /// </summary> Raw, /// <summary> /// Digital On/Off input. /// </summary> Digital, /// <summary> /// Single Axis analogue input. /// </summary> SingleAxis, /// <summary> /// Dual Axis analogue input. /// </summary> DualAxis, /// <summary> /// Position only Axis analogue input. /// </summary> ThreeDofPosition, /// <summary> /// Rotation only Axis analogue input. /// </summary> ThreeDofRotation, /// <summary> /// Position AND Rotation analogue input. /// </summary> SixDof } }
31.222222
123
0.53452
[ "MIT" ]
Argylebuild/aad-hololens
Assets/MRTK/Core/Definitions/Utilities/AxisType.cs
1,407
C#
//----------------------------------------------------------------------- // <copyright file="SingleInstance.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary> // This class checks to make sure that only one instance of // this application is running at a time. // </summary> //----------------------------------------------------------------------- namespace Microsoft.Shell { using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Ipc; using System.Runtime.Serialization.Formatters; using System.Threading; using System.Windows; using System.Windows.Threading; using System.Security; using System.Runtime.InteropServices; using System.ComponentModel; internal enum WM { NULL = 0x0000, CREATE = 0x0001, DESTROY = 0x0002, MOVE = 0x0003, SIZE = 0x0005, ACTIVATE = 0x0006, SETFOCUS = 0x0007, KILLFOCUS = 0x0008, ENABLE = 0x000A, SETREDRAW = 0x000B, SETTEXT = 0x000C, GETTEXT = 0x000D, GETTEXTLENGTH = 0x000E, PAINT = 0x000F, CLOSE = 0x0010, QUERYENDSESSION = 0x0011, QUIT = 0x0012, QUERYOPEN = 0x0013, ERASEBKGND = 0x0014, SYSCOLORCHANGE = 0x0015, SHOWWINDOW = 0x0018, ACTIVATEAPP = 0x001C, SETCURSOR = 0x0020, MOUSEACTIVATE = 0x0021, CHILDACTIVATE = 0x0022, QUEUESYNC = 0x0023, GETMINMAXINFO = 0x0024, WINDOWPOSCHANGING = 0x0046, WINDOWPOSCHANGED = 0x0047, CONTEXTMENU = 0x007B, STYLECHANGING = 0x007C, STYLECHANGED = 0x007D, DISPLAYCHANGE = 0x007E, GETICON = 0x007F, SETICON = 0x0080, NCCREATE = 0x0081, NCDESTROY = 0x0082, NCCALCSIZE = 0x0083, NCHITTEST = 0x0084, NCPAINT = 0x0085, NCACTIVATE = 0x0086, GETDLGCODE = 0x0087, SYNCPAINT = 0x0088, NCMOUSEMOVE = 0x00A0, NCLBUTTONDOWN = 0x00A1, NCLBUTTONUP = 0x00A2, NCLBUTTONDBLCLK = 0x00A3, NCRBUTTONDOWN = 0x00A4, NCRBUTTONUP = 0x00A5, NCRBUTTONDBLCLK = 0x00A6, NCMBUTTONDOWN = 0x00A7, NCMBUTTONUP = 0x00A8, NCMBUTTONDBLCLK = 0x00A9, SYSKEYDOWN = 0x0104, SYSKEYUP = 0x0105, SYSCHAR = 0x0106, SYSDEADCHAR = 0x0107, COMMAND = 0x0111, SYSCOMMAND = 0x0112, MOUSEMOVE = 0x0200, LBUTTONDOWN = 0x0201, LBUTTONUP = 0x0202, LBUTTONDBLCLK = 0x0203, RBUTTONDOWN = 0x0204, RBUTTONUP = 0x0205, RBUTTONDBLCLK = 0x0206, MBUTTONDOWN = 0x0207, MBUTTONUP = 0x0208, MBUTTONDBLCLK = 0x0209, MOUSEWHEEL = 0x020A, XBUTTONDOWN = 0x020B, XBUTTONUP = 0x020C, XBUTTONDBLCLK = 0x020D, MOUSEHWHEEL = 0x020E, CAPTURECHANGED = 0x0215, ENTERSIZEMOVE = 0x0231, EXITSIZEMOVE = 0x0232, IME_SETCONTEXT = 0x0281, IME_NOTIFY = 0x0282, IME_CONTROL = 0x0283, IME_COMPOSITIONFULL = 0x0284, IME_SELECT = 0x0285, IME_CHAR = 0x0286, IME_REQUEST = 0x0288, IME_KEYDOWN = 0x0290, IME_KEYUP = 0x0291, NCMOUSELEAVE = 0x02A2, DWMCOMPOSITIONCHANGED = 0x031E, DWMNCRENDERINGCHANGED = 0x031F, DWMCOLORIZATIONCOLORCHANGED = 0x0320, DWMWINDOWMAXIMIZEDCHANGE = 0x0321, #region Windows 7 DWMSENDICONICTHUMBNAIL = 0x0323, DWMSENDICONICLIVEPREVIEWBITMAP = 0x0326, #endregion USER = 0x0400, // This is the hard-coded message value used by WinForms for Shell_NotifyIcon. // It's relatively safe to reuse. TRAYMOUSEMESSAGE = 0x800, //WM_USER + 1024 APP = 0x8000, } [SuppressUnmanagedCodeSecurity] internal static class NativeMethods { /// <summary> /// Delegate declaration that matches WndProc signatures. /// </summary> public delegate IntPtr MessageHandler(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled); [DllImport("shell32.dll", EntryPoint = "CommandLineToArgvW", CharSet = CharSet.Unicode)] private static extern IntPtr _CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string cmdLine, out int numArgs); [DllImport("kernel32.dll", EntryPoint = "LocalFree", SetLastError = true)] private static extern IntPtr _LocalFree(IntPtr hMem); public static string[] CommandLineToArgvW(string cmdLine) { IntPtr argv = IntPtr.Zero; try { int numArgs = 0; argv = _CommandLineToArgvW(cmdLine, out numArgs); if (argv == IntPtr.Zero) { throw new Win32Exception(); } var result = new string[numArgs]; for (int i = 0; i < numArgs; i++) { IntPtr currArg = Marshal.ReadIntPtr(argv, i * Marshal.SizeOf(typeof(IntPtr))); result[i] = Marshal.PtrToStringUni(currArg); } return result; } finally { IntPtr p = _LocalFree(argv); // Otherwise LocalFree failed. // Assert.AreEqual(IntPtr.Zero, p); } } } public interface ISingleInstanceApp { bool SignalExternalCommandLineArgs(IList<string> args); } /// <summary> /// This class checks to make sure that only one instance of /// this application is running at a time. /// </summary> /// <remarks> /// Note: this class should be used with some caution, because it does no /// security checking. For example, if one instance of an app that uses this class /// is running as Administrator, any other instance, even if it is not /// running as Administrator, can activate it with command line arguments. /// For most apps, this will not be much of an issue. /// </remarks> public static class SingleInstance<TApplication> where TApplication : Application, ISingleInstanceApp { #region Private Fields /// <summary> /// String delimiter used in channel names. /// </summary> private const string Delimiter = ":"; /// <summary> /// Suffix to the channel name. /// </summary> private const string ChannelNameSuffix = "SingeInstanceIPCChannel"; /// <summary> /// Remote service name. /// </summary> private const string RemoteServiceName = "SingleInstanceApplicationService"; /// <summary> /// IPC protocol used (string). /// </summary> private const string IpcProtocol = "ipc://"; /// <summary> /// Application mutex. /// </summary> private static Mutex singleInstanceMutex; /// <summary> /// IPC channel for communications. /// </summary> private static IpcServerChannel channel; /// <summary> /// List of command line arguments for the application. /// </summary> private static IList<string> commandLineArgs; #endregion #region Public Properties /// <summary> /// Gets list of command line arguments for the application. /// </summary> public static IList<string> CommandLineArgs { get { return commandLineArgs; } } #endregion #region Public Methods /// <summary> /// Checks if the instance of the application attempting to start is the first instance. /// If not, activates the first instance. /// </summary> /// <returns>True if this is the first instance of the application.</returns> public static bool InitializeAsFirstInstance(string uniqueName) { commandLineArgs = GetCommandLineArgs(uniqueName); // Build unique application Id and the IPC channel name. string applicationIdentifier = uniqueName + Environment.UserName; string channelName = String.Concat(applicationIdentifier, Delimiter, ChannelNameSuffix); // Create mutex based on unique application Id to check if this is the first instance of the application. bool firstInstance; singleInstanceMutex = new Mutex(true, applicationIdentifier, out firstInstance); if (firstInstance) { CreateRemoteService(channelName); } else { SignalFirstInstance(channelName, commandLineArgs); } return firstInstance; } /// <summary> /// Cleans up single-instance code, clearing shared resources, mutexes, etc. /// </summary> public static void Cleanup() { if (singleInstanceMutex != null) { singleInstanceMutex.Close(); singleInstanceMutex = null; } if (channel != null) { ChannelServices.UnregisterChannel(channel); channel = null; } } #endregion #region Private Methods /// <summary> /// Gets command line args - for ClickOnce deployed applications, command line args may not be passed directly, they have to be retrieved. /// </summary> /// <returns>List of command line arg strings.</returns> private static IList<string> GetCommandLineArgs(string uniqueApplicationName) { string[] args = null; if (AppDomain.CurrentDomain.ActivationContext == null) { // The application was not clickonce deployed, get args from standard API's args = Environment.GetCommandLineArgs(); } else { // The application was clickonce deployed // Clickonce deployed apps cannot recieve traditional commandline arguments // As a workaround commandline arguments can be written to a shared location before // the app is launched and the app can obtain its commandline arguments from the // shared location string appFolderPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), uniqueApplicationName); string cmdLinePath = Path.Combine(appFolderPath, "cmdline.txt"); if (File.Exists(cmdLinePath)) { try { using (TextReader reader = new StreamReader(cmdLinePath, System.Text.Encoding.Unicode)) { args = NativeMethods.CommandLineToArgvW(reader.ReadToEnd()); } File.Delete(cmdLinePath); } catch (IOException) { } } } if (args == null) { args = new string[] { }; } return new List<string>(args); } /// <summary> /// Creates a remote service for communication. /// </summary> /// <param name="channelName">Application's IPC channel name.</param> private static void CreateRemoteService(string channelName) { BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider(); serverProvider.TypeFilterLevel = TypeFilterLevel.Full; IDictionary props = new Dictionary<string, string>(); props["name"] = channelName; props["portName"] = channelName; props["exclusiveAddressUse"] = "false"; // Create the IPC Server channel with the channel properties channel = new IpcServerChannel(props, serverProvider); // Register the channel with the channel services ChannelServices.RegisterChannel(channel, true); // Expose the remote service with the REMOTE_SERVICE_NAME IPCRemoteService remoteService = new IPCRemoteService(); RemotingServices.Marshal(remoteService, RemoteServiceName); } /// <summary> /// Creates a client channel and obtains a reference to the remoting service exposed by the server - /// in this case, the remoting service exposed by the first instance. Calls a function of the remoting service /// class to pass on command line arguments from the second instance to the first and cause it to activate itself. /// </summary> /// <param name="channelName">Application's IPC channel name.</param> /// <param name="args"> /// Command line arguments for the second instance, passed to the first instance to take appropriate action. /// </param> private static void SignalFirstInstance(string channelName, IList<string> args) { IpcClientChannel secondInstanceChannel = new IpcClientChannel(); ChannelServices.RegisterChannel(secondInstanceChannel, true); string remotingServiceUrl = IpcProtocol + channelName + "/" + RemoteServiceName; // Obtain a reference to the remoting service exposed by the server i.e the first instance of the application IPCRemoteService firstInstanceRemoteServiceReference = (IPCRemoteService)RemotingServices.Connect(typeof(IPCRemoteService), remotingServiceUrl); // Check that the remote service exists, in some cases the first instance may not yet have created one, in which case // the second instance should just exit if (firstInstanceRemoteServiceReference != null) { // Invoke a method of the remote service exposed by the first instance passing on the command line // arguments and causing the first instance to activate itself firstInstanceRemoteServiceReference.InvokeFirstInstance(args); } } /// <summary> /// Callback for activating first instance of the application. /// </summary> /// <param name="arg">Callback argument.</param> /// <returns>Always null.</returns> private static object ActivateFirstInstanceCallback(object arg) { // Get command line args to be passed to first instance IList<string> args = arg as IList<string>; ActivateFirstInstance(args); return null; } /// <summary> /// Activates the first instance of the application with arguments from a second instance. /// </summary> /// <param name="args">List of arguments to supply the first instance of the application.</param> private static void ActivateFirstInstance(IList<string> args) { // Set main window state and process command line args if (Application.Current == null) { return; } ((TApplication)Application.Current).SignalExternalCommandLineArgs(args); } #endregion #region Private Classes /// <summary> /// Remoting service class which is exposed by the server i.e the first instance and called by the second instance /// to pass on the command line arguments to the first instance and cause it to activate itself. /// </summary> private class IPCRemoteService : MarshalByRefObject { /// <summary> /// Activates the first instance of the application. /// </summary> /// <param name="args">List of arguments to pass to the first instance.</param> public void InvokeFirstInstance(IList<string> args) { if (Application.Current != null) { // Do an asynchronous call to ActivateFirstInstance function Application.Current.Dispatcher.BeginInvoke( DispatcherPriority.Normal, new DispatcherOperationCallback(SingleInstance<TApplication>.ActivateFirstInstanceCallback), args); } } /// <summary> /// Remoting Object's ease expires after every 5 minutes by default. We need to override the InitializeLifetimeService class /// to ensure that lease never expires. /// </summary> /// <returns>Always null.</returns> public override object InitializeLifetimeService() { return null; } } #endregion } }
35.330595
156
0.581658
[ "BSD-3-Clause" ]
Cftn/oneM2MBrowser
oneM2MBrowser/SingleInstance.cs
17,208
C#
namespace Kafka.Example.Models { public class ResponseLog { public ResponseLog(string method, long elapsedTime, long timestamp) { Method = method; ElapsedTime = elapsedTime; Timestamp = timestamp; } public string Method { get; set; } public long Timestamp { get; set; } public long ElapsedTime { get; set; } } }
25.5
75
0.573529
[ "Unlicense" ]
halilkocaoz/kafka-response-log
server/Models/ResponseLog.cs
408
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Threading; using System.Threading.Tasks; namespace Microsoft.Azure.WebJobs.Host.Bindings { // Bind an IAsyncCollector to an 'Out T" parameter. internal class OutValueProvider<TMessage> : IOrderedValueBinder { private readonly IAsyncCollector<TMessage> _raw; private readonly string _invokeString; // raw is the underlying object (exposes a Flush method). // obj is athe front-end veneer to pass to the user function. // calls to obj will trickle through adapters to be calls on raw. public OutValueProvider(IAsyncCollector<TMessage> raw, string invokeString) { _raw = raw; _invokeString = invokeString; } public BindStepOrder StepOrder { get { return BindStepOrder.Enqueue; } } public Type Type { get { return typeof(TMessage); } } public Task<object> GetValueAsync() { // Out parameters are set on return return Task.FromResult<object>(null); } public async Task SetValueAsync(object value, CancellationToken cancellationToken) { if (value == null) { // Nothing set return; } TMessage message = (TMessage)value; await _raw.AddAsync(message, cancellationToken); await _raw.FlushAsync(); } public string ToInvokeString() { return _invokeString; } } }
28.079365
95
0.584511
[ "MIT" ]
Azure-App-Service/azure-webjobs-sdk
src/Microsoft.Azure.WebJobs.Host/Bindings/AsyncCollector/OutValueProvider.cs
1,771
C#
/* * Author: Kishore Reddy * Url: http://commonlibrarynet.codeplex.com/ * Title: CommonLibrary.NET * Copyright: � 2009 Kishore Reddy * License: LGPL License * LicenseUrl: http://commonlibrarynet.codeplex.com/license * Description: A C# based .NET 3.5 Open-Source collection of reusable components. * Usage: Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using ComLib; namespace ComLib.Collections { /// <summary> /// Extension to enumerator with extended methods to indicate if last or first item /// </summary> /// <typeparam name="T"></typeparam> public class EnumeratorMulti<T> : IEnumerator<T> { private IEnumerator<T> _currentEnumerator; private IList<IEnumerator<T>> _allEnumerators; private int _currentEnumeratorIndex; /// <summary> /// Initialize the list. /// </summary> /// <param name="allEnumerators"></param> public EnumeratorMulti(IList<IEnumerator<T>> allEnumerators) { _allEnumerators = allEnumerators; _currentEnumeratorIndex = -1; } #region IEnumerator<T> Members /// <summary> /// Get the current item. /// </summary> public T Current { get { if( IsWithinBounds() ) return _allEnumerators[_currentEnumeratorIndex].Current; return default(T); } } #endregion #region IDisposable Members /// <summary> /// Dispose. /// </summary> public void Dispose() { // Nothing to dispose. } #endregion #region IEnumerator Members /// <summary> /// Get the current item in list. /// </summary> object System.Collections.IEnumerator.Current { get { if (IsWithinBounds()) return _allEnumerators[_currentEnumeratorIndex].Current; return null; } } /// <summary> /// Move to the next item. /// </summary> /// <returns></returns> public bool MoveNext() { // Check for case where moving to first one. if (_currentEnumeratorIndex == -1) MoveToNextEnumerator(); // Can move on the current enumerator? if (_currentEnumerator.MoveNext()) return true; // Last enumerator - can not move anymore. if (_currentEnumeratorIndex == _allEnumerators.Count - 1) return false; // Ok. move to the next enumerator. MoveToNextEnumerator(); // If past // Now move next on the next enumerator. return _currentEnumerator.MoveNext(); } /// <summary> /// Reset the iterator to first item enumerator. /// </summary> public void Reset() { _currentEnumeratorIndex = -1; _currentEnumerator = null; } #endregion private void MoveToNextEnumerator() { _currentEnumeratorIndex++; _currentEnumerator = _allEnumerators[_currentEnumeratorIndex]; } /// <summary> /// Check if current index referencing the enumerator in the list /// is within bounds. /// </summary> /// <returns></returns> private bool IsWithinBounds() { return _currentEnumeratorIndex > -1 && _currentEnumeratorIndex < _allEnumerators.Count; } } }
27.326531
99
0.561862
[ "MIT" ]
joelverhagen/Knapcode.CommonLibrary.NET
src/Lib/CommonLibrary.NET/Collections/EnumeratorMulti.cs
4,019
C#
using System; namespace Microsoft.VisualStudio.Utilities { /// <summary> /// Represents a single scope of a context of executing potentially long running operation on the UI thread. /// Scopes allow multiple components running within an operation to share the same context. /// </summary> public interface IUIThreadOperationScope : IDisposable { /// <summary> /// Gets or sets whether the operation can be cancelled. /// </summary> bool AllowCancellation { get; set; } /// <summary> /// Gets user readable operation description. /// </summary> string Description { get; set; } /// <summary> /// The <see cref="IUIThreadOperationContext" /> owning this scope instance. /// </summary> IUIThreadOperationContext Context { get; } /// <summary> /// Progress tracker instance to report operation progress. /// </summary> IProgress<ProgressInfo> Progress { get; } } #pragma warning disable CA1815 // Override equals and operator equals on value types /// <summary> /// Represents an update of a progress. /// </summary> public struct ProgressInfo #pragma warning restore CA1815 // Override equals and operator equals on value types { /// <summary> /// A number of already completed items. /// </summary> public int CompletedItems { get; } /// <summary> /// A total number if items. /// </summary> public int TotalItems { get; } /// <summary> /// Creates a new instance of the <see cref="ProgressInfo"/> struct. /// </summary> /// <param name="completedItems">A number of already completed items.</param> /// <param name="totalItems">A total number if items.</param> public ProgressInfo(int completedItems, int totalItems) { this.CompletedItems = completedItems; this.TotalItems = totalItems; } } }
33.295082
112
0.605613
[ "MIT" ]
AmadeusW/vs-editor-api
src/Editor/Text/Def/TextUI/Utilities/IUIThreadOperationScope.cs
2,033
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.AspNetCore.Routing.Constraints; public class FileNameRouteConstraintTest { public static TheoryData<object> FileNameData { get { return new TheoryData<object>() { "hello.txt", "hello.txt.jpg", "/hello.t", "/////hello.x", "a/b/c/d.e", "a/b./.c/d.e", ".gitnore", ".a", "/.......a" }; } } [Theory] [MemberData(nameof(FileNameData))] public void Match_RouteValue_IsFileName(object value) { // Arrange var constraint = new FileNameRouteConstraint(); var values = new RouteValueDictionary(); values.Add("path", value); // Act var result = constraint.Match(httpContext: null, route: null, "path", values, RouteDirection.IncomingRequest); // Assert Assert.True(result); } public static TheoryData<object> NonFileNameData { get { return new TheoryData<object>() { null, string.Empty, "/", ".", "..........", "hello.", "/hello", "//", "//b.c/", "/////hello.", "a/b./.c/d.", }; } } [Theory] [MemberData(nameof(NonFileNameData))] public void Match_RouteValue_IsNotFileName(object value) { // Arrange var constraint = new FileNameRouteConstraint(); var values = new RouteValueDictionary(); values.Add("path", value); // Act var result = constraint.Match(httpContext: null, route: null, "path", values, RouteDirection.IncomingRequest); // Assert Assert.False(result); } [Fact] public void Match_MissingValue_IsNotFileName() { // Arrange var constraint = new FileNameRouteConstraint(); var values = new RouteValueDictionary(); // Act var result = constraint.Match(httpContext: null, route: null, "path", values, RouteDirection.IncomingRequest); // Assert Assert.False(result); } }
26.164948
118
0.487786
[ "MIT" ]
3ejki/aspnetcore
src/Http/Routing/test/UnitTests/Constraints/FileNameRouteConstraintTest.cs
2,538
C#
namespace Xamarin.Essentials { public static partial class AppInfo { static string PlatformGetPackageName() => throw ExceptionUtils.NotSupportedOrImplementedException; static string PlatformGetName() => throw ExceptionUtils.NotSupportedOrImplementedException; static string PlatformGetVersionString() => throw ExceptionUtils.NotSupportedOrImplementedException; static string PlatformGetBuild() => throw ExceptionUtils.NotSupportedOrImplementedException; static void PlatformShowSettingsUI() => throw ExceptionUtils.NotSupportedOrImplementedException; static AppTheme PlatformRequestedTheme() => throw ExceptionUtils.NotSupportedOrImplementedException; } }
40.111111
108
0.786704
[ "MIT" ]
1Cor125/Essentials
Xamarin.Essentials/AppInfo/AppInfo.netstandard.cs
724
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Infusion.Packets; namespace Infusion.LegacyApi.Tests.Packets { public static class SpeechPackets { public static Packet FailureMessageFromServer = new Packet(0xAE, new byte[] { 0xAE, 0x00, 0x52, 0x00, 0x00, 0x00, 0x01, 0x01, 0x90, 0x03, 0x02, 0xB2, 0x00, 0x03, 0x45, 0x4E, 0x55, 0x00, 0x64, 0x64, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x00, 0x61, 0x00, 0x69, 0x00, 0x6C, 0x00, 0x75, 0x00, 0x72, 0x00, 0x65, 0x00, 0x20, 0x00, 0x6D, 0x00, 0x65, 0x00, 0x73, 0x00, 0x73, 0x00, 0x61, 0x00, 0x67, 0x00, 0x65, 0x00, 0x00, 0xCF, 0x3C, }); } }
39.521739
107
0.630363
[ "MIT" ]
3HMonkey/Infusion
Infusion.LegacyApi.Tests/Packets/SpeechPackets.cs
911
C#
using cherryflavored.net; using cherryflavored.net.ExtensionMethods.System; using System.Collections.Generic; using System.Linq; using System.Net.Mime; using System.Web; using System.Xml.Linq; namespace silkveil.net.Mappings { /// <summary> /// Contains methods for mapping an filename to a mimetype /// </summary> public static class MimeTypeMapping { /// <summary> /// Contains the extension for the default mimetype. /// </summary> private static string _defaultKey = "*"; /// <summary> /// Contains the mappings of extensions to the according mimetypes. /// </summary> private static readonly Dictionary<string, ContentType> _extensionToMimeType = CreateMimeTypeMappings(); /// <summary> /// Creates the mapping list for the mimetypes. /// </summary> /// <returns></returns> private static Dictionary<string, ContentType> CreateMimeTypeMappings() { // Load the mime types and return them to the caller. return (from mimeType in XElement.Load(HttpContext.Current.Server.MapPath("~/App_Data/Configuration/MimeTypes.xml")).Elements("mimeType") select new { Extension = mimeType.Attribute("extension").Value, ContentType = new ContentType(mimeType.Attribute("value").Value) }).Union(new[] {new { Extension = "*", ContentType = new ContentType("application/octet-stream") }}).ToDictionary(mimeType => mimeType.Extension, mimeType => mimeType.ContentType); } /// <summary> /// Gets a mimetype for the extension contained in the fileName /// If on extension available, or the extension is not in the dictionary, /// octet-stream is returned (forces download). /// </summary> /// <param name="fileName">The filename</param> /// <returns>The mimetype for the extension of the filename</returns> public static ContentType GetMimeTypeMapping(string fileName) { fileName = Enforce.NotNullOrEmpty(fileName, () => fileName); // Get the extension. string extension = GetFileExtension(fileName); // Check whether an extension was found. If not, return the default mimetype. if (extension.IsNullOrEmpty()) { return _extensionToMimeType[_defaultKey]; } // Check whether the extension is contained within the dictionary. If not, return the // default mimetype. if (!_extensionToMimeType.ContainsKey(extension)) { return _extensionToMimeType[_defaultKey]; } // Else return the appropriate mimetype. return _extensionToMimeType[extension]; } /// <summary> /// Get the file extension from a given filename / path. /// </summary> /// <param name="fileName">The filename.</param> /// <returns>The extension without the leading dot.</returns> private static string GetFileExtension(string fileName) { fileName = Enforce.NotNullOrEmpty(fileName, () => fileName); // Get the index of the last dot. int index = fileName.LastIndexOf('.'); // If no extension was found, return an empty string to the caller. if (index == -1 || index == fileName.Length) { return ""; } // Otherwise, return the extension without the leading dot. return fileName.Substring(index).TrimStart('.'); } } }
38.643564
147
0.569818
[ "Unlicense", "MIT" ]
peterbucher/silkveil
silkveil.net Classic/silkveil.net/Mappings/MimeTypeMapping.cs
3,905
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Networking.NetworkOperators { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented] #endif public partial class MobileBroadbandCellGsm { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public int? BaseStationId { get { throw new global::System.NotImplementedException("The member int? MobileBroadbandCellGsm.BaseStationId is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public int? CellId { get { throw new global::System.NotImplementedException("The member int? MobileBroadbandCellGsm.CellId is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public int? ChannelNumber { get { throw new global::System.NotImplementedException("The member int? MobileBroadbandCellGsm.ChannelNumber is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public int? LocationAreaCode { get { throw new global::System.NotImplementedException("The member int? MobileBroadbandCellGsm.LocationAreaCode is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public string ProviderId { get { throw new global::System.NotImplementedException("The member string MobileBroadbandCellGsm.ProviderId is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public double? ReceivedSignalStrengthInDBm { get { throw new global::System.NotImplementedException("The member double? MobileBroadbandCellGsm.ReceivedSignalStrengthInDBm is not implemented in Uno."); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public int? TimingAdvanceInBitPeriods { get { throw new global::System.NotImplementedException("The member int? MobileBroadbandCellGsm.TimingAdvanceInBitPeriods is not implemented in Uno."); } } #endif // Forced skipping of method Windows.Networking.NetworkOperators.MobileBroadbandCellGsm.BaseStationId.get // Forced skipping of method Windows.Networking.NetworkOperators.MobileBroadbandCellGsm.CellId.get // Forced skipping of method Windows.Networking.NetworkOperators.MobileBroadbandCellGsm.ChannelNumber.get // Forced skipping of method Windows.Networking.NetworkOperators.MobileBroadbandCellGsm.LocationAreaCode.get // Forced skipping of method Windows.Networking.NetworkOperators.MobileBroadbandCellGsm.ProviderId.get // Forced skipping of method Windows.Networking.NetworkOperators.MobileBroadbandCellGsm.ReceivedSignalStrengthInDBm.get // Forced skipping of method Windows.Networking.NetworkOperators.MobileBroadbandCellGsm.TimingAdvanceInBitPeriods.get } }
46.730337
153
0.747055
[ "Apache-2.0" ]
AbdalaMask/uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Networking.NetworkOperators/MobileBroadbandCellGsm.cs
4,159
C#
using System; using UnityEngine.Events; using UnityEngine.Rendering; namespace UnityEngine.UI { public abstract class MaskableGraphic : Graphic, IClippable, IMaskable, IMaterialModifier { [NonSerialized] protected bool m_ShouldRecalculateStencil = true; [NonSerialized] protected Material m_MaskMaterial; [NonSerialized] private RectMask2D m_ParentMask; // m_Maskable is whether this graphic is allowed to be masked or not. It has the matching public property maskable. // The default for m_Maskable is true, so graphics under a mask are masked out of the box. // The maskable property can be turned off from script by the user if masking is not desired. // m_IncludeForMasking is whether we actually consider this graphic for masking or not - this is an implementation detail. // m_IncludeForMasking should only be true if m_Maskable is true AND a parent of the graphic has an IMask component. // Things would still work correctly if m_IncludeForMasking was always true when m_Maskable is, but performance would suffer. [NonSerialized] private bool m_Maskable = true; [NonSerialized] [Obsolete("Not used anymore.", true)] protected bool m_IncludeForMasking = false; [Serializable] public class CullStateChangedEvent : UnityEvent<bool> {} // Event delegates triggered on click. [SerializeField] private CullStateChangedEvent m_OnCullStateChanged = new CullStateChangedEvent(); public CullStateChangedEvent onCullStateChanged { get { return m_OnCullStateChanged; } set { m_OnCullStateChanged = value; } } public bool maskable { get { return m_Maskable; } set { if (value == m_Maskable) return; m_Maskable = value; m_ShouldRecalculateStencil = true; SetMaterialDirty(); } } [NonSerialized] [Obsolete("Not used anymore", true)] protected bool m_ShouldRecalculate = true; [NonSerialized] protected int m_StencilValue; public virtual Material GetModifiedMaterial(Material baseMaterial) { var toUse = baseMaterial; if (m_ShouldRecalculateStencil) { var rootCanvas = MaskUtilities.FindRootSortOverrideCanvas(transform); m_StencilValue = maskable ? MaskUtilities.GetStencilDepth(transform, rootCanvas) : 0; m_ShouldRecalculateStencil = false; } // if we have a enabled Mask component then it will // generate the mask material. This is an optimisation // it adds some coupling between components though :( Mask maskComponent = GetComponent<Mask>(); if (m_StencilValue > 0 && (maskComponent == null || !maskComponent.IsActive())) { var maskMat = StencilMaterial.Add(toUse, (1 << m_StencilValue) - 1, StencilOp.Keep, CompareFunction.Equal, ColorWriteMask.All, (1 << m_StencilValue) - 1, 0); StencilMaterial.Remove(m_MaskMaterial); m_MaskMaterial = maskMat; toUse = m_MaskMaterial; } return toUse; } public virtual void Cull(Rect clipRect, bool validRect) { var cull = !validRect || !clipRect.Overlaps(rootCanvasRect, true); UpdateCull(cull); } private void UpdateCull(bool cull) { var cullingChanged = canvasRenderer.cull != cull; canvasRenderer.cull = cull; if (cullingChanged) { UISystemProfilerApi.AddMarker("MaskableGraphic.cullingChanged", this); m_OnCullStateChanged.Invoke(cull); SetVerticesDirty(); } } public virtual void SetClipRect(Rect clipRect, bool validRect) { if (validRect) canvasRenderer.EnableRectClipping(clipRect); else canvasRenderer.DisableRectClipping(); } protected override void OnEnable() { base.OnEnable(); m_ShouldRecalculateStencil = true; UpdateClipParent(); SetMaterialDirty(); if (GetComponent<Mask>() != null) { MaskUtilities.NotifyStencilStateChanged(this); } } protected override void OnDisable() { base.OnDisable(); m_ShouldRecalculateStencil = true; SetMaterialDirty(); UpdateClipParent(); StencilMaterial.Remove(m_MaskMaterial); m_MaskMaterial = null; if (GetComponent<Mask>() != null) { MaskUtilities.NotifyStencilStateChanged(this); } } #if UNITY_EDITOR protected override void OnValidate() { base.OnValidate(); m_ShouldRecalculateStencil = true; UpdateClipParent(); SetMaterialDirty(); } #endif protected override void OnTransformParentChanged() { base.OnTransformParentChanged(); if (!isActiveAndEnabled) return; m_ShouldRecalculateStencil = true; UpdateClipParent(); SetMaterialDirty(); } [Obsolete("Not used anymore.", true)] public virtual void ParentMaskStateChanged() {} protected override void OnCanvasHierarchyChanged() { base.OnCanvasHierarchyChanged(); if (!isActiveAndEnabled) return; m_ShouldRecalculateStencil = true; UpdateClipParent(); SetMaterialDirty(); } readonly Vector3[] m_Corners = new Vector3[4]; private Rect rootCanvasRect { get { rectTransform.GetWorldCorners(m_Corners); if (canvas) { Canvas rootCanvas = canvas.rootCanvas; for (int i = 0; i < 4; ++i) m_Corners[i] = rootCanvas.transform.InverseTransformPoint(m_Corners[i]); } return new Rect(m_Corners[0].x, m_Corners[0].y, m_Corners[2].x - m_Corners[0].x, m_Corners[2].y - m_Corners[0].y); } } private void UpdateClipParent() { var newParent = (maskable && IsActive()) ? MaskUtilities.GetRectMaskForClippable(this) : null; // if the new parent is different OR is now inactive if (m_ParentMask != null && (newParent != m_ParentMask || !newParent.IsActive())) { m_ParentMask.RemoveClippable(this); UpdateCull(false); } // don't re-add it if the newparent is inactive if (newParent != null && newParent.IsActive()) newParent.AddClippable(this); m_ParentMask = newParent; } public virtual void RecalculateClipping() { UpdateClipParent(); } public virtual void RecalculateMasking() { m_ShouldRecalculateStencil = true; SetMaterialDirty(); } } }
32.552174
173
0.572325
[ "MIT" ]
CyndaquilDAC/uGUI
UnityEngine.UI/UI/Core/MaskableGraphic.cs
7,487
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DiagnosticAnalyzerAttributeAnalyzer : DiagnosticAnalyzerCorrectnessAnalyzer { private static readonly LocalizableString s_localizableTitleMissingAttribute = new LocalizableResourceString(nameof(CodeAnalysisDiagnosticsResources.MissingDiagnosticAnalyzerAttributeTitle), CodeAnalysisDiagnosticsResources.ResourceManager, typeof(CodeAnalysisDiagnosticsResources)); private static readonly LocalizableString s_localizableMessageMissingAttribute = new LocalizableResourceString(nameof(CodeAnalysisDiagnosticsResources.MissingAttributeMessage), CodeAnalysisDiagnosticsResources.ResourceManager, typeof(CodeAnalysisDiagnosticsResources), WellKnownTypeNames.MicrosoftCodeAnalysisDiagnosticsDiagnosticAnalyzerAttribute); private static readonly LocalizableString s_localizableDescriptionMissingAttribute = new LocalizableResourceString(nameof(CodeAnalysisDiagnosticsResources.MissingDiagnosticAnalyzerAttributeDescription), CodeAnalysisDiagnosticsResources.ResourceManager, typeof(CodeAnalysisDiagnosticsResources)); public static readonly DiagnosticDescriptor MissingDiagnosticAnalyzerAttributeRule = new DiagnosticDescriptor( DiagnosticIds.MissingDiagnosticAnalyzerAttributeRuleId, s_localizableTitleMissingAttribute, s_localizableMessageMissingAttribute, DiagnosticCategory.MicrosoftCodeAnalysisCorrectness, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: s_localizableDescriptionMissingAttribute, customTags: WellKnownDiagnosticTags.Telemetry); private static readonly LocalizableString s_localizableTitleAddLanguageSupportToAnalyzer = new LocalizableResourceString(nameof(CodeAnalysisDiagnosticsResources.AddLanguageSupportToAnalyzerTitle), CodeAnalysisDiagnosticsResources.ResourceManager, typeof(CodeAnalysisDiagnosticsResources)); private static readonly LocalizableString s_localizableMessageAddLanguageSupportToAnalyzer = new LocalizableResourceString(nameof(CodeAnalysisDiagnosticsResources.AddLanguageSupportToAnalyzerMessage), CodeAnalysisDiagnosticsResources.ResourceManager, typeof(CodeAnalysisDiagnosticsResources)); private static readonly LocalizableString s_localizableDescriptionAddLanguageSupportToAnalyzer = new LocalizableResourceString(nameof(CodeAnalysisDiagnosticsResources.AddLanguageSupportToAnalyzerDescription), CodeAnalysisDiagnosticsResources.ResourceManager, typeof(CodeAnalysisDiagnosticsResources)); public static readonly DiagnosticDescriptor AddLanguageSupportToAnalyzerRule = new DiagnosticDescriptor( DiagnosticIds.AddLanguageSupportToAnalyzerRuleId, s_localizableTitleAddLanguageSupportToAnalyzer, s_localizableMessageAddLanguageSupportToAnalyzer, DiagnosticCategory.MicrosoftCodeAnalysisCorrectness, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: s_localizableDescriptionAddLanguageSupportToAnalyzer, customTags: WellKnownDiagnosticTags.Telemetry); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(MissingDiagnosticAnalyzerAttributeRule, AddLanguageSupportToAnalyzerRule); #pragma warning disable RS1025 // Configure generated code analysis public override void Initialize(AnalysisContext context) #pragma warning restore RS1025 // Configure generated code analysis { context.EnableConcurrentExecution(); base.Initialize(context); } [SuppressMessage("AnalyzerPerformance", "RS1012:Start action has no registered actions.", Justification = "Method returns an analyzer that is registered by the caller.")] protected override DiagnosticAnalyzerSymbolAnalyzer GetDiagnosticAnalyzerSymbolAnalyzer(CompilationStartAnalysisContext compilationContext, INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute) { var attributeUsageAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttributeUsageAttribute); return new AttributeAnalyzer(diagnosticAnalyzer, diagnosticAnalyzerAttribute, attributeUsageAttribute); } private sealed class AttributeAnalyzer : DiagnosticAnalyzerSymbolAnalyzer { private const string CSharpCompilationFullName = @"Microsoft.CodeAnalysis.CSharp.CSharpCompilation"; private const string BasicCompilationFullName = @"Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation"; private readonly INamedTypeSymbol? _attributeUsageAttribute; public AttributeAnalyzer(INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute, INamedTypeSymbol? attributeUsageAttribute) : base(diagnosticAnalyzer, diagnosticAnalyzerAttribute) { _attributeUsageAttribute = attributeUsageAttribute; } protected override void AnalyzeDiagnosticAnalyzer(SymbolAnalysisContext symbolContext) { var namedType = (INamedTypeSymbol)symbolContext.Symbol; if (namedType.IsAbstract) { return; } // 1) MissingDiagnosticAnalyzerAttributeRule: DiagnosticAnalyzer has no DiagnosticAnalyzerAttribute. // 2) AddLanguageSupportToAnalyzerRule: For analyzer supporting only one of C# or VB languages, detect if it can support the other language. var hasAttribute = false; SyntaxNode? attributeSyntax = null; bool supportsCSharp = false; bool supportsVB = false; var namedTypeAttributes = namedType.GetApplicableAttributes(_attributeUsageAttribute); foreach (AttributeData attribute in namedTypeAttributes) { if (attribute.AttributeClass.DerivesFrom(DiagnosticAnalyzerAttribute)) { // Bail out for the case where analyzer type derives from a sub-type in different assembly, and the sub-type has the diagnostic analyzer attribute. if (attribute.ApplicationSyntaxReference == null) { return; } hasAttribute = true; // The attribute constructor's signature is "(string, params string[])", // so process both string arguments and string[] arguments. foreach (TypedConstant arg in attribute.ConstructorArguments) { CheckLanguage(arg, ref supportsCSharp, ref supportsVB); if (arg.Kind == TypedConstantKind.Array) { foreach (TypedConstant element in arg.Values) { CheckLanguage(element, ref supportsCSharp, ref supportsVB); } } } attributeSyntax = attribute.ApplicationSyntaxReference.GetSyntax(symbolContext.CancellationToken); } } if (!hasAttribute) { Diagnostic diagnostic = namedType.CreateDiagnostic(MissingDiagnosticAnalyzerAttributeRule); symbolContext.ReportDiagnostic(diagnostic); } else if (supportsCSharp ^ supportsVB) { RoslynDebug.Assert(attributeSyntax != null); // If the analyzer assembly doesn't reference either C# or VB CodeAnalysis assemblies, // then the analyzer is pretty likely a language-agnostic analyzer. Compilation compilation = symbolContext.Compilation; string compilationTypeNameToCheck = supportsCSharp ? CSharpCompilationFullName : BasicCompilationFullName; INamedTypeSymbol? compilationType = compilation.GetOrCreateTypeByMetadataName(compilationTypeNameToCheck); if (compilationType == null) { string missingLanguage = supportsCSharp ? LanguageNames.VisualBasic : LanguageNames.CSharp; Diagnostic diagnostic = attributeSyntax.CreateDiagnostic(AddLanguageSupportToAnalyzerRule, namedType.Name, missingLanguage); symbolContext.ReportDiagnostic(diagnostic); } } } } private static void CheckLanguage(TypedConstant argument, ref bool supportsCSharp, ref bool supportsVB) { if (argument.Kind == TypedConstantKind.Primitive && argument.Type != null && argument.Type.SpecialType == SpecialType.System_String) { string supportedLanguage = (string)argument.Value; if (supportedLanguage == LanguageNames.CSharp) { supportsCSharp = true; } else if (supportedLanguage == LanguageNames.VisualBasic) { supportsVB = true; } } } } }
60.412121
357
0.691011
[ "Apache-2.0" ]
Atrejoe/roslyn-analyzers
src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAttributeAnalyzer.cs
9,970
C#
using System; using System.Web; using CMS; using CMS.DataEngine; using CMS.Helpers; using CMS.WebServices; using CMS.Base; using CMS.UIControls; using MAMR.RestHashTracker; [assembly: RegisterModule(typeof(MamrRestHashTrackerModule))] public class MamrRestHashTrackerModule : Module { /// <summary> /// Constructor for module /// </summary> public MamrRestHashTrackerModule() : base("MamrRestHashTrackerModule"){} /// <summary> /// Initializes the module. Called when the application starts. /// </summary> protected override void OnInit() { base.OnInit(); //Events for the HashInfo object. This is how we handle generating the read only URL on insert and update. HashInfo.TYPEINFO.Events.Insert.Before += HashGenerateSecureUrl; HashInfo.TYPEINFO.Events.Update.Before += HashGenerateSecureUrl; //Couple of custom transformations for the unigrid used in the list view of the REST Hash Tracker module. UniGridTransformations.Global.RegisterTransformation("#getresthashtrackerlink", GetRestHashTrackerLink); UniGridTransformations.Global.RegisterTransformation("#getresthashtrackertype", GetRestHashTrackerType); } /// <summary> /// Generate the secure URL (original URL with hash) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void HashGenerateSecureUrl(object sender, ObjectEventArgs e) { var url = e.Object.GetStringValue("HashUrl", string.Empty); var hashSecureUrl = ""; var urlWithoutHash = URLHelper.RemoveParameterFromUrl(url, "hash"); var newUrl = HttpUtility.UrlDecode(urlWithoutHash); var query = URLHelper.GetQuery(newUrl).TrimStart('?'); int index = newUrl.IndexOfCSafe("/rest", true); if (index >= 0) { var domain = URLHelper.GetDomain(newUrl); newUrl = URLHelper.RemoveQuery(newUrl.Substring(index)); var rewritten = BaseRESTService.RewriteRESTUrl(newUrl, query, domain, "GET"); newUrl = rewritten[0].TrimStart('~') + "?" + rewritten[1]; hashSecureUrl += URLHelper.AddParameterToUrl(urlWithoutHash, "hash", RESTService.GetHashForURL(newUrl, domain)) + Environment.NewLine; e.Object.SetValue("HashSecureUrl", hashSecureUrl); } } /// <summary> /// Create HTML link. /// </summary> /// <param name="parameter">Value from the UniGrid row.</param> /// <returns>HTML Link</returns> private static object GetRestHashTrackerLink(object parameter) { var link = ValidationHelper.GetString(parameter, string.Empty); return string.Format("<a href=\"{0}\" target=\"_blank\">Open</a>", link, link); } /// <summary> /// Generate a response type label. /// </summary> /// <param name="parameter">Value from the UniGrid row.</param> /// <returns>Label - "JSON" or "XML" (default)</returns> private static object GetRestHashTrackerType(object parameter) { var link = ValidationHelper.GetString(parameter, string.Empty); if (link.ToLower().Contains("format=json")) { return "JSON"; } return "XML"; } }
35.747253
146
0.658469
[ "MIT" ]
meandmyrobot/REST-Hash-Tracker
RestHashTracker/MamrRestHashTrackerModule.cs
3,255
C#
namespace DSInternals.PowerShell.Commands { using System; using System.Management.Automation; using System.Security.Cryptography.X509Certificates; using DSInternals.Common; using DSInternals.Common.Data; [Cmdlet(VerbsCommon.Get, "ADKeyCredential", DefaultParameterSetName = ParamSetFromCertificate)] [OutputType(new Type[] { typeof(KeyCredential) })] public class GetADKeyCredentialCommand : PSCmdlet { #region Parameters private const string ParamSetFromCertificate = "FromCertificate"; private const string ParamSetFromBinary = "FromBinary"; private const string ParamSetFromDNBinary = "FromDNBinary"; [Parameter( Mandatory = true, Position = 0, ParameterSetName = ParamSetFromDNBinary, ValueFromPipeline = true )] public string DNWithBinaryData { get; set; } [Parameter( Mandatory = true, ParameterSetName = ParamSetFromBinary )] [AcceptHexString] public byte[] BinaryData { get; set; } [Parameter( Mandatory = true, Position = 0, ParameterSetName = ParamSetFromCertificate )] public X509Certificate2 Certificate { get; set; } [Parameter( Mandatory = true, Position = 1, ParameterSetName = ParamSetFromCertificate )] public Guid DeviceId { get; set; } #endregion Parameters #region Cmdlet Overrides protected override void ProcessRecord() { KeyCredential keyCredential; switch(this.ParameterSetName) { case ParamSetFromDNBinary: keyCredential = new KeyCredential(this.DNWithBinaryData.FromDNWithBinary()); break; case ParamSetFromBinary: keyCredential = new KeyCredential(this.BinaryData); break; case ParamSetFromCertificate: default: byte[] publicKey = this.Certificate.ExportPublicKeyBlob(); keyCredential = new KeyCredential(publicKey, this.DeviceId); break; } this.WriteObject(keyCredential); } #endregion Cmdlet Overrides } }
28.505618
99
0.55341
[ "MIT" ]
0xh4di/DSInternals
Src/DSInternals.PowerShell/Commands/Misc/GetADKeyCredential.cs
2,539
C#
using AdsGoFast.SqlServer; using AdsGoFast.TaskMetaData; using Cronos; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace AdsGoFast { public static class PrepareFrameworkTasksTimerTrigger { [FunctionName("PrepareFrameworkTasksTimerTrigger")] public static async Task Run([TimerTrigger("0 */2 * * * *")] TimerInfo myTimer, ILogger log, ExecutionContext context) { Guid ExecutionId = context.InvocationId; if (Shared.GlobalConfigs.GetBoolConfig("EnablePrepareFrameworkTasks")) { using (FrameworkRunner FR = new FrameworkRunner(log, ExecutionId)) { FrameworkRunner.FrameworkRunnerWorker worker = PrepareFrameworkTasks.PrepareFrameworkTasksCore; FrameworkRunner.FrameworkRunnerResult result = FR.Invoke("PrepareFrameworkTasksHttpTrigger", worker); } } } } public static class PrepareFrameworkTasks { public static dynamic PrepareFrameworkTasksCore(Logging logging) { TaskMetaDataDatabase TMD = new TaskMetaDataDatabase(); TMD.ExecuteSql(string.Format("Insert into Execution values ('{0}', '{1}', '{2}')", logging.DefaultActivityLogItem.ExecutionUid, DateTimeOffset.Now.ToString("u"), DateTimeOffset.Now.AddYears(999).ToString("u"))); //Check status of running pipelines and calculate available "slots" based on max concurrency settings short _FrameworkWideMaxConcurrency = Shared.GlobalConfigs.GetInt16Config("FrameworkWideMaxConcurrency"); //ToDo: Write Pipelines that need to be checked to Queue for now I have just reduced to only those tasks that have been running for longer than x minutes. //CheckLongRunningPipelines(logging); //Get Count of All runnning pipelines directly from the database short _RunnningPipelines = CountRunnningPipelines(logging); short _AvailableConcurrencySlots = (short)(_FrameworkWideMaxConcurrency - _RunnningPipelines); //Generate new task instances based on task master and schedules CreateTaskInstance(logging); //Is there is Available Slots Proceed if (_AvailableConcurrencySlots > 0) { List<AdsGoFast.TaskMetaData.TaskGroup> _TaskGroups = TaskGroupsStatic.GetActive(); if (_TaskGroups.Count > 0) { short _ConcurrencySlotsAllocated = 0; short _DefaultTasksPerGroup = 0; short _DistributionLoopCounter = 1; //Distribute Concurrency Slots while (_AvailableConcurrencySlots > 0) { DistributeConcurrencySlots(ref _TaskGroups, ref _DefaultTasksPerGroup, ref _ConcurrencySlotsAllocated, ref _AvailableConcurrencySlots, _DistributionLoopCounter); _DistributionLoopCounter += 1; } Table TempTarget = new Table { Schema = "dbo", Name = "#TempGroups" + logging.DefaultActivityLogItem.ExecutionUid.ToString() }; SqlConnection _con = TMD.GetSqlConnection(); TMD.BulkInsert(_TaskGroups.ToDataTable(), TempTarget, true, _con); Dictionary<string, string> _params = new Dictionary<string, string> { { "TempTable", TempTarget.QuotedSchemaAndName() } }; string _sql = GenerateSQLStatementTemplates.GetSQL(Shared.GlobalConfigs.GetStringConfig("SQLTemplateLocation"), "UpdateTaskInstancesWithTaskRunner", _params); TMD.ExecuteSql(_sql, _con); } } return new { }; } public static void DistributeConcurrencySlots(ref List<AdsGoFast.TaskMetaData.TaskGroup> _TaskGroups, ref short _DefaultTasksPerGroup, ref short _ConcurrencySlotsAllocated, ref short _AvailableConcurrencySlots, short DistributionLoopCount) { short TaskGroupLoopCount = 1; short MaxTaskGroupIndex = 32767; //Ensure that we have at least one concurrency slot per group if (_TaskGroups.Count > _AvailableConcurrencySlots) { MaxTaskGroupIndex = _AvailableConcurrencySlots; _DefaultTasksPerGroup = 1; //List<AdsGoFast.TaskMetaData.TaskGroup> _NewTaskGroups = _TaskGroups.Take<AdsGoFast.TaskMetaData.TaskGroup>(_AvailableConcurrencySlots).ToList(); //_TaskGroups = _NewTaskGroups; } else { _DefaultTasksPerGroup = (short)Math.Floor((decimal)(_AvailableConcurrencySlots / _TaskGroups.Count)); } foreach (TaskGroup _TaskGroup in _TaskGroups) { if (DistributionLoopCount == 1) { _TaskGroup.TasksUnAllocated = _TaskGroup.TaskCount; } if (_TaskGroup.TasksUnAllocated < _DefaultTasksPerGroup) { _ConcurrencySlotsAllocated += _TaskGroup.TaskCount; _AvailableConcurrencySlots -= _TaskGroup.TaskCount; _TaskGroup.ConcurrencySlotsAllocated += _TaskGroup.TaskCount; _TaskGroup.TasksUnAllocated -= _TaskGroup.TaskCount; } else { _ConcurrencySlotsAllocated += _DefaultTasksPerGroup; _AvailableConcurrencySlots -= _DefaultTasksPerGroup; _TaskGroup.ConcurrencySlotsAllocated += _DefaultTasksPerGroup; _TaskGroup.TasksUnAllocated -= _DefaultTasksPerGroup; } TaskGroupLoopCount += 1; //Break the foreach if we have hit the max if (TaskGroupLoopCount >= MaxTaskGroupIndex) { break; } } } public static void CreateTaskInstance(Logging logging) { logging.LogInformation("Create ScheduleInstance called."); TaskMetaDataDatabase TMD = new TaskMetaDataDatabase(); DateTimeOffset _date = DateTimeOffset.Now; DataTable dtScheduleInstance = new DataTable(); dtScheduleInstance.Columns.Add(new DataColumn("ScheduleMasterId", typeof(long))); dtScheduleInstance.Columns.Add(new DataColumn("ScheduledDateUtc", typeof(DateTime))); dtScheduleInstance.Columns.Add(new DataColumn("ScheduledDateTimeOffset", typeof(DateTimeOffset))); dtScheduleInstance.Columns.Add(new DataColumn("ActiveYN", typeof(bool))); dynamic resScheduleInstance = TMD.GetSqlConnection().QueryWithRetry(@" Select SM.ScheduleMasterId, SM.ScheduleCronExpression, Coalesce(SI.MaxScheduledDateTimeOffset,cast('1900-01-01' as datetimeoffset)) as MaxScheduledDateTimeOffset from ScheduleMaster SM join ( Select distinct ScheduleMasterId from TaskMaster TM where TM.ActiveYN = 1) TM on TM.ScheduleMasterId = SM.ScheduleMasterId left outer join ( Select ScheduleMasterId, Max(ScheduledDateTimeOffset) MaxScheduledDateTimeOffset From ScheduleInstance Where ActiveYN = 1 Group By ScheduleMasterId ) SI on SM.ScheduleMasterId = SI.ScheduleMasterId Where SM.ActiveYN = 1"); foreach (dynamic _row in resScheduleInstance) { DateTimeOffset? nextUtc; if (_row.ScheduleCronExpression.ToString() == "N/A") { nextUtc = DateTime.UtcNow.AddMinutes(-1); } else { CronExpression _cronExpression = CronExpression.Parse(_row.ScheduleCronExpression.ToString(), CronFormat.IncludeSeconds); nextUtc = _cronExpression.GetNextOccurrence(_row.MaxScheduledDateTimeOffset, TimeZoneInfo.Utc); } if (nextUtc?.DateTime <= DateTime.UtcNow) { DataRow dr = dtScheduleInstance.NewRow(); dr["ScheduleMasterId"] = _row.ScheduleMasterId; dr["ScheduledDateUtc"] = _date.Date; dr["ScheduledDateTimeOffset"] = _date; dr["ActiveYN"] = true; dtScheduleInstance.Rows.Add(dr); } } //Persist TEMP ScheduleInstance SqlConnection _con = TMD.GetSqlConnection(); Table tmpScheduleInstanceTargetTable = new Table { Name = "#Temp" + Guid.NewGuid().ToString() }; TMD.BulkInsert(dtScheduleInstance, tmpScheduleInstanceTargetTable, true, _con); //Create TaskInstance logging.LogInformation("Create TaskInstance called."); DataTable dtTaskInstance = new DataTable(); dtTaskInstance.Columns.Add(new DataColumn("ExecutionUid", typeof(Guid))); dtTaskInstance.Columns.Add(new DataColumn("TaskMasterId", typeof(long))); dtTaskInstance.Columns.Add(new DataColumn("ScheduleInstanceId", typeof(long))); dtTaskInstance.Columns.Add(new DataColumn("ADFPipeline", typeof(string))); dtTaskInstance.Columns.Add(new DataColumn("TaskInstanceJson", typeof(string))); dtTaskInstance.Columns.Add(new DataColumn("LastExecutionStatus", typeof(string))); dtTaskInstance.Columns.Add(new DataColumn("ActiveYN", typeof(bool))); dynamic resTaskInstance = TMD.GetSqlConnection().QueryWithRetry(@"Exec dbo.GetTaskMaster"); DataTable dtTaskTypeMapping = GetTaskTypeMapping(logging); foreach (dynamic _row in resTaskInstance) { DataRow drTaskInstance = dtTaskInstance.NewRow(); logging.DefaultActivityLogItem.TaskInstanceId = _row.TaskInstanceId; logging.DefaultActivityLogItem.TaskMasterId = _row.TaskMasterId; try { dynamic sourceSystemJson = JsonConvert.DeserializeObject(_row.SourceSystemJSON); dynamic taskMasterJson = JsonConvert.DeserializeObject(_row.TaskMasterJSON); dynamic targetSystemJson = JsonConvert.DeserializeObject(_row.TargetSystemJSON); string _ADFPipeline = GetTaskTypeMappingName(logging, _row.TaskExecutionType.ToString(), dtTaskTypeMapping, _row.TaskTypeId, _row.SourceSystemType.ToString(), taskMasterJson?.Source.Type.ToString(), _row.TargetSystemType.ToString(), taskMasterJson?.Target.Type.ToString(), _row.TaskDatafactoryIR); drTaskInstance["TaskMasterId"] = _row.TaskMasterId ?? DBNull.Value; drTaskInstance["ScheduleInstanceId"] = 0;//_row.ScheduleInstanceId == null ? DBNull.Value : _row.ScheduleInstanceId; drTaskInstance["ExecutionUid"] = logging.DefaultActivityLogItem.ExecutionUid; drTaskInstance["ADFPipeline"] = _ADFPipeline; drTaskInstance["LastExecutionStatus"] = "Untried"; drTaskInstance["ActiveYN"] = true; JObject Root = new JObject(); if (_row.SourceSystemType == "ADLS" || _row.SourceSystemType == "Azure Blob") { if (taskMasterJson?.Source.Type.ToString() != "Filelist") { Root["SourceRelativePath"] = TaskInstancesStatic.TransformRelativePath(JObject.Parse(_row.TaskMasterJSON)["Source"]["RelativePath"].ToString(), _date.DateTime); } } if (_row.TargetSystemType == "ADLS" || _row.TargetSystemType == "Azure Blob") { if (JObject.Parse(_row.TaskMasterJSON)["Target"]["RelativePath"] != null) { Root["TargetRelativePath"] = TaskInstancesStatic.TransformRelativePath(JObject.Parse(_row.TaskMasterJSON)["Target"]["RelativePath"].ToString(), _date.DateTime); } } if (JObject.Parse(_row.TaskMasterJSON)["Source"]["IncrementalType"] == "Watermark") { Root["IncrementalField"] = _row.TaskMasterWaterMarkColumn; Root["IncrementalColumnType"] = _row.TaskMasterWaterMarkColumnType; if (_row.TaskMasterWaterMarkColumnType == "DateTime") { Root["IncrementalValue"] = _row.TaskMasterWaterMark_DateTime ?? "1900-01-01"; } else if (_row.TaskMasterWaterMarkColumnType == "BigInt") { Root["IncrementalValue"] = _row.TaskMasterWaterMark_BigInt ?? -1; } } if (Root == null) { drTaskInstance["TaskInstanceJson"] = DBNull.Value; } else { drTaskInstance["TaskInstanceJson"] = Root; } dtTaskInstance.Rows.Add(drTaskInstance); } catch (Exception e) { logging.LogErrors(new Exception(string.Format("Failed to create new task instances for TaskMasterId '{0}'.", logging.DefaultActivityLogItem.TaskInstanceId))); logging.LogErrors(e); } } //Persist TMP TaskInstance Table tmpTaskInstanceTargetTable = new Table { Name = "#Temp" + Guid.NewGuid().ToString() }; TMD.BulkInsert(dtTaskInstance, tmpTaskInstanceTargetTable, true, _con); Dictionary<string, string> SqlParams = new Dictionary<string, string> { { "tmpScheduleInstance", tmpScheduleInstanceTargetTable.QuotedSchemaAndName() }, { "tmpTaskInstance", tmpTaskInstanceTargetTable.QuotedSchemaAndName() } }; string InsertSQL = GenerateSQLStatementTemplates.GetSQL(Shared.GlobalConfigs.GetStringConfig("SQLTemplateLocation"), "InsertScheduleInstance_TaskInstance", SqlParams); _con.ExecuteWithRetry(InsertSQL); _con.Close(); } public static short CountRunnningPipelines(Logging logging) { short _ActivePipelines = ActivePipelines.CountActivePipelines(logging); return _ActivePipelines; } /// <summary> /// Checks for long running pipelines and updates their status in the database /// </summary> /// <param name="logging"></param> /// <returns></returns> public static short CheckLongRunningPipelines(Logging logging) { dynamic _ActivePipelines = ActivePipelines.GetLongRunningPipelines(logging); short RunningPipelines = 0; short FinishedPipelines = 0; DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn("TaskInstanceId", typeof(string))); dt.Columns.Add(new DataColumn("ExecutionUid", typeof(Guid))); dt.Columns.Add(new DataColumn("PipelineName", typeof(string))); dt.Columns.Add(new DataColumn("DatafactorySubscriptionUid", typeof(Guid))); dt.Columns.Add(new DataColumn("DatafactoryResourceGroup", typeof(string))); dt.Columns.Add(new DataColumn("DatafactoryName", typeof(string))); dt.Columns.Add(new DataColumn("RunUid", typeof(Guid))); dt.Columns.Add(new DataColumn("Status", typeof(string))); dt.Columns.Add(new DataColumn("SimpleStatus", typeof(string))); //Check Each Running Pipeline foreach (dynamic _Pipeline in _ActivePipelines) { dynamic _PipelineStatus = CheckPipelineStatus.CheckPipelineStatusMethod(_Pipeline.DatafactorySubscriptionUid.ToString(), _Pipeline.DatafactoryResourceGroup.ToString(), _Pipeline.DatafactoryName.ToString(), _Pipeline.PipelineName.ToString(), _Pipeline.AdfRunUid.ToString(), logging); if (_PipelineStatus["SimpleStatus"].ToString() == "Runnning") { RunningPipelines += 1; } if (_PipelineStatus["SimpleStatus"].ToString() == "Done") { FinishedPipelines += 1; } DataRow dr = dt.NewRow(); dr["TaskInstanceId"] = _Pipeline.TaskInstanceId; dr["ExecutionUid"] = _Pipeline.ExecutionUid; dr["DatafactorySubscriptionUid"] = _Pipeline.DatafactorySubscriptionUid; dr["DatafactoryResourceGroup"] = _Pipeline.DatafactoryResourceGroup; dr["DatafactoryName"] = _Pipeline.DatafactoryName; dr["Status"] = _PipelineStatus["Status"]; dr["SimpleStatus"] = _PipelineStatus["SimpleStatus"]; dr["RunUid"] = (Guid)_PipelineStatus["RunId"]; dr["PipelineName"] = _PipelineStatus["PipelineName"]; dt.Rows.Add(dr); } string TempTableName = "#Temp" + Guid.NewGuid().ToString(); TaskMetaDataDatabase TMD = new TaskMetaDataDatabase(); //Todo: Update both the TaskInstanceExecution and the TaskInstance; TMD.AutoBulkInsertAndMerge(dt, TempTableName, "TaskInstanceExecution"); return RunningPipelines; } public static DataTable GetTaskTypeMapping(Logging logging) { logging.LogDebug("Load TaskTypeMapping called."); TaskMetaDataDatabase TMD = new TaskMetaDataDatabase(); dynamic resTaskTypeMapping = TMD.GetSqlConnection().QueryWithRetry(@"select * from [dbo].[TaskTypeMapping] Where ActiveYN = 1"); DataTable dtTaskTypeMapping = new DataTable(); dtTaskTypeMapping.Columns.Add(new DataColumn("TaskTypeId", typeof(int))); dtTaskTypeMapping.Columns.Add(new DataColumn("MappingType", typeof(string))); dtTaskTypeMapping.Columns.Add(new DataColumn("MappingName", typeof(string))); dtTaskTypeMapping.Columns.Add(new DataColumn("SourceSystemType", typeof(string))); dtTaskTypeMapping.Columns.Add(new DataColumn("SourceType", typeof(string))); dtTaskTypeMapping.Columns.Add(new DataColumn("TargetSystemType", typeof(string))); dtTaskTypeMapping.Columns.Add(new DataColumn("TargetType", typeof(string))); dtTaskTypeMapping.Columns.Add(new DataColumn("TaskDatafactoryIR", typeof(string))); foreach (dynamic _row in resTaskTypeMapping) { DataRow dr = dtTaskTypeMapping.NewRow(); dr["TaskTypeId"] = _row.TaskTypeId; dr["MappingType"] = _row.MappingType; dr["MappingName"] = _row.MappingName; dr["SourceSystemType"] = _row.SourceSystemType; dr["SourceType"] = _row.SourceType; dr["TargetSystemType"] = _row.TargetSystemType; dr["TargetType"] = _row.TargetType; dr["TaskDatafactoryIR"] = _row.TaskDatafactoryIR; dtTaskTypeMapping.Rows.Add(dr); } logging.LogDebug("Load TaskTypeMapping complete."); return dtTaskTypeMapping; } public static string GetTaskTypeMappingName(Logging logging, String MappingType, DataTable dt, int TaskTypeId, string SourceSystemType, string SourceType, string TargetSystemType, string TargetType, string TaskDatafactoryIR) { logging.LogDebug("Get TaskTypeMappingName called."); string _ex = string.Format("MappingType = '{6}' and SourceSystemType = '{0}' and SourceType = '{1}' and TargetSystemType = '{2}' and TargetType = '{3}' and TaskDatafactoryIR = '{4}' and TaskTypeId = {5}", SourceSystemType, SourceType, TargetSystemType, TargetType, TaskDatafactoryIR, TaskTypeId, MappingType); DataRow[] foundRows = dt.Select(_ex); if (foundRows.Count() > 1 || foundRows.Count() == 0) { throw new System.ArgumentException(string.Format("Invalid TypeMapping for SourceSystemType = '{0}' and SourceType = '{1}' and TargetSystemType = '{2}' and TargetType = '{3}' and TaskDatafactoryIR = '{4}'. Mapping returned: {5}", SourceSystemType, SourceType, TargetSystemType, TargetType, TaskDatafactoryIR, foundRows.Count())); } string TypeName = foundRows[0]["MappingName"].ToString(); logging.LogDebug("Get TaskTypeMappingName complete."); return TypeName; } } }
48.523702
344
0.60374
[ "MIT" ]
hboiled/azure-data-services-go-fast-codebase
solution/FunctionApp/PrepareFrameworkTasks.cs
21,496
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.ServiceFabric.Client.Http.Serialization { using System; using System.Collections.Generic; using Microsoft.ServiceFabric.Common; using Newtonsoft.Json; using Newtonsoft.Json.Linq; /// <summary> /// Converter for <see cref="ServiceHealthState" />. /// </summary> internal class ServiceHealthStateConverter { /// <summary> /// Deserializes the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T: Newtonsoft.Json.JsonReader" /> to read from.</param> /// <returns>The object Value.</returns> internal static ServiceHealthState Deserialize(JsonReader reader) { return reader.Deserialize(GetFromJsonProperties); } /// <summary> /// Gets the object from Json properties. /// </summary> /// <param name="reader">The <see cref="T: Newtonsoft.Json.JsonReader" /> to read from, reader must be placed at first property.</param> /// <returns>The object Value.</returns> internal static ServiceHealthState GetFromJsonProperties(JsonReader reader) { var aggregatedHealthState = default(HealthState?); var serviceName = default(ServiceName); do { var propName = reader.ReadPropertyName(); if (string.Compare("AggregatedHealthState", propName, StringComparison.OrdinalIgnoreCase) == 0) { aggregatedHealthState = HealthStateConverter.Deserialize(reader); } else if (string.Compare("ServiceName", propName, StringComparison.OrdinalIgnoreCase) == 0) { serviceName = ServiceNameConverter.Deserialize(reader); } else { reader.SkipPropertyValue(); } } while (reader.TokenType != JsonToken.EndObject); return new ServiceHealthState( aggregatedHealthState: aggregatedHealthState, serviceName: serviceName); } /// <summary> /// Serializes the object to JSON. /// </summary> /// <param name="writer">The <see cref="T: Newtonsoft.Json.JsonWriter" /> to write to.</param> /// <param name="obj">The object to serialize to JSON.</param> internal static void Serialize(JsonWriter writer, ServiceHealthState obj) { // Required properties are always serialized, optional properties are serialized when not null. writer.WriteStartObject(); writer.WriteProperty(obj.AggregatedHealthState, "AggregatedHealthState", HealthStateConverter.Serialize); if (obj.ServiceName != null) { writer.WriteProperty(obj.ServiceName, "ServiceName", ServiceNameConverter.Serialize); } writer.WriteEndObject(); } } }
40.740741
144
0.580303
[ "MIT" ]
Bhaskers-Blu-Org2/service-fabric-client-dotnet
src/Microsoft.ServiceFabric.Client.Http/Generated/Serialization/ServiceHealthStateConverter.cs
3,300
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the pinpoint-sms-voice-v2-2022-03-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.PinpointSMSVoiceV2.Model { /// <summary> /// This is the response object from the DeleteConfigurationSet operation. /// </summary> public partial class DeleteConfigurationSetResponse : AmazonWebServiceResponse { private string _configurationSetArn; private string _configurationSetName; private DateTime? _createdTimestamp; private MessageType _defaultMessageType; private string _defaultSenderId; private List<EventDestination> _eventDestinations = new List<EventDestination>(); /// <summary> /// Gets and sets the property ConfigurationSetArn. /// <para> /// The Amazon Resource Name (ARN) of the deleted configuration set. /// </para> /// </summary> public string ConfigurationSetArn { get { return this._configurationSetArn; } set { this._configurationSetArn = value; } } // Check to see if ConfigurationSetArn property is set internal bool IsSetConfigurationSetArn() { return this._configurationSetArn != null; } /// <summary> /// Gets and sets the property ConfigurationSetName. /// <para> /// The name of the deleted configuration set. /// </para> /// </summary> [AWSProperty(Min=1, Max=64)] public string ConfigurationSetName { get { return this._configurationSetName; } set { this._configurationSetName = value; } } // Check to see if ConfigurationSetName property is set internal bool IsSetConfigurationSetName() { return this._configurationSetName != null; } /// <summary> /// Gets and sets the property CreatedTimestamp. /// <para> /// The time that the deleted configuration set was created in <a href="https://www.epochconverter.com/">UNIX /// epoch time</a> format. /// </para> /// </summary> public DateTime CreatedTimestamp { get { return this._createdTimestamp.GetValueOrDefault(); } set { this._createdTimestamp = value; } } // Check to see if CreatedTimestamp property is set internal bool IsSetCreatedTimestamp() { return this._createdTimestamp.HasValue; } /// <summary> /// Gets and sets the property DefaultMessageType. /// <para> /// The default message type of the configuration set that was deleted. /// </para> /// </summary> public MessageType DefaultMessageType { get { return this._defaultMessageType; } set { this._defaultMessageType = value; } } // Check to see if DefaultMessageType property is set internal bool IsSetDefaultMessageType() { return this._defaultMessageType != null; } /// <summary> /// Gets and sets the property DefaultSenderId. /// <para> /// The default Sender ID of the configuration set that was deleted. /// </para> /// </summary> [AWSProperty(Min=1, Max=11)] public string DefaultSenderId { get { return this._defaultSenderId; } set { this._defaultSenderId = value; } } // Check to see if DefaultSenderId property is set internal bool IsSetDefaultSenderId() { return this._defaultSenderId != null; } /// <summary> /// Gets and sets the property EventDestinations. /// <para> /// An array of any EventDestination objects that were associated with the deleted configuration /// set. /// </para> /// </summary> public List<EventDestination> EventDestinations { get { return this._eventDestinations; } set { this._eventDestinations = value; } } // Check to see if EventDestinations property is set internal bool IsSetEventDestinations() { return this._eventDestinations != null && this._eventDestinations.Count > 0; } } }
33.012821
119
0.611262
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/PinpointSMSVoiceV2/Generated/Model/DeleteConfigurationSetResponse.cs
5,150
C#
/**** Git Credential Manager for Windows **** * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the """"Software""""), to deal * in the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." **/ namespace Microsoft.Alm.Authentication { public interface ISecretStore { /// <summary> /// Gets the namespace used by the store to segment stored values. /// </summary> string Namespace { get; } /// <summary> /// Gets or sets the method used to convert a Uri into a storage key. /// </summary> Secret.UriNameConversionDelegate UriNameConversion { get; set; } } }
40.365854
86
0.711178
[ "MIT" ]
6paklata/Git-Credential-Manager-for-Windows
Microsoft.Alm.Authentication/Src/ISecretStore.cs
1,657
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Bir bütünleştirilmiş koda ilişkin Genel Bilgiler aşağıdaki öznitelikler kümesiyle // denetlenir. Bütünleştirilmiş kod ile ilişkili bilgileri değiştirmek için // bu öznitelik değerlerini değiştirin. [assembly: AssemblyTitle("RawDataDecoder")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RawDataDecoder")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible özniteliğinin false olarak ayarlanması bu bütünleştirilmiş koddaki türleri // COM bileşenleri için görünmez yapar. Bu bütünleştirilmiş koddaki bir türe // erişmeniz gerekirse ComVisible özniteliğini o türde true olarak ayarlayın. [assembly: ComVisible(false)] // Bu proje COM'un kullanımına sunulursa, aşağıdaki GUID tür kitaplığının kimliği içindir [assembly: Guid("351250ea-fdc1-45f4-b650-7bead47e3b17")] // Bir derlemenin sürüm bilgileri aşağıdaki dört değerden oluşur: // // Ana Sürüm // İkincil Sürüm // Yapı Numarası // Düzeltme // // Tüm değerleri belirtebilir veya varsayılan Derleme ve Düzeltme Numaralarını kullanmak için // '*' kullanarak varsayılana ayarlayabilirsiniz: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.459459
93
0.778082
[ "MIT" ]
nejdetsarikaya3802/RAW-Data-decoder
Properties/AssemblyInfo.cs
1,543
C#
using FalconNet.Common.Graphics; using System; using System.Diagnostics; using Pintensity = System.Single; using Pmatrix = FalconNet.Common.Graphics.Trotation; namespace FalconNet.Graphics { public struct StateStackFrame { public Tpoint[] XformedPosPool; public Pintensity[] IntensityPool; public PclipInfo[] ClipInfoPool; public Pmatrix Rotation; public Tpoint Xlation; public Tpoint ObjSpaceEye; public Tpoint ObjSpaceLight; public int[] CurrentTextureTable; public ObjectInstance CurrentInstance; public ObjectLOD CurrentLOD; public PolyLib.DrawPrimFp DrawPrimJumpTable; public StateStackClass.TransformFp Transform; } public class StateStackClass { // The one and only state stack. This would need to be replaced // by pointers to instances of StateStackClass passed to each call // if more than one stack were to be simultaniously maintained. public static StateStackClass TheStateStack; public delegate void TransformFp(Tpoint[] p, int n, int offset =0); public const int MAX_STATE_STACK_DEPTH = 8; // Arbitrary public const int MAX_SLOT_AND_DYNAMIC_PER_OBJECT = 64; // Arbitrary public const int MAX_TEXTURES_PER_OBJECT = 128; // Arbitrary public const int MAX_CLIP_PLANES = 6; // 5 view volume, plus 1 extra public const int MAX_VERTS_PER_POLYGON = 32; // Arbitrary public const int MAX_VERT_POOL_SIZE = 4096; // Arbitrary public const int MAX_VERTS_PER_CLIPPED_POLYGON = MAX_VERTS_PER_POLYGON + MAX_CLIP_PLANES; public const int MAX_CLIP_VERTS = 2 * MAX_CLIP_PLANES; public const int MAX_VERTS_PER_OBJECT_TREE = MAX_VERT_POOL_SIZE - MAX_VERTS_PER_POLYGON - MAX_CLIP_VERTS; public const float NEAR_CLIP_DISTANCE = 1.0f; public StateStackClass() { #if TODO stackDepth = 0; XformedPosPoolNext = XformedPosPoolBuffer; IntensityPoolNext = IntensityPoolBuffer; ClipInfoPoolNext = ClipInfoPoolBuffer; LODBiasInv = 1.0f; SetTextureState(true); SetFog(0.0f, null); #endif throw new NotImplementedException(); } //public ~StateStackClass() { Debug.Assert(stackDepth == 0); }; // Called by application public static void SetContext(ContextMPR cntxt) { context = cntxt; } public static void SetLight(float a, float d, Tpoint atLight) { LightAmbient = a; LightDiffuse = d; // Prescale the light vector with the diffuse multiplier LightVector.x = atLight.x * d; LightVector.y = atLight.y * d; LightVector.z = atLight.z * d; // Intialize the light postion in world space ObjSpaceLight = LightVector; } public static void SetCameraProperties(float ooTanHHAngle, float ooTanVHAngle, float sclx, float scly, float shftx, float shfty) { float rx2; rx2 = (ooTanHHAngle * ooTanHHAngle); hAspectDepthCorrection = 1.0f / (float)Math.Sqrt(rx2 + 1.0f); hAspectWidthCorrection = rx2 * hAspectDepthCorrection; rx2 = (ooTanVHAngle * ooTanVHAngle); vAspectDepthCorrection = 1.0f / (float)Math.Sqrt(rx2 + 1.0f); vAspectWidthCorrection = rx2 * vAspectDepthCorrection; scaleX = sclx; scaleY = scly; shiftX = shftx; shiftY = shfty; } public static void SetLODBias(float bias) { LODBiasInv = 1.0f / bias; } public static void SetTextureState(bool state) { #if TODO if(!PlayerOptions.bFilteredObjects) { // OW original code if(state) { RenderStateTableNoFogPC = RenderStateTableWithPCTex; RenderStateTableNoFogNPC = RenderStateTableWithNPCTex; DrawPrimNoFogNoClipJumpTable = DrawPrimNoClipWithTexJumpTable; ClipPrimNoFogJumpTable = ClipPrimWithTexJumpTable; RenderStateTableFogPC = RenderStateTableFogWithPCTex; RenderStateTableFogNPC = RenderStateTableFogWithNPCTex; DrawPrimFogNoClipJumpTable = DrawPrimFogNoClipWithTexJumpTable; ClipPrimFogJumpTable = ClipPrimFogWithTexJumpTable; } else { RenderStateTableNoFogPC = RenderStateTableNoTex; RenderStateTableNoFogNPC = RenderStateTableNoTex; DrawPrimNoFogNoClipJumpTable = DrawPrimNoClipNoTexJumpTable; ClipPrimNoFogJumpTable = ClipPrimNoTexJumpTable; RenderStateTableFogPC = RenderStateTableNoTex; RenderStateTableFogNPC = RenderStateTableNoTex; DrawPrimFogNoClipJumpTable = DrawPrimFogNoClipNoTexJumpTable; ClipPrimFogJumpTable = ClipPrimFogNoTexJumpTable; } if(fogValue <= 0.0f) { RenderStateTablePC = RenderStateTableNoFogPC; RenderStateTableNPC = RenderStateTableNoFogNPC; DrawPrimNoClipJumpTable = DrawPrimNoFogNoClipJumpTable; ClipPrimJumpTable = ClipPrimNoFogJumpTable; } else { RenderStateTablePC = RenderStateTableFogPC; RenderStateTableNPC = RenderStateTableFogNPC; DrawPrimNoClipJumpTable = DrawPrimFogNoClipJumpTable; ClipPrimJumpTable = ClipPrimFogJumpTable; } } else // OW { if(state) { RenderStateTableNoFogPC = RenderStateTableWithPCTex_Filter; RenderStateTableNoFogNPC = RenderStateTableWithNPCTex_Filter; DrawPrimNoFogNoClipJumpTable = DrawPrimNoClipWithTexJumpTable; ClipPrimNoFogJumpTable = ClipPrimWithTexJumpTable; RenderStateTableFogPC = RenderStateTableFogWithPCTex_Filter; RenderStateTableFogNPC = RenderStateTableFogWithNPCTex_Filter; DrawPrimFogNoClipJumpTable = DrawPrimFogNoClipWithTexJumpTable; ClipPrimFogJumpTable = ClipPrimFogWithTexJumpTable; } else { RenderStateTableNoFogPC = RenderStateTableNoTex_Filter; RenderStateTableNoFogNPC = RenderStateTableNoTex_Filter; DrawPrimNoFogNoClipJumpTable = DrawPrimNoClipNoTexJumpTable; ClipPrimNoFogJumpTable = ClipPrimNoTexJumpTable; RenderStateTableFogPC = RenderStateTableNoTex_Filter; RenderStateTableFogNPC = RenderStateTableNoTex_Filter; DrawPrimFogNoClipJumpTable = DrawPrimFogNoClipNoTexJumpTable; ClipPrimFogJumpTable = ClipPrimFogNoTexJumpTable; } if(fogValue <= 0.0f) { RenderStateTablePC = RenderStateTableNoFogPC; RenderStateTableNPC = RenderStateTableNoFogNPC; DrawPrimNoClipJumpTable = DrawPrimNoFogNoClipJumpTable; ClipPrimJumpTable = ClipPrimNoFogJumpTable; } else { RenderStateTablePC = RenderStateTableFogPC; RenderStateTableNPC = RenderStateTableFogNPC; DrawPrimNoClipJumpTable = DrawPrimFogNoClipJumpTable; ClipPrimJumpTable = ClipPrimFogJumpTable; } } #endif } public static void SetFog(float percent, Pcolor color) { #if TODO Debug.Assert( percent <= 1.0f ); fogValue = percent; if (percent <= 0.0f) { // Turn fog off RenderStateTablePC = RenderStateTableNoFogPC; RenderStateTableNPC = RenderStateTableNoFogNPC; DrawPrimNoClipJumpTable = DrawPrimNoFogNoClipJumpTable; ClipPrimJumpTable = ClipPrimNoFogJumpTable; } else { // Turn fog on RenderStateTablePC = RenderStateTableFogPC; RenderStateTableNPC = RenderStateTableFogNPC; DrawPrimNoClipJumpTable = DrawPrimFogNoClipJumpTable; ClipPrimJumpTable = ClipPrimFogJumpTable; // We store the color pre-scaled by the percent of fog to save time later. Debug.Assert( color ); fogColor_premul.r = color.r * percent; fogColor_premul.g = color.g * percent; fogColor_premul.b = color.b * percent; // We store 1-percent to save time later. fogValue_inv = 1.0f - percent; // SCR 6/30/98: We properly should set MPR's notion of the fog color here // but it's a little messy to use a context here, and besides, // Falcon can count on the RendererOTW to set it (right?) // Therefore: this should be normally off (turned on only for testing) #if !NOTHING if (g_nFogRenderState & 0x02) { UInt32 c; c = FloatToInt32(color.r * 255.9f); c |= FloatToInt32(color.g * 255.9f) << 8; c |= FloatToInt32(color.b * 255.9f) << 16; context.SetState( MPR_STA_FOG_COLOR, c ); } #endif } #endif } public static void SetCamera(Tpoint pos, Pmatrix rotWaspect, Pmatrix Bill, Pmatrix Tree) { #if TODO Debug.Assert(stackDepth == 0); // Store our rotation from world to camera space (including aspect scale effects) Rotation = rotWaspect; // Compute the vector from the camera to the origin rotated into camera space Xlation.x = -pos.x * Rotation.M11 - pos.y * Rotation.M12 - pos.z * Rotation.M13; Xlation.y = -pos.x * Rotation.M21 - pos.y * Rotation.M22 - pos.z * Rotation.M23; Xlation.z = -pos.x * Rotation.M31 - pos.y * Rotation.M32 - pos.z * Rotation.M33; // Intialize the eye postion in world space ObjSpaceEye = pos; // Store pointers out to the billboard and tree matrices in case we need them Tb = Bill; Tt = Tree; #endif throw new NotImplementedException(); } // This call is for the application to call to draw an instance of an object. public static void DrawObject(ObjectInstance objInst, Pmatrix rot, Tpoint pos, float scale = 1.0f) { #if TODO pvtDrawObject( OP_NONE, objInst, rot, pos, 1.0f, 1.0f, 1.0f, scale ); #endif throw new NotImplementedException(); } // This call is rather specialized. It is intended for use in drawing shadows which // are simple objects (no slots, dofs, etc) but require asymetric scaling in x and y // to simulate orientation changes of the object casting the shadow. public static void DrawWarpedObject(ObjectInstance objInst, Pmatrix rot, Tpoint pos, float sx, float sy, float sz, float scale = 1.0f) { #if TODO pvtDrawObject( OP_WARP, objInst, rot, pos, sx, sy, sz, scale ); #endif throw new NotImplementedException(); } // Called by BRoot nodes at draw heading // This call is for the BSPlib to call to draw a child instance attached to a slot. public static void DrawSubObject(ObjectInstance objInst, Pmatrix rot, Tpoint pos) { #if TODO pvtDrawObject( OP_NONE, objInst, rot, pos, 1.0f, 1.0f, 1.0f, 1.0f ); #endif throw new NotImplementedException(); } public static void CompoundTransform(Pmatrix rot, Tpoint pos) { Tpoint tempP = new Tpoint(), tempP2; Pmatrix tempM; // Compute the rotated translation vector for this object Xlation.x += pos.x * Rotation.M11 + pos.y * Rotation.M12 + pos.z * Rotation.M13; Xlation.y += pos.x * Rotation.M21 + pos.y * Rotation.M22 + pos.z * Rotation.M23; Xlation.z += pos.x * Rotation.M31 + pos.y * Rotation.M32 + pos.z * Rotation.M33; tempM = Rotation; tempP.x = ObjSpaceEye.x - pos.x; tempP.y = ObjSpaceEye.y - pos.y; tempP.z = ObjSpaceEye.z - pos.z; tempP2 = ObjSpaceLight; // Composit the camera matrix with the object rotation Matrix.MatrixMult(tempM, rot, ref Rotation); // Compute the eye point in object space Matrix.MatrixMultTranspose(rot, tempP, ref ObjSpaceEye); // Compute the light direction in object space. Matrix.MatrixMultTranspose(rot, tempP2, ref ObjSpaceLight); } public static void Light(Pnormal[] pNormals, int nNormals) { // Make sure we've got enough room in the light value pool Debug.Assert(IsValidIntensityIndex(nNormals - 1)); for(int j = 0; j < nNormals; j++) { // light intensity = ambient + diffuse*(lightVector dot normal) // and we already scaled the lightVector by the diffuse intensity. IntensityPool[IntensityPoolNext] = pNormals[j].i * ObjSpaceLight.x + pNormals[j].j * ObjSpaceLight.y + pNormals[j].k * ObjSpaceLight.z; if (IntensityPool[IntensityPoolNext] > 0.0f) { IntensityPool[IntensityPoolNext] += LightAmbient; } else { IntensityPool[IntensityPoolNext] = LightAmbient; } IntensityPoolNext++; } } public static void SetTextureTable(int[] pTexIDs) { CurrentTextureTable = pTexIDs; } public static void PushAll() { #if TODO Debug.Assert( stackDepth < MAX_STATE_STACK_DEPTH ); stack[stackDepth].XformedPosPool = XformedPosPool; stack[stackDepth].IntensityPool = IntensityPool; stack[stackDepth].ClipInfoPool = ClipInfoPool; stack[stackDepth].Rotation = Rotation; stack[stackDepth].Xlation = Xlation; stack[stackDepth].ObjSpaceEye = ObjSpaceEye; stack[stackDepth].ObjSpaceLight = ObjSpaceLight; stack[stackDepth].CurrentInstance = CurrentInstance; stack[stackDepth].CurrentLOD = CurrentLOD; stack[stackDepth].CurrentTextureTable = CurrentTextureTable; stack[stackDepth].DrawPrimJumpTable = DrawPrimJumpTable; stack[stackDepth].Transform = Transform; XformedPosPool = XformedPosPoolNext; IntensityPool = IntensityPoolNext; ClipInfoPool = ClipInfoPoolNext; stackDepth++; #endif throw new NotImplementedException(); } public static void PopAll() { #if TODO stackDepth--; XformedPosPoolNext = XformedPosPool; IntensityPoolNext = IntensityPool; ClipInfoPoolNext = ClipInfoPool; XformedPosPool = stack[stackDepth].XformedPosPool; IntensityPool = stack[stackDepth].IntensityPool; ClipInfoPool = stack[stackDepth].ClipInfoPool; Rotation = stack[stackDepth].Rotation; Xlation = stack[stackDepth].Xlation; ObjSpaceEye = stack[stackDepth].ObjSpaceEye; ObjSpaceLight = stack[stackDepth].ObjSpaceLight; CurrentInstance = stack[stackDepth].CurrentInstance; CurrentLOD = stack[stackDepth].CurrentLOD; CurrentTextureTable = stack[stackDepth].CurrentTextureTable; DrawPrimJumpTable = stack[stackDepth].DrawPrimJumpTable; Transform = stack[stackDepth].Transform; #endif throw new NotImplementedException(); } public static void PushVerts() { #if TODO Debug.Assert( stackDepth < MAX_STATE_STACK_DEPTH ); stack[stackDepth].XformedPosPool = XformedPosPool; stack[stackDepth].IntensityPool = IntensityPool; stack[stackDepth].ClipInfoPool = ClipInfoPool; XformedPosPool = XformedPosPoolNext; IntensityPool = IntensityPoolNext; ClipInfoPool = ClipInfoPoolNext; stackDepth++; #endif throw new NotImplementedException(); } public static void PopVerts() { #if TODO stackDepth--; XformedPosPoolNext = XformedPosPool; IntensityPoolNext = IntensityPool; ClipInfoPoolNext = ClipInfoPool; XformedPosPool = stack[stackDepth].XformedPosPool; IntensityPool = stack[stackDepth].IntensityPool; ClipInfoPool = stack[stackDepth].ClipInfoPool; #endif throw new NotImplementedException(); } // This should be cleaned up and probably have special clip/noclip versions public static void TransformBillboardWithClip(Tpoint[] p, int n, BTransformType type) { #if TODO float scratch_x, scratch_y, scratch_z; Pmatrix T; // Make sure we've got enough room in the transformed position pool Debug.Assert( IsValidPosIndex( n-1 ) ); if (type == Tree) { T = Tt; } else { T = Tb; } while( n-- ) { scratch_z = T.M11 * p.x + T.M12 * p.y + T.M13 * p.z + Xlation.x; scratch_x = T.M21 * p.x + T.M22 * p.y + T.M23 * p.z + Xlation.y; scratch_y = T.M31 * p.x + T.M32 * p.y + T.M33 * p.z + Xlation.z; ClipInfoPoolNext.clipFlag = ON_SCREEN; if ( scratch_z < NEAR_CLIP_DISTANCE ) { ClipInfoPoolNext.clipFlag |= ClippingFlags.CLIP_NEAR; } if ( fabs(scratch_y) > scratch_z ) { if ( scratch_y > scratch_z ) { ClipInfoPoolNext.clipFlag |= CLIP_BOTTOM; } else { ClipInfoPoolNext.clipFlag |= CLIP_TOP; } } if ( fabs(scratch_x) > scratch_z ) { if ( scratch_x > scratch_z ) { ClipInfoPoolNext.clipFlag |= CLIP_RIGHT; } else { ClipInfoPoolNext.clipFlag |= CLIP_LEFT; } } ClipInfoPoolNext.csX = scratch_x; ClipInfoPoolNext.csY = scratch_y; ClipInfoPoolNext.csZ = scratch_z; ClipInfoPoolNext++; float OneOverZ = 1.0f/scratch_z; p++; XformedPosPoolNext.z = scratch_z; XformedPosPoolNext.x = XtoPixel( scratch_x * OneOverZ ); XformedPosPoolNext.y = YtoPixel( scratch_y * OneOverZ ); XformedPosPoolNext++; } #endif throw new NotImplementedException(); } // Called by our own transformations and the clipper public static float XtoPixel(float x) { return (x * scaleX) + shiftX; } public static float YtoPixel(float y) { return (y * scaleY) + shiftY; } // For parameter validation during debug public static bool IsValidPosIndex(int i) { #if TODO return (i+XformedPosPool < XformedPosPoolBuffer+MAX_VERT_POOL_SIZE); #endif throw new NotImplementedException(); } public static bool IsValidIntensityIndex(int i) { #if TODO return (i+IntensityPool < IntensityPoolBuffer+MAX_VERT_POOL_SIZE); #endif throw new NotImplementedException(); } protected static void TransformNoClip(Tpoint[] pCoords, int nCoords, int offset = 0) { TransformInline(pCoords, nCoords, false, offset); } protected static void TransformWithClip(Tpoint[] pCoords, int nCoords, int offset = 0) { TransformInline(pCoords, nCoords, true, offset); } protected static ClippingFlags CheckBoundingSphereClipping() { // Decide if we need clipping, or if the object is totally off screen // REMEMBER: Xlation is camera oriented, but still X front, Y right, Z down // so range from viewer is in the X term. // NOTE: We compute "d", the distance from the viewer at which the bounding // sphere should intersect the view frustum. We use .707 since the // rotation matrix already normalized us to a 45 degree half angle. // We do have to adjust the radius shift by the FOV correction factors, // though, since it didn't go through the matix. // NOTE2: We could develop the complete set of clip flags here by continuing to // check other edges instead of returning in the clipped cases. For now, // we only need to know if it IS clipped or not, so we terminate early. // TODO: We should roll the radius of any attached slot children into the check radius // to ensure that we don't reject a parent object whose _children_ may be on screen. // (though this should be fairly rare in practice) float rd; float rh; // UInt32 clipFlag = ClippingFlags.ON_SCREEN; rd = CurrentInstance.Radius() * vAspectDepthCorrection; rh = CurrentInstance.Radius() * vAspectWidthCorrection; if (-(Xlation.z - rh) >= Xlation.x - rd) { if (-(Xlation.z + rh) > Xlation.x + rd) { return ClippingFlags.OFF_SCREEN; // Trivial reject top } // clipFlag = ClippingFlags.CLIP_TOP; return ClippingFlags.CLIP_TOP; } if (Xlation.z + rh >= Xlation.x - rd) { if (Xlation.z - rh > Xlation.x + rd) { return ClippingFlags.OFF_SCREEN; // Trivial reject bottom } // clipFlag |= ClippingFlags.CLIP_BOTTOM; return ClippingFlags.CLIP_BOTTOM; } rd = CurrentInstance.Radius() * hAspectDepthCorrection; rh = CurrentInstance.Radius() * hAspectWidthCorrection; if (-(Xlation.y - rh) >= Xlation.x - rd) { if (-(Xlation.x + rh) > Xlation.x + rd) { return ClippingFlags.OFF_SCREEN; // Trivial reject left } // clipFlag |= ClippingFlags.CLIP_LEFT; return ClippingFlags.CLIP_LEFT; } if (Xlation.y + rh >= Xlation.x - rd) { if (Xlation.y - rh > Xlation.x + rd) { return ClippingFlags.OFF_SCREEN; // Trivial reject right } // clipFlag |= ClippingFlags.CLIP_RIGHT; return ClippingFlags.CLIP_RIGHT; } rh = CurrentInstance.Radius(); if (Xlation.x - rh < NEAR_CLIP_DISTANCE) { if (Xlation.x + rh < NEAR_CLIP_DISTANCE) { return ClippingFlags.OFF_SCREEN; // Trivial reject near } // clipFlag |= ClippingFlags.CLIP_NEAR; return ClippingFlags.CLIP_NEAR; } // return clipFlag; return ClippingFlags.ON_SCREEN; } protected static void TransformInline(Tpoint[] p, int nCoords, bool clip, int offset = 0) { float scratch_x, scratch_y, scratch_z; // Make sure we've got enough room in the transformed position pool Debug.Assert(IsValidPosIndex(nCoords - 1)); for (int n = 0; n < nCoords; n++ ) { scratch_z = Rotation.M11 * p[n].x + Rotation.M12 * p[n].y + Rotation.M13 * p[n].z + Xlation.x; scratch_x = Rotation.M21 * p[n].x + Rotation.M22 * p[n].y + Rotation.M23 * p[n].z + Xlation.y; scratch_y = Rotation.M31 * p[n].x + Rotation.M32 * p[n].y + Rotation.M33 * p[n].z + Xlation.z; if (clip) { ClipInfoPool[ClipInfoPoolNext].clipFlag = ClippingFlags.ON_SCREEN; if (scratch_z < NEAR_CLIP_DISTANCE) { ClipInfoPool[ClipInfoPoolNext].clipFlag |= ClippingFlags.CLIP_NEAR; } if (Math.Abs(scratch_y) > scratch_z) { if (scratch_y > scratch_z) { ClipInfoPool[ClipInfoPoolNext].clipFlag |= ClippingFlags.CLIP_BOTTOM; } else { ClipInfoPool[ClipInfoPoolNext].clipFlag |= ClippingFlags.CLIP_TOP; } } if (Math.Abs(scratch_x) > scratch_z) { if (scratch_x > scratch_z) { ClipInfoPool[ClipInfoPoolNext].clipFlag |= ClippingFlags.CLIP_RIGHT; } else { ClipInfoPool[ClipInfoPoolNext].clipFlag |= ClippingFlags.CLIP_LEFT; } } ClipInfoPool[ClipInfoPoolNext].csX = scratch_x; ClipInfoPool[ClipInfoPoolNext].csY = scratch_y; ClipInfoPool[ClipInfoPoolNext].csZ = scratch_z; ClipInfoPoolNext++; } float OneOverZ = 1.0f / scratch_z; XformedPosPool[XformedPosPoolNext].z = scratch_z; XformedPosPool[XformedPosPoolNext].x = XtoPixel(scratch_x * OneOverZ); XformedPosPool[XformedPosPoolNext].y = YtoPixel(scratch_y * OneOverZ); XformedPosPoolNext++; } } // The asymetric scale factors MUST be <= 1.0f. // The global scale factor can be any positive value. // The effects of the scales are multiplicative. private const UInt32 OP_NONE = 0; private const UInt32 OP_FOG = 1; private const UInt32 OP_WARP = 2; static int in_ = 0; #if TODO protected static void pvtDrawObject (DWORD operation, ObjectInstance *objInst, Pmatrix *rot, Tpoint *pos, float sx, float sy, float sz, float scale=1.0f) { UInt32 clipFlag; int LODused; float MaxLODRange; Debug.Assert( objInst ); PushAll(); // Set up our transformations CompoundTransform( rot, pos ); // Special code to impose an asymetric warp on the object // (Will screw up if any child transforms are encountered) if (operation & OP_WARP) { // Put the stretch into the transformation matrix Debug.Assert( (sx > 0.0f) && (sx <= 1.0f) ); Debug.Assert( (sy > 0.0f) && (sy <= 1.0f) ); Debug.Assert( (sz > 0.0f) && (sz <= 1.0f) ); Pmatrix tempM; Pmatrix stretchM = { sx, 0.0f, 0.0f, 0.0f, sy, 0.0f, 0.0f, 0.0f, sz }; tempM = Rotation; MatrixMult( &tempM, &stretchM, &Rotation ); } // Special code to impose a scale on an object if (scale != 1.0f) { float inv = 1.0f / scale; Xlation.x *= inv; Xlation.y *= inv; Xlation.z *= inv; ObjSpaceEye.x *= inv; ObjSpaceEye.y *= inv; ObjSpaceEye.z *= inv; } // Store the adjusted range for LOD determinations LODRange = Xlation.x * LODBiasInv; // Choose the appropriate LOD of the object to be drawn CurrentInstance = objInst; if (objInst.ParentObject) { if (g_bSlowButSafe && F4IsBadCodePtr((FARPROC) objInst.ParentObject)) // JB 010220 CTD (too much CPU) CurrentLOD = 0; // JB 010220 CTD else // JB 010220 CTD if (objInst.id < 0 || objInst.id >= TheObjectListLength || objInst.TextureSet < 0) // JB 010705 CTD second try { Debug.Assert(false); CurrentLOD = 0; } else CurrentLOD = objInst.ParentObject.ChooseLOD(LODRange, &LODused, &MaxLODRange); if (CurrentLOD) { // Decide if we need clipping, or if the object is totally off screen clipFlag = CheckBoundingSphereClipping(); // Continue only if some part of the bounding volume is on screen if (clipFlag != OFF_SCREEN) { // Set the jump pointers to turn on/off clipping if (clipFlag == ON_SCREEN) { Transform = TransformNoClip; DrawPrimJumpTable = DrawPrimNoClipJumpTable; } else { Transform = TransformWithClip; DrawPrimJumpTable = DrawPrimWithClipJumpTable; } // Choose perspective correction or not if ((Xlation.x > CurrentInstance.Radius() * PERSP_CORR_RADIUS_MULTIPLIER) && !(CurrentLOD.flags & ObjectLOD::PERSP_CORR)) { RenderStateTable = RenderStateTableNPC; } else { RenderStateTable = RenderStateTablePC; } in_ ++; if (in_ == 1) { verts = 0; } // Draw the object CurrentLOD.Draw(); // if (in == 1) // { // if (verts) // { // MonoPrint ("Obj %d:%d %d : %d\n", objInst.id, LODused, (int) MaxLODRange, verts); // } // } in_ --; } } } PopAll(); } #endif // Active transformation function (selects between with or without clipping) public static TransformFp Transform; // Computed data pools public static Tpoint[] XformedPosPool; // These point into global storage. They will point public static Pintensity[] IntensityPool; // to the computed tables for each sub-object. public static PclipInfo[] ClipInfoPool; public static int XformedPosPoolNext;// These point into global storage. They will point public static int IntensityPoolNext; // to at least MAX_CLIP_VERTS empty slots beyond public static int ClipInfoPoolNext; // the computed tables in use by the current sub-object. // Instance of the object we're drawing and its range normalized for resolution and FOV public static ObjectInstance CurrentInstance; public static ObjectLOD CurrentLOD; public static int[] CurrentTextureTable; public static float LODRange; // Fog properties public static float fogValue; // fog precent (set by SetFog()) public static float fogValue_inv; // 1.0f - fog precent (set by SetFog()) public static Pcolor fogColor_premul; // Fog color times fog percent (set by SetFog()) // Final transform public static Pmatrix Rotation; // These are the final camera transform public static Tpoint Xlation; // including contributions from parent objects // Fudge factors for drawing public static float LODBiasInv; // This times real range is LOD evaluation range // Object space points of interest public static Tpoint ObjSpaceEye; // Eye point in object space (for BSP evaluation) public static Tpoint ObjSpaceLight; // Light location in object space(for BSP evaluation) // Pointers to our clients billboard and tree matrices in case we need them public static Pmatrix[] Tb; // Billboard (always faces viewer) public static Pmatrix[] Tt; // Tree (always stands up straight and faces viewer) // Lighting properties for the BSP objects public static float LightAmbient = 0.5f; public static float LightDiffuse = 0.5f; public static Tpoint LightVector = new Tpoint() { x = 0.0f, y = 0.0f, z = -LightDiffuse }; // The context on which we'll draw public static IContext context; protected static StateStackFrame[] stack = new StateStackFrame[MAX_STATE_STACK_DEPTH]; protected static int stackDepth; // Required for object culling protected static float hAspectWidthCorrection; protected static float hAspectDepthCorrection; protected static float vAspectWidthCorrection; protected static float vAspectDepthCorrection; // The parameters required to get from normalized screen space to pixel space protected static float scaleX; protected static float scaleY; protected static float shiftX; protected static float shiftY; /********************************************\ Reserved storage space for computed values. \********************************************/ private static Tpoint[] XformedPosPoolBuffer = new Tpoint[MAX_VERT_POOL_SIZE]; private static Pintensity[] IntensityPoolBuffer = new Pintensity[MAX_VERT_POOL_SIZE]; private static PclipInfo[] ClipInfoPoolBuffer = new PclipInfo[MAX_VERT_POOL_SIZE]; } }
34.561191
156
0.62242
[ "MIT" ]
agustinsantos/FalconNet
Graphics/StateStack.cs
31,347
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Microsoft.Health.Fhir.Liquid.Converter.Exceptions; using Microsoft.Health.Fhir.Liquid.Converter.Hl7v2.InputProcessor; using Microsoft.Health.Fhir.Liquid.Converter.Hl7v2.Models; using Microsoft.Health.Fhir.Liquid.Converter.Models; namespace Microsoft.Health.Fhir.Liquid.Converter.Hl7v2 { public class Hl7v2DataParser { private readonly Hl7v2DataValidator _validator = new Hl7v2DataValidator(); private static readonly string[] SegmentSeparators = { "\r\n", "\r", "\n" }; public Hl7v2Data Parse(string message) { var result = new Hl7v2Data(message); try { if (string.IsNullOrEmpty(message)) { throw new DataParseException(FhirConverterErrorCode.NullOrEmptyInput, Resources.NullOrEmptyInput); } var segments = message.Split(SegmentSeparators, StringSplitOptions.RemoveEmptyEntries); _validator.ValidateMessageHeader(segments[0]); var encodingCharacters = ParseHl7v2EncodingCharacters(segments[0]); result.EncodingCharacters = encodingCharacters; for (var i = 0; i < segments.Length; ++i) { var fields = ParseFields(segments[i], encodingCharacters, isHeaderSegment: i == 0); var segment = new Hl7v2Segment(NormalizeText(segments[i], encodingCharacters), fields); result.Meta.Add(fields.First()?.Value ?? string.Empty); result.Data.Add(segment); } } catch (Exception ex) { throw new DataParseException(FhirConverterErrorCode.InputParsingError, string.Format(Resources.InputParsingError, ex.Message), ex); } return result; } private List<Hl7v2Field> ParseFields(string dataString, Hl7v2EncodingCharacters encodingCharacters, bool isHeaderSegment = false) { var fields = new List<Hl7v2Field>(); var fieldValues = dataString.Split(encodingCharacters.FieldSeparator); for (var f = 0; f < fieldValues.Length; ++f) { // MSH segment need to be handled separatedly since it's first field is the field separator `|`, // and the second field is encoding characters if (isHeaderSegment && f == 1) { // field separator var fieldSeparatorComponents = new List<Hl7v2Component> { null, new Hl7v2Component(encodingCharacters.FieldSeparator.ToString(), new List<string> { null, encodingCharacters.FieldSeparator.ToString() }), }; var fieldSeparatorField = new Hl7v2Field(encodingCharacters.FieldSeparator.ToString(), fieldSeparatorComponents); fields.Add(fieldSeparatorField); // encoding characters var seperatorFieldComponents = new List<Hl7v2Component> { null, new Hl7v2Component(fieldValues[f], new List<string> { null, fieldValues[f] }), }; var separatorField = new Hl7v2Field(fieldValues[f], seperatorFieldComponents); fields.Add(separatorField); } else { if (!string.IsNullOrEmpty(fieldValues[f])) { /** * We have four circumstances here. * 1. The templates using this field treat it as repeatable, and the field contains $RepetitionSeparator; * 2. The templates using this field treat it as repeatable, and the field doesn't contain $RepetitionSeparator; * 3. The templates using this field treat it as unrepeatable, and the field contains $RepetitionSeparator; * 4. The templates using this field treat it as unrepeatable, and the field doesn't contain $RepetitionSeparator; * * For circumstance #1 and #2, it will be all ok because the $field.Repeats always contains at least one value; * For circumstance #3, we just take the first element in the repetition as the whole field by default; * For circumstance #4, there will also be all right to take the first element of the $Repeats as the field itself; */ var field = new Hl7v2Field(NormalizeText(fieldValues[f], encodingCharacters), new List<Hl7v2Component>()); var repetitions = fieldValues[f].Split(encodingCharacters.RepetitionSeparator); for (var r = 0; r < repetitions.Length; ++r) { var repetitionComponents = ParseComponents(repetitions[r], encodingCharacters); var repetition = new Hl7v2Field(NormalizeText(repetitions[r], encodingCharacters), repetitionComponents); field.Repeats.Add(repetition); } field.Components = ((Hl7v2Field)field.Repeats[0]).Components; fields.Add(field); } else { fields.Add(null); } } } return fields; } private List<Hl7v2Component> ParseComponents(string dataString, Hl7v2EncodingCharacters encodingCharacters) { // Add a null value at first to keep consistent indexes with HL7 v2 spec var components = new List<Hl7v2Component> { null }; var componentValues = dataString.Split(encodingCharacters.ComponentSeparator); foreach (var componentValue in componentValues) { if (!string.IsNullOrEmpty(componentValue)) { var subcomponents = ParseSubcomponents(componentValue, encodingCharacters); var component = new Hl7v2Component(NormalizeText(componentValue, encodingCharacters), subcomponents); components.Add(component); } else { components.Add(null); } } return components; } private List<string> ParseSubcomponents(string dataString, Hl7v2EncodingCharacters encodingCharacters) { // Add a null value at first to keep consistent indexes with HL7 v2 spec var subcomponents = new List<string>() { null }; var subcomponentValues = dataString.Split(encodingCharacters.SubcomponentSeparator); foreach (var subcomponentValue in subcomponentValues) { subcomponents.Add(NormalizeText(subcomponentValue, encodingCharacters)); } return subcomponents; } private Hl7v2EncodingCharacters ParseHl7v2EncodingCharacters(string headerSegment) { return new Hl7v2EncodingCharacters { FieldSeparator = headerSegment[3], ComponentSeparator = headerSegment[4], RepetitionSeparator = headerSegment[5], EscapeCharacter = headerSegment[6], SubcomponentSeparator = headerSegment[7], }; } private string NormalizeText(string value, Hl7v2EncodingCharacters encodingCharacters) { var semanticalUnescape = Hl7v2EscapeSequenceProcessor.Unescape(value, encodingCharacters); var grammarEscape = SpecialCharProcessor.Escape(semanticalUnescape); return grammarEscape; } } }
48.965116
162
0.56483
[ "MIT" ]
SemanticClarity/FHIR-Converter
src/Microsoft.Health.Fhir.Liquid.Converter/Hl7v2/Hl7v2DataParser.cs
8,422
C#
namespace TechnologyCharacterGenerator.Foundation.Models { public class UserViewModel { public string Name { get; set; } public int BirthMonth { get; set; } public int BirthDay { get; set; } public string FavoriteFood { get; set; } } }
20.285714
57
0.623239
[ "MIT" ]
bofirial/Blazor-RPG-Persona
TechnologyCharacterGenerator.Foundation/Models/UserViewModel.cs
286
C#
namespace QuizHut.Web.ViewModels.UsersInRole { using System.ComponentModel.DataAnnotations; public class UserInputViewModel { [Required] [EmailAddress] public string Email { get; set; } public bool IsNotAdded { get; set; } public string RoleName { get; set; } } }
20.25
48
0.62963
[ "MIT" ]
miraDask/QuizHut
QuizHut/Web/QuizHut.Web.ViewModels/UsersInRole/UserInputViewModel.cs
326
C#
using System; using System.Collections.Generic; using System.IO; using Mammoth.Couscous; using Mammoth.Couscous.org.zwobble.mammoth.@internal; using Mammoth.Couscous.org.zwobble.mammoth.@internal.conversion; namespace Mammoth { public class DocumentConverter { private readonly DocumentToHtmlOptions options; public DocumentConverter() : this(DocumentToHtmlOptions._DEFAULT) { } private DocumentConverter(DocumentToHtmlOptions options) { this.options = options; } public DocumentConverter IdPrefix(string idPrefix) { return new DocumentConverter(options.idPrefix(idPrefix)); } public DocumentConverter PreserveEmptyParagraphs() { return new DocumentConverter(options.preserveEmptyParagraphs()); } public DocumentConverter AddStyleMap(string styleMap) { return new DocumentConverter(options.addStyleMap(styleMap)); } public DocumentConverter DisableDefaultStyleMap() { return new DocumentConverter(options.disableDefaultStyleMap()); } public DocumentConverter DisableEmbeddedStyleMap() { return new DocumentConverter(options.disableEmbeddedStyleMap()); } public DocumentConverter ImageConverter(Func<IImage, IDictionary<string, string>> imageConverter) { return new DocumentConverter(options.imageConverter(new ImageConverterShim(imageConverter))); } internal class ImageConverterShim : Mammoth.Couscous.org.zwobble.mammoth.images.ImageConverter__ImgElement { private readonly Func<IImage, IDictionary<string, string>> func; internal ImageConverterShim(Func<IImage, IDictionary<string, string>> func) { this.func = func; } public Mammoth.Couscous.java.util.Map<string, string> convert(Mammoth.Couscous.org.zwobble.mammoth.images.Image image) { return ToJava.DictionaryToMap(func(new Image(image))); } } internal class Image : IImage { private readonly Mammoth.Couscous.org.zwobble.mammoth.images.Image image; internal Image(Mammoth.Couscous.org.zwobble.mammoth.images.Image image) { this.image = image; } public string AltText { get { return image.getAltText().orElse(null); } } public string ContentType { get { return image.getContentType(); } } public Stream GetStream() { return image.getInputStream().Stream; } } public IResult<string> ConvertToHtml(Stream stream) { return new InternalDocumentConverter(options) .convertToHtml(ToJava.StreamToInputStream(stream)) .ToResult(); } public IResult<string> ConvertToHtml(string path) { return new InternalDocumentConverter(options) .convertToHtml(new Couscous.java.io.File(path)) .ToResult(); } public IResult<string> ExtractRawText(Stream stream) { return new InternalDocumentConverter(options) .extractRawText(ToJava.StreamToInputStream(stream)) .ToResult(); } public IResult<string> ExtractRawText(string path) { return new InternalDocumentConverter(options) .extractRawText(new Couscous.java.io.File(path)) .ToResult(); } } }
38.673913
132
0.637718
[ "BSD-2-Clause" ]
ScriptBox99/dotnet-mammoth
Mammoth/DocumentConverter.cs
3,558
C#
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Record { using System; using System.Text; using NPOI.Util; /** * Title: WSBool Record. * Description: stores workbook Settings (aka its a big "everything we didn't * put somewhere else") * REFERENCE: PG 425 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2) * @author Andrew C. Oliver (acoliver at apache dot org) * @author Glen Stampoultzis (gstamp@iprimus.com.au) * @author Jason Height (jheight at chariot dot net dot au) * @version 2.0-pre */ public class WSBoolRecord : StandardRecord { public const short sid = 0x81; private byte field_1_wsbool; // crappy names are because this is really one big short field (2byte) private byte field_2_wsbool; // but the docs inconsistantly use it as 2 seperate bytes // I decided to be consistant in this way. static private BitField autobreaks = BitFieldFactory.GetInstance(0x01); // are automatic page breaks visible // bits 1 to 3 Unused static private BitField dialog = BitFieldFactory.GetInstance(0x10); // is sheet dialog sheet static private BitField applystyles = BitFieldFactory.GetInstance(0x20); // whether to apply automatic styles to outlines static private BitField rowsumsbelow = BitFieldFactory.GetInstance(0x40); // whether summary rows will appear below detail in outlines static private BitField rowsumsright = BitFieldFactory.GetInstance(0x80); // whether summary rows will appear right of the detail in outlines static private BitField fittopage = BitFieldFactory.GetInstance(0x01); // whether to fit stuff to the page // bit 2 reserved static private BitField Displayguts = BitFieldFactory.GetInstance(0x06); // whether to Display outline symbols (in the gutters) // bits 4-5 reserved static private BitField alternateexpression = BitFieldFactory.GetInstance(0x40); // whether to use alternate expression eval static private BitField alternateformula = BitFieldFactory.GetInstance(0x80); // whether to use alternate formula entry public WSBoolRecord() { } /** * Constructs a WSBool record and Sets its fields appropriately. * @param in the RecordInputstream to Read the record from */ public WSBoolRecord(RecordInputStream in1) { byte[] data = in1.ReadRemainder(); field_1_wsbool = data[0]; field_2_wsbool = data[1]; } /** * Get first byte (see bit Getters) */ public byte WSBool1 { get { return field_1_wsbool; } set { field_1_wsbool = value; } } // bool1 bitfields /// <summary> /// Whether to show automatic page breaks or not /// </summary> public bool Autobreaks { get { return autobreaks.IsSet(field_1_wsbool); } set { field_1_wsbool = autobreaks.SetByteBoolean(field_1_wsbool, value); } } /// <summary> /// Whether sheet is a dialog sheet or not /// </summary> public bool Dialog { get { return dialog.IsSet(field_1_wsbool); } set { field_1_wsbool = dialog.SetByteBoolean(field_1_wsbool, value); } } /// <summary> /// Get if row summaries appear below detail in the outline /// </summary> public bool RowSumsBelow { get { return rowsumsbelow.IsSet(field_1_wsbool); } set { field_1_wsbool = rowsumsbelow.SetByteBoolean(field_1_wsbool, value); } } /// <summary> /// Get if col summaries appear right of the detail in the outline /// </summary> public bool RowSumsRight { get { return rowsumsright.IsSet(field_1_wsbool); } set { field_1_wsbool = rowsumsright.SetByteBoolean(field_1_wsbool, value); } } /// <summary> /// Get the second byte (see bit Getters) /// </summary> public byte WSBool2 { get { return field_2_wsbool; } set { field_2_wsbool = value; } } /// <summary> /// fit to page option is on /// </summary> public bool FitToPage { get { return fittopage.IsSet(field_2_wsbool); } set { field_2_wsbool = fittopage.SetByteBoolean(field_2_wsbool, value); } } /// <summary> /// Whether to display the guts or not /// </summary> public bool DisplayGuts { get { return Displayguts.IsSet(field_2_wsbool); } set { field_2_wsbool = Displayguts.SetByteBoolean(field_2_wsbool, value); } } /// <summary> /// whether alternate expression evaluation is on /// </summary> public bool AlternateExpression { get { return alternateexpression.IsSet(field_2_wsbool); } set { field_2_wsbool = alternateexpression.SetByteBoolean(field_2_wsbool, value); } } /// <summary> /// whether alternative formula entry is on /// </summary> public bool AlternateFormula { get { return alternateformula.IsSet(field_2_wsbool); } set { field_2_wsbool = alternateformula.SetByteBoolean(field_2_wsbool, value); } } public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("[WSBOOL]\n"); buffer.Append(" .wsbool1 = ") .Append(StringUtil.ToHexString(WSBool1)).Append("\n"); buffer.Append(" .autobreaks = ").Append(Autobreaks) .Append("\n"); buffer.Append(" .dialog = ").Append(Dialog) .Append("\n"); buffer.Append(" .rowsumsbelw= ").Append(RowSumsBelow) .Append("\n"); buffer.Append(" .rowsumsrigt= ").Append(RowSumsRight) .Append("\n"); buffer.Append(" .wsbool2 = ") .Append(StringUtil.ToHexString(WSBool2)).Append("\n"); buffer.Append(" .fittopage = ").Append(FitToPage) .Append("\n"); buffer.Append(" .Displayguts= ").Append(DisplayGuts) .Append("\n"); buffer.Append(" .alternateex= ") .Append(AlternateExpression).Append("\n"); buffer.Append(" .alternatefo= ").Append(AlternateFormula) .Append("\n"); buffer.Append("[/WSBOOL]\n"); return buffer.ToString(); } public override void Serialize(ILittleEndianOutput out1) { out1.WriteByte(WSBool1); out1.WriteByte(WSBool2); } protected override int DataSize { get { return 2; } } public override short Sid { get { return sid; } } public override Object Clone() { WSBoolRecord rec = new WSBoolRecord(); rec.field_1_wsbool = field_1_wsbool; rec.field_2_wsbool = field_2_wsbool; return rec; } } }
33.885185
192
0.52891
[ "Apache-2.0" ]
0xAAE/npoi
main/HSSF/Record/WSBoolRecord.cs
9,149
C#
// Project: Daggerfall Tools For Unity // Copyright: Copyright (C) 2009-2021 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Gavin Clayton (interkarma@dfworkshop.net) // Contributors: // // Notes: // #region Using Statements using System; using System.IO; using System.Collections.Generic; using DaggerfallConnect.Utility; using DaggerfallWorkshop; using DaggerfallWorkshop.Game; using DaggerfallWorkshop.Game.Questing; using DaggerfallWorkshop.Utility.AssetInjection; #endregion namespace DaggerfallConnect.Arena2 { /// <summary> /// Connects to MAPS.BSA to enumerate locations within a specific region and extract their layouts. /// </summary> public class MapsFile { #region Class Variables public const int WorldMapTerrainDim = 32768; public const int WorldMapTileDim = 128; public const int WorldMapRMBDim = 4096; public const int MinWorldCoordX = 0; public const int MinWorldCoordZ = 0; public const int MaxWorldCoordX = 32768000; public const int MaxWorldCoordZ = 16384000; public const int MinWorldTileCoordX = 0; public const int MaxWorldTileCoordX = 128000; public const int MinWorldTileCoordZ = 0; public const int MaxWorldTileCoordZ = 64000; public const int MinMapPixelX = 0; public const int MinMapPixelY = 0; public const int MaxMapPixelX = 1000; public const int MaxMapPixelY = 500; /// <summary> /// All region names. /// </summary> private static readonly string[] regionNames = { "Alik'r Desert", "Dragontail Mountains", "Glenpoint Foothills", "Daggerfall Bluffs", "Yeorth Burrowland", "Dwynnen", "Ravennian Forest", "Devilrock", "Malekna Forest", "Isle of Balfiera", "Bantha", "Dak'fron", "Islands in the Western Iliac Bay", "Tamarilyn Point", "Lainlyn Cliffs", "Bjoulsae River", "Wrothgarian Mountains", "Daggerfall", "Glenpoint", "Betony", "Sentinel", "Anticlere", "Lainlyn", "Wayrest", "Gen Tem High Rock village", "Gen Rai Hammerfell village", "Orsinium Area", "Skeffington Wood", "Hammerfell bay coast", "Hammerfell sea coast", "High Rock bay coast", "High Rock sea coast", "Northmoor", "Menevia", "Alcaire", "Koegria", "Bhoriane", "Kambria", "Phrygias", "Urvaius", "Ykalon", "Daenia", "Shalgora", "Abibon-Gora", "Kairou", "Pothago", "Myrkwasa", "Ayasofya", "Tigonus", "Kozanset", "Satakalaam", "Totambu", "Mournoth", "Ephesus", "Santaki", "Antiphyllos", "Bergama", "Gavaudon", "Tulune", "Glenumbra Moors", "Ilessan Hills", "Cybiades" }; /// <summary> /// All region races, primarily used to generate townsfolk names. In the array extracted from FALL.EXE: /// 0 = Breton, 1 = Redguard. /// </summary> private static readonly byte[] regionRaces = { 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1 }; /// <summary> /// Region temple faction IDs, extracted from FALL.EXE. /// </summary> private static readonly int[] regionTemples = { 106, 82, 0, 0, 0, 98, 0, 0, 0, 92, 0, 106, 0, 0, 0, 84, 36, 36, 84, 88, 82, 88, 98, 92, 0, 0, 82, 0, 0, 0, 0, 0, 88, 94, 36, 94, 106, 84, 106, 106, 88, 98, 82, 98, 84, 94, 36, 88, 94, 36, 98, 84, 106, 88, 106, 88, 92, 84, 98, 88, 82, 94 }; /// <summary> /// Block file prefixes. /// </summary> private readonly string[] rmbBlockPrefixes = { "TVRN", "GENR", "RESI", "WEAP", "ARMR", "ALCH", "BANK", "BOOK", "CLOT", "FURN", "GEMS", "LIBR", "PAWN", "TEMP", "TEMP", "PALA", "FARM", "DUNG", "CAST", "MANR", "SHRI", "RUIN", "SHCK", "GRVE", "FILL", "KRAV", "KDRA", "KOWL", "KMOO", "KCAN", "KFLA", "KHOR", "KROS", "KWHE", "KSCA", "KHAW", "MAGE", "THIE", "DARK", "FIGH", "CUST", "WALL", "MARK", "SHIP", "WITC" }; /// <summary> /// Letters that form the second part of an RMB block name. /// </summary> readonly string[] letter2Array = { "A", "L", "M", "S" }; /// <summary> /// RDB block letters array. /// </summary> private readonly string[] rdbBlockLetters = { "N", "W", "L", "S", "B", "M" }; /// <summary> /// Auto-discard behaviour enabled or disabled. /// </summary> private bool autoDiscardValue = true; /// <summary> /// The last region opened. Used by auto-discard logic. /// </summary> private int lastRegion = -1; /// <summary> /// The BsaFile representing MAPS.BSA. /// </summary> private readonly BsaFile bsaFile = new BsaFile(); /// <summary> /// Array of decomposed region records. /// </summary> private RegionRecord[] regions; /// <summary> /// Climate PAK file. /// </summary> private PakFile climatePak; /// <summary> /// Politic PAK file. /// </summary> private PakFile politicPak; /// <summary> /// Flag set when class is loaded and ready. /// </summary> private bool isReady = false; #endregion #region Class Structures /// <summary> /// Represents a single region record. /// </summary> private struct RegionRecord { public string Name; public FileProxy MapNames; public FileProxy MapTable; public FileProxy MapPItem; public FileProxy MapDItem; public DFRegion DFRegion; } /// <summary> /// Offsets to dungeon records. /// </summary> private struct DungeonOffset { /// <summary>Offset in bytes relative to end of offset list.</summary> public UInt32 Offset; /// <summary>Is TRUE (0x0001) for all elements.</summary> public UInt16 IsDungeon; /// <summary>The exterior location this dungeon is paired with.</summary> public UInt16 ExteriorLocationId; } #endregion #region Static Properties /// <summary> /// Gets default MAPS.BSA filename. /// </summary> public static string Filename { get { return "MAPS.BSA"; } } #endregion #region Constructors /// <summary> /// Default constructor. /// </summary> public MapsFile() { } /// <summary> /// Load constructor. /// </summary> /// <param name="filePath">Absolute path to MAPS.BSA.</param> /// <param name="usage">Determines if the BSA file will read from disk or memory.</param> /// <param name="readOnly">File will be read-only if true, read-write if false.</param> public MapsFile(string filePath, FileUsage usage, bool readOnly) { Load(filePath, usage, readOnly); } #endregion #region Public Properties /// <summary> /// If true then decomposed regions will be destroyed every time a different region is fetched. /// If false then decomposed regions will be maintained until DiscardRegion() or DiscardAllRegions() is called. /// Turning off auto-discard will speed up region retrieval times at the expense of RAM. For best results, disable /// auto-discard and impose your own caching scheme using LoadRecord() and DiscardRecord() based on your application /// needs. /// </summary> public bool AutoDiscard { get { return autoDiscardValue; } set { autoDiscardValue = value; } } /// <summary> /// Number of regions in MAPS.BSA. /// </summary> public int RegionCount { get { return bsaFile.Count / 4; } } /// <summary> /// Gets all region names as string array. /// </summary> public static string[] RegionNames { get { return regionNames; } } /// <summary> /// Gets all region races as byte array. /// </summary> public static byte[] RegionRaces { get { return regionRaces; } } /// <summary> /// Gets region temple faction IDs. /// </summary> public static int[] RegionTemples { get { return regionTemples; } } /// <summary> /// Gets raw MAPS.BSA file. /// </summary> public BsaFile BsaFile { get { return bsaFile; } } /// <summary> /// True when ready to load regions and locations, otherwise false. /// </summary> public bool Ready { get { return isReady; } } /// <summary> /// Gets internal climate data. /// </summary> public PakFile ClimateFile { get { return climatePak; } } #endregion #region Static Properties public enum Climates { Ocean = 223, Desert = 224, Desert2 = 225, // seen in dak'fron Mountain = 226, Rainforest = 227, Swamp = 228, Subtropical = 229, MountainWoods = 230, Woodlands = 231, HauntedWoodlands = 232 // not sure where this is? } /// <summary> /// Gets default climate index. /// </summary> public static int DefaultClimate { get { return 231; } } /// <summary> /// Gets default climate settings. /// </summary> public static DFLocation.ClimateSettings DefaultClimateSettings { get { return GetWorldClimateSettings(DefaultClimate); } } #endregion #region Static Public Methods /// <summary> /// Converts longitude and latitude to map pixel coordinates. /// The world is 1000x500 map pixels. /// </summary> /// <param name="longitude">Longitude position.</param> /// <param name="latitude">Latitude position.</param> /// <returns>Map pixel position.</returns> public static DFPosition LongitudeLatitudeToMapPixel(int longitude, int latitude) { DFPosition pos = new DFPosition(); pos.X = longitude / 128; pos.Y = 499 - (latitude / 128); return pos; } /// <summary> /// Converts map pixel coord to longitude and latitude. /// </summary> /// <param name="mapPixelX">Map pixel X.</param> /// <param name="mapPixelY">Map pixel Y.</param> /// <returns></returns> public static DFPosition MapPixelToLongitudeLatitude(int mapPixelX, int mapPixelY) { DFPosition pos = new DFPosition(); pos.X = mapPixelX * 128; pos.Y = (499 - mapPixelY) * 128; return pos; } /// <summary> /// Gets ID of map pixel. /// This can be mapped to location IDs and quest IDs. /// MapTableData.MapId &amp; 0x000fffff = WorldPixelID. /// </summary> /// <param name="mapPixelX">Map pixel X.</param> /// <param name="mapPixelY">Map pixel Y.</param> /// <returns>Map pixel ID.</returns> public static int GetMapPixelID(int mapPixelX, int mapPixelY) { return mapPixelY * 1000 + mapPixelX; } public static DFPosition GetPixelFromPixelID(int pixelID) { int x = pixelID % 1000; int y = (pixelID - x) / 1000; return new DFPosition(x, y); } /// <summary> /// Gets ID of map pixel using latitude and longitude. /// This can be mapped to location IDs and quest IDs. /// MapTableData.MapId &amp; 0x000fffff = WorldPixelID. /// </summary> /// <param name="longitude">Longitude position.</param> /// <param name="latitude">Latitude position.</param> /// <returns>Map pixel ID.</returns> public static int GetMapPixelIDFromLongitudeLatitude(int longitude, int latitude) { DFPosition pos = LongitudeLatitudeToMapPixel(longitude, latitude); return pos.Y * 1000 + pos.X; } /// <summary> /// Converts map pixel to world coord. /// </summary> /// <param name="mapPixelX">Map pixel X.</param> /// <param name="mapPixelY">Map pixel Y.</param> /// <returns>World position.</returns> public static DFPosition MapPixelToWorldCoord(int mapPixelX, int mapPixelY) { DFPosition pos = new DFPosition(); pos.X = mapPixelX * 32768; pos.Y = (499 - mapPixelY) * 32768; return pos; } /// <summary> /// Converts world coord to nearest map pixel. /// </summary> /// <param name="worldX">World X position in native Daggerfall units.</param> /// <param name="worldZ">World Z position in native Daggerfall units.</param> /// <returns>Map pixel position.</returns> public static DFPosition WorldCoordToMapPixel(int worldX, int worldZ) { DFPosition pos = new DFPosition(); pos.X = worldX / 32768; pos.Y = 499 - (worldZ / 32768); return pos; } /// <summary> /// Converts world coord back to longitude and latitude. /// </summary> /// <param name="worldX">World X position in native Daggerfall units.</param> /// <param name="worldZ">World Z position in native Daggerfall units.</param> /// <returns>Longitude and latitude.</returns> public static DFPosition WorldCoordToLongitudeLatitude(int worldX, int worldZ) { DFPosition mapPixel = WorldCoordToMapPixel(worldX, worldZ); DFPosition pos = new DFPosition(); pos.X = mapPixel.X * 128; pos.Y = (499 - mapPixel.Y) * 128; return pos; } /// <summary> /// Gets settings for specified map climate. /// </summary> /// <param name="worldClimate">Climate value from CLIMATE.PAK. Valid range is 223-232.</param> /// <returns>Climate settings for specified world climate value.</returns> public static DFLocation.ClimateSettings GetWorldClimateSettings(int worldClimate) { // Create settings struct DFLocation.ClimateSettings settings = new DFLocation.ClimateSettings(); settings.WorldClimate = worldClimate; // Set based on world climate switch (worldClimate) { case (int)Climates.Ocean: // Ocean settings.ClimateType = DFLocation.ClimateBaseType.Swamp; settings.GroundArchive = 402; settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_TemperateWoodland; settings.SkyBase = 24; settings.People = FactionFile.FactionRaces.Breton; break; case (int)Climates.Desert: case (int)Climates.Desert2: settings.ClimateType = DFLocation.ClimateBaseType.Desert; settings.GroundArchive = 2; settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_Desert; settings.SkyBase = 8; settings.People = FactionFile.FactionRaces.Redguard; break; case (int)Climates.Mountain: settings.ClimateType = DFLocation.ClimateBaseType.Mountain; settings.GroundArchive = 102; settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_Mountains; settings.SkyBase = 0; settings.People = FactionFile.FactionRaces.Nord; break; case (int)Climates.Rainforest: settings.ClimateType = DFLocation.ClimateBaseType.Swamp; settings.GroundArchive = 402; settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_RainForest; settings.SkyBase = 24; settings.People = FactionFile.FactionRaces.Redguard; break; case (int)Climates.Swamp: settings.ClimateType = DFLocation.ClimateBaseType.Swamp; settings.GroundArchive = 402; settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_Swamp; settings.SkyBase = 24; settings.People = FactionFile.FactionRaces.Breton; break; case (int)Climates.Subtropical: settings.ClimateType = DFLocation.ClimateBaseType.Desert; settings.GroundArchive = 2; settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_SubTropical; settings.SkyBase = 24; settings.People = FactionFile.FactionRaces.Breton; break; case (int)Climates.MountainWoods: settings.ClimateType = DFLocation.ClimateBaseType.Temperate; settings.GroundArchive = 102; settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_WoodlandHills; settings.SkyBase = 16; settings.People = FactionFile.FactionRaces.Breton; break; case (int)Climates.Woodlands: settings.ClimateType = DFLocation.ClimateBaseType.Temperate; settings.GroundArchive = 302; settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_TemperateWoodland; settings.SkyBase = 16; settings.People = FactionFile.FactionRaces.Breton; break; case (int)Climates.HauntedWoodlands: settings.ClimateType = DFLocation.ClimateBaseType.Temperate; settings.GroundArchive = 302; settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_HauntedWoodlands; settings.SkyBase = 16; settings.People = FactionFile.FactionRaces.Breton; break; default: settings.ClimateType = DFLocation.ClimateBaseType.Temperate; settings.GroundArchive = 302; settings.NatureArchive = (int)DFLocation.ClimateTextureSet.Nature_TemperateWoodland; settings.SkyBase = 16; settings.People = FactionFile.FactionRaces.Breton; break; } // Set nature set from nature archive index settings.NatureSet = (DFLocation.ClimateTextureSet)settings.NatureArchive; return settings; } #endregion #region Public Methods /// <summary> /// Load MAPS.BSA file. /// </summary> /// <param name="filePath">Absolute path to MAPS.BSA file.</param> /// <param name="usage">Specify if file will be accessed from disk, or loaded into RAM.</param> /// <param name="readOnly">File will be read-only if true, read-write if false.</param> /// <returns>True if successful, otherwise false.</returns> public bool Load(string filePath, FileUsage usage, bool readOnly) { // Validate filename if (!filePath.EndsWith("MAPS.BSA", StringComparison.InvariantCultureIgnoreCase)) return false; // Load PAK files string arena2Path = Path.GetDirectoryName(filePath); climatePak = new PakFile(Path.Combine(arena2Path, "CLIMATE.PAK")); politicPak = new PakFile(Path.Combine(arena2Path, "POLITIC.PAK")); // Load file isReady = false; if (!bsaFile.Load(filePath, usage, readOnly)) return false; // Create records array regions = new RegionRecord[RegionCount]; // Set ready flag isReady = true; return true; } /// <summary> /// Gets the name of specified region. Does not change the currently loaded region. /// </summary> /// <param name="region">Index of region.</param> /// <returns>Name of the region.</returns> public string GetRegionName(int region) { if (region < 0 || region >= RegionCount) return string.Empty; else return regionNames[region]; } /// <summary> /// Gets index of region with specified name. Does not change the currently loaded region. /// </summary> /// <param name="name">Name of region.</param> /// <returns>Index of found region, or -1 if not found.</returns> public int GetRegionIndex(string name) { // Search for region name for (int i = 0; i < RegionCount; i++) { if (regionNames[i] == name) return i; } return -1; } /// <summary> /// Load a region into memory by name and decompose it for use. /// </summary> /// <param name="name">Name of region.</param> /// <returns>True if successful, otherwise false.</returns> public bool LoadRegion(string name) { return LoadRegion(GetRegionIndex(name)); } /// <summary> /// Load a region into memory by index and decompose it for use. /// </summary> /// <param name="region">Index of region to load.</param> /// <returns>True if successful, otherwise false.</returns> public bool LoadRegion(int region) { // Validate if (region < 0 || region >= RegionCount) return false; // Auto discard previous record if (autoDiscardValue && lastRegion != -1) DiscardRegion(lastRegion); // Load record data int record = region * 4; regions[region].MapPItem = bsaFile.GetRecordProxy(record++); regions[region].MapDItem = bsaFile.GetRecordProxy(record++); regions[region].MapTable = bsaFile.GetRecordProxy(record++); regions[region].MapNames = bsaFile.GetRecordProxy(record); if (regions[region].MapNames.Length == 0 || regions[region].MapTable.Length == 0 || regions[region].MapPItem.Length == 0 || regions[region].MapDItem.Length == 0) return false; // Set region name regions[region].Name = regionNames[region]; // Read region if (!ReadRegion(region)) { DiscardRegion(region); return false; } // Set previous record lastRegion = region; return true; } /// <summary> /// Discard a region from memory. /// </summary> /// <param name="region">Index of region to discard.</param> public void DiscardRegion(int region) { // Validate if (region >= RegionCount) return; // Discard memory files and other data regions[region].Name = string.Empty; regions[region].MapNames = null; regions[region].MapTable = null; regions[region].MapPItem = null; regions[region].MapDItem = null; regions[region].DFRegion = new DFRegion(); } /// <summary> /// Discard all regions. /// </summary> public void DiscardAllRegions() { for (int index = 0; index < RegionCount; index++) { DiscardRegion(index); } } /// <summary> /// Gets a DFRegion by index. /// </summary> /// <param name="region">Index of region.</param> /// <returns>DFRegion.</returns> public DFRegion GetRegion(int region) { // Load the region if (!LoadRegion(region)) return new DFRegion(); return regions[region].DFRegion; } /// <summary> /// Gets a DFRegion by name. /// </summary> /// <param name="name">Name of region.</param> /// <returns>DFRegion.</returns> public DFRegion GetRegion(string name) { int Region = GetRegionIndex(name); if (-1 == Region) return new DFRegion(); return GetRegion(Region); } /// <summary> /// Gets a DFLocation representation of a location. /// </summary> /// <param name="region">Index of region.</param> /// <param name="location">Index of location.</param> /// <returns>DFLocation.</returns> public DFLocation GetLocation(int region, int location) { // Load the region if (!LoadRegion(region)) return new DFLocation(); // Read location DFLocation dfLocation = new DFLocation(); if (!ReadLocation(region, location, ref dfLocation)) return new DFLocation(); // Store indices dfLocation.RegionIndex = region; dfLocation.LocationIndex = location; // Generate smaller dungeon when possible if (UseSmallerDungeon(dfLocation)) GenerateSmallerDungeon(ref dfLocation); return dfLocation; } private bool UseSmallerDungeon(in DFLocation dfLocation) { // Do nothing if location has no dungeon or if a main story dungeon - these are never made smaller if (!dfLocation.HasDungeon || DaggerfallDungeon.IsMainStoryDungeon(dfLocation.MapTableData.MapId)) return false; // Collect any SiteLinks associated with this dungeon - there should only be one quest assignment per dungeon SiteLink[] siteLinks = QuestMachine.Instance.GetSiteLinks(SiteTypes.Dungeon, dfLocation.MapTableData.MapId); if (siteLinks != null && siteLinks.Length > 0) { // If a SiteLink and related Quest is found then use whatever SmallerDungeons setting as configured at time quest started // Marker assignments are not relocated when user changes SmallerDungeons state so we always use whatever quest compiled with Quest quest = QuestMachine.Instance.GetQuest(siteLinks[0].questUID); if (quest != null && quest.SmallerDungeonsState == QuestSmallerDungeonsState.Enabled) return true; else if (quest != null && quest.SmallerDungeonsState == QuestSmallerDungeonsState.Disabled) return false; } // If not a main story dungeon and no quest found in dungeon then just use setting as configured return DaggerfallUnity.Settings.SmallerDungeons; } /// <summary> /// Gets DFLocation representation of a location. /// </summary> /// <param name="regionName">Name of region.</param> /// <param name="locationName">Name of location.</param> /// <returns>DFLocation.</returns> public DFLocation GetLocation(string regionName, string locationName) { // Load region int Region = GetRegionIndex(regionName); if (!LoadRegion(Region)) return new DFLocation(); // Check location exists if (!regions[Region].DFRegion.MapNameLookup.ContainsKey(locationName)) return new DFLocation(); // Get location index int Location = regions[Region].DFRegion.MapNameLookup[locationName]; return GetLocation(Region, Location); } /// <summary> /// Lookup block name for exterior block from location data provided. /// </summary> /// <param name="dfLocation">DFLocation to read block name.</param> /// <param name="x">Block X coordinate.</param> /// <param name="y">Block Y coordinate.</param> /// <returns>Block name.</returns> public string GetRmbBlockName(in DFLocation dfLocation, int x, int y) { int index = y * dfLocation.Exterior.ExteriorData.Width + x; return dfLocation.Exterior.ExteriorData.BlockNames[index]; } /// <summary> /// Resolve block name for exterior block from X, Y coordinates. /// </summary> /// <param name="dfLocation">DFLocation to resolve block name.</param> /// <param name="x">Block X coordinate.</param> /// <param name="y">Block Y coordinate.</param> /// <returns>Block name.</returns> public string ResolveRmbBlockName(in DFLocation dfLocation, int x, int y) { // Get indices int offset = y * dfLocation.Exterior.ExteriorData.Width + x; byte blockIndex = dfLocation.Exterior.ExteriorData.BlockIndex[offset]; byte blockNumber = dfLocation.Exterior.ExteriorData.BlockNumber[offset]; byte blockCharacter = dfLocation.Exterior.ExteriorData.BlockCharacter[offset]; return ResolveRmbBlockName(dfLocation, blockIndex, blockNumber, blockCharacter); } /// <summary> /// Resolve block name from raw components. /// </summary> /// <param name="dfLocation">DFLocation to resolve block name.</param> /// <param name="blockIndex">Block index.</param> /// <param name="blockNumber">Block number.</param> /// <param name="blockCharacter">Block character.</param> /// <returns>Block name.</returns> public string ResolveRmbBlockName(in DFLocation dfLocation, byte blockIndex, byte blockNumber, byte blockCharacter) { string letter1 = string.Empty; string letter2 = string.Empty; string numbers = string.Empty; // Get prefix string prefix = rmbBlockPrefixes[blockIndex]; // Get letter 1 if ((blockCharacter & 0x10) != 0) { int asciiValue = dfLocation.Exterior.ExteriorData.Letter1ForRMBName; letter1 = char.ConvertFromUtf32(asciiValue); } else letter1 = "A"; // Get letter 2 letter2 = letter2Array[(byte)(2 * blockCharacter) >> 6]; // Get block number as a string string blockNumberString = blockNumber.ToString(); if (blockIndex == 13 || blockIndex == 14) { // Handle temple numbers int asciivalue = (blockCharacter & 0xF) + 65; numbers = char.ConvertFromUtf32(asciivalue) + blockNumberString; } else { // Numbers are uniform in non-temple blocks numbers = string.Format("{0:00}", blockNumber); } return prefix + letter1 + letter2 + numbers + ".RMB"; } /// <summary> /// Reads climate index from CLIMATE.PAK based on world pixel. /// </summary> /// <param name="mapPixelX">Map pixel X position.</param> /// <param name="mapPixelY">Map pixel Y position.</param> public int GetClimateIndex(int mapPixelX, int mapPixelY) { // Add +1 to X coordinate to line up with height map mapPixelX += 1; return climatePak.GetValue(mapPixelX, mapPixelY); } /// <summary> /// Reads politic index from POLITIC.PAK based on world pixel. /// </summary> /// <param name="mapPixelX">Map pixel X position.</param> /// <param name="mapPixelY">Map pixel Y position.</param> public int GetPoliticIndex(int mapPixelX, int mapPixelY) { mapPixelX += 1; return politicPak.GetValue(mapPixelX, mapPixelY); } /// <summary> /// Sets climate index from CLIMATE.PAK based on world pixel. /// Allows loaded climate data from Pak file to be modified by mods. /// </summary> /// <param name="mapPixelX">Map pixel X position.</param> /// <param name="mapPixelY">Map pixel Y position.</param> /// <param name="value">The climate to set for the specified map pixel.</param> /// <returns>True if climate index was set, false otherwise.</returns> public bool SetClimateIndex(int mapPixelX, int mapPixelY, Climates value) { mapPixelX += 1; return climatePak.SetValue(mapPixelX, mapPixelY, (byte)value); } /// <summary> /// Reads politic index from POLITIC.PAK based on world pixel. /// Allows loaded region data from Pak file to be modified by mods. /// </summary> /// <param name="mapPixelX">Map pixel X position.</param> /// <param name="mapPixelY">Map pixel Y position.</param> /// <param name="value">The politic index to set for the specified map pixel.</param> /// <returns>True if politic index was set, false otherwise.</returns> public bool SetPoliticIndex(int mapPixelX, int mapPixelY, byte value) { mapPixelX += 1; return politicPak.SetValue(mapPixelX, mapPixelY, value); } #endregion #region Readers /// <summary> /// Read a region. /// </summary> /// <param name="region">The region index to read.</param> /// <returns>True if successful, otherwise false.</returns> private bool ReadRegion(int region) { try { // Store region name regions[region].DFRegion.Name = regionNames[region]; // Read map names BinaryReader reader = regions[region].MapNames.GetReader(); ReadMapNames(ref reader, region); // Read map table reader = regions[region].MapTable.GetReader(); ReadMapTable(ref reader, region); } catch (Exception e) { DiscardRegion(region); Console.WriteLine(e.Message); return false; } // Add any additional replacement location data to the region, assigning locationIndex WorldDataReplacement.GetDFRegionAdditionalLocationData(region, ref regions[region].DFRegion); return true; } /// <summary> /// Read a location from the currently loaded region. /// </summary> /// <param name="region">Region index.</param> /// <param name="location">Location index.</param> /// <param name="dfLocation">DFLocation object to receive data.</param> /// <returns>True if successful, otherwise false.</returns> private bool ReadLocation(int region, int location, ref DFLocation dfLocation) { // Check for replacement location data and use it if found if (WorldDataReplacement.GetDFLocationReplacementData(region, location, out dfLocation)) return true; try { // Store parent region name dfLocation.RegionName = RegionNames[region]; // Read MapPItem for this location BinaryReader reader = regions[region].MapPItem.GetReader(); ReadMapPItem(ref reader, region, location, ref dfLocation); // Read MapDItem for this location reader = regions[region].MapDItem.GetReader(); ReadMapDItem(ref reader, region, ref dfLocation); // Copy RegionMapTable data to this location dfLocation.MapTableData = regions[region].DFRegion.MapTable[location]; // Read climate and politic data ReadClimatePoliticData(ref dfLocation); // Set loaded flag dfLocation.Loaded = true; return true; } catch (Exception e) { Console.WriteLine(e.Message); return false; } } /// <summary> /// Reads information from CLIMATE.PAK and POLITIC.PAK. /// </summary> /// <param name="dfLocation">DFLocation.</param> private void ReadClimatePoliticData(ref DFLocation dfLocation) { DFPosition pos = LongitudeLatitudeToMapPixel(dfLocation.MapTableData.Longitude, dfLocation.MapTableData.Latitude); // Read politic data. This should always equal region index + 128. dfLocation.Politic = politicPak.GetValue(pos.X, pos.Y); // Read climate data int worldClimate = climatePak.GetValue(pos.X, pos.Y); dfLocation.Climate = MapsFile.GetWorldClimateSettings(worldClimate); } /// <summary> /// Read map names. /// </summary> /// <param name="reader">A binary reader to data.</param> /// <param name="region">Destination region index.</param> private void ReadMapNames(ref BinaryReader reader, int region) { // Location count reader.BaseStream.Position = 0; regions[region].DFRegion.LocationCount = reader.ReadUInt32(); // Read names regions[region].DFRegion.MapNames = new String[regions[region].DFRegion.LocationCount]; regions[region].DFRegion.MapNameLookup = new System.Collections.Generic.Dictionary<string, int>(); for (int i = 0; i < regions[region].DFRegion.LocationCount; i++) { // Read map name data regions[region].DFRegion.MapNames[i] = FileProxy.ReadCStringSkip(reader, 0, 32); // Add to dictionary if (!regions[region].DFRegion.MapNameLookup.ContainsKey(regions[region].DFRegion.MapNames[i])) regions[region].DFRegion.MapNameLookup.Add(regions[region].DFRegion.MapNames[i], i); } } /// <summary> /// Read map table. /// </summary> /// <param name="reader">A binary reader to data.</param> /// <param name="region">Destination region index.</param> private void ReadMapTable(ref BinaryReader reader, int region) { // Read map table for each location UInt32 bitfield; reader.BaseStream.Position = 0; regions[region].DFRegion.MapTable = new DFRegion.RegionMapTable[regions[region].DFRegion.LocationCount]; regions[region].DFRegion.MapIdLookup = new System.Collections.Generic.Dictionary<int, int>(); for (int i = 0; i < regions[region].DFRegion.LocationCount; i++) { // Read map table data regions[region].DFRegion.MapTable[i].MapId = reader.ReadInt32(); bitfield = reader.ReadUInt32(); regions[region].DFRegion.MapTable[i].Longitude = (int)(bitfield & 0x1FFFFFF) >> 8; regions[region].DFRegion.MapTable[i].LocationType = (DFRegion.LocationTypes)((4 * bitfield) >> 27); regions[region].DFRegion.MapTable[i].Discovered = ((bitfield >> 24) & 0x40) != 0; regions[region].DFRegion.MapTable[i].Latitude = (reader.ReadInt32() & 0xFFFFFF) >> 8; regions[region].DFRegion.MapTable[i].DungeonType = (DFRegion.DungeonTypes)reader.ReadByte(); regions[region].DFRegion.MapTable[i].Key = reader.ReadUInt32(); // Add to dictionary if (!regions[region].DFRegion.MapIdLookup.ContainsKey(regions[region].DFRegion.MapTable[i].MapId)) regions[region].DFRegion.MapIdLookup.Add(regions[region].DFRegion.MapTable[i].MapId, i); } } /// <summary>Read location count from maps file, used to get count in /// classic datafiles only, excluding added locations. </summary> private uint ReadLocationCount(int region) { BinaryReader reader = regions[region].MapNames.GetReader(); reader.BaseStream.Position = 0; return reader.ReadUInt32(); } /// <summary> /// Quickly reads the LocationId with minimal overhead. /// Region must be loaded before calling this method. /// </summary> /// <param name="region">Region index.</param> /// <param name="location">Location index.</param> /// <returns>LocationId.</returns> public int ReadLocationIdFast(int region, int location) { // Added new locations will put the LocationId in regions map table, since it doesn't exist in classic data if (regions[region].DFRegion.MapTable[location].LocationId != 0) return regions[region].DFRegion.MapTable[location].LocationId; // Get datafile location count (excluding added locations) uint locationCount = ReadLocationCount(region); // Get reader BinaryReader reader = regions[region].MapPItem.GetReader(); // Position reader at location record by reading offset and adding to end of offset table reader.BaseStream.Position = location * 4; reader.BaseStream.Position = (locationCount * 4) + reader.ReadUInt32(); // Skip doors (+6 bytes per door) UInt32 doorCount = reader.ReadUInt32(); reader.BaseStream.Position += doorCount * 6; // Skip to LocationId (+33 bytes) reader.BaseStream.Position += 33; // Read the LocationId int locationId = reader.ReadUInt16(); return locationId; } /// <summary> /// Reads MapPItem data. /// </summary> /// <param name="reader">A binary reader to data.</param> /// <param name="region">Region index.</param> /// <param name="location">Location Index.</param> /// <param name="dfLocation">Destination DFLocation.</param> private void ReadMapPItem(ref BinaryReader reader, int region, int location, ref DFLocation dfLocation) { // Get datafile location count (excluding added locations) uint locationCount = ReadLocationCount(region); // Position reader at location record by reading offset and adding to end of offset table reader.BaseStream.Position = location * 4; reader.BaseStream.Position = (locationCount * 4) + reader.ReadUInt32(); // Store name dfLocation.Name = regions[region].DFRegion.MapNames[location]; // Read LocationRecordElement ReadLocationRecordElement(ref reader, region, ref dfLocation.Exterior.RecordElement); // Read BuildingListHeader dfLocation.Exterior.BuildingCount = reader.ReadUInt16(); dfLocation.Exterior.Unknown1 = new Byte[5]; for (int i = 0; i < 5; i++) dfLocation.Exterior.Unknown1[i] = reader.ReadByte(); // Read BuildingData dfLocation.Exterior.Buildings = new DFLocation.BuildingData[dfLocation.Exterior.BuildingCount]; for (int building = 0; building < dfLocation.Exterior.BuildingCount; building++) { dfLocation.Exterior.Buildings[building].NameSeed = reader.ReadUInt16(); dfLocation.Exterior.Buildings[building].ServiceTimeLimit = reader.ReadUInt32(); dfLocation.Exterior.Buildings[building].Unknown = reader.ReadUInt16(); dfLocation.Exterior.Buildings[building].Unknown2 = reader.ReadUInt16(); dfLocation.Exterior.Buildings[building].Unknown3 = reader.ReadUInt32(); dfLocation.Exterior.Buildings[building].Unknown4 = reader.ReadUInt32(); dfLocation.Exterior.Buildings[building].FactionId = reader.ReadUInt16(); dfLocation.Exterior.Buildings[building].Sector = reader.ReadInt16(); dfLocation.Exterior.Buildings[building].LocationId = reader.ReadUInt16(); dfLocation.Exterior.Buildings[building].BuildingType = (DFLocation.BuildingTypes)reader.ReadByte(); dfLocation.Exterior.Buildings[building].Quality = reader.ReadByte(); } // Read ExteriorData dfLocation.Exterior.ExteriorData.AnotherName = FileProxy.ReadCStringSkip(reader, 0, 32); dfLocation.Exterior.ExteriorData.MapId = reader.ReadInt32(); dfLocation.Exterior.ExteriorData.LocationId = reader.ReadUInt32(); dfLocation.Exterior.ExteriorData.Width = reader.ReadByte(); dfLocation.Exterior.ExteriorData.Height = reader.ReadByte(); dfLocation.Exterior.ExteriorData.Unknown2 = reader.ReadBytes(4); dfLocation.Exterior.ExteriorData.Letter1ForRMBName = reader.ReadByte(); dfLocation.Exterior.ExteriorData.PortTownAndUnknown = reader.ReadByte(); dfLocation.Exterior.ExteriorData.Unknown3 = reader.ReadByte(); dfLocation.Exterior.ExteriorData.BlockIndex = reader.ReadBytes(64); dfLocation.Exterior.ExteriorData.BlockNumber = reader.ReadBytes(64); dfLocation.Exterior.ExteriorData.BlockCharacter = reader.ReadBytes(64); dfLocation.Exterior.ExteriorData.Unknown4 = reader.ReadBytes(34); dfLocation.Exterior.ExteriorData.NullValue1 = reader.ReadUInt64(); dfLocation.Exterior.ExteriorData.NullValue2 = reader.ReadByte(); dfLocation.Exterior.ExteriorData.Unknown5 = new UInt32[22]; for (int i = 0; i < 22; i++) dfLocation.Exterior.ExteriorData.Unknown5[i] = reader.ReadUInt32(); dfLocation.Exterior.ExteriorData.NullValue3 = reader.ReadBytes(40); dfLocation.Exterior.ExteriorData.Unknown6 = reader.ReadUInt32(); // Get block names int totalBlocks = dfLocation.Exterior.ExteriorData.Width * dfLocation.Exterior.ExteriorData.Height; dfLocation.Exterior.ExteriorData.BlockNames = new string[totalBlocks]; for (int i = 0; i < totalBlocks; i++) { // Construct block name dfLocation.Exterior.ExteriorData.BlockNames[i] = ResolveRmbBlockName( dfLocation, dfLocation.Exterior.ExteriorData.BlockIndex[i], dfLocation.Exterior.ExteriorData.BlockNumber[i], dfLocation.Exterior.ExteriorData.BlockCharacter[i]); } } /// <summary> /// Read LocationRecordElementData common to both MapPItem and MapDItem /// </summary> /// <param name="reader">A binary reader to data.</param> /// <param name="region">Region index.</param> /// <param name="recordElement">Destination DFLocation.LocationRecordElement.</param> private void ReadLocationRecordElement(ref BinaryReader reader, int region, ref DFLocation.LocationRecordElement recordElement) { // Read LocationDoorElement UInt32 doorCount = reader.ReadUInt32(); recordElement.DoorCount = doorCount; recordElement.Doors = new DFLocation.LocationDoorElement[doorCount]; for (int door = 0; door < doorCount; door++) { recordElement.Doors[door].BuildingDataIndex = reader.ReadUInt16(); recordElement.Doors[door].NullValue = reader.ReadByte(); recordElement.Doors[door].Mask = reader.ReadByte(); recordElement.Doors[door].Unknown1 = reader.ReadByte(); recordElement.Doors[door].Unknown2 = reader.ReadByte(); } // Read LocationRecordElementHeader recordElement.Header.AlwaysOne1 = reader.ReadUInt32(); recordElement.Header.NullValue1 = reader.ReadUInt16(); recordElement.Header.NullValue2 = reader.ReadByte(); recordElement.Header.X = reader.ReadInt32(); recordElement.Header.NullValue3 = reader.ReadUInt32(); recordElement.Header.Y = reader.ReadInt32(); recordElement.Header.IsExterior = reader.ReadUInt16(); recordElement.Header.NullValue4 = reader.ReadUInt16(); recordElement.Header.Unknown1 = reader.ReadUInt32(); recordElement.Header.Unknown2 = reader.ReadUInt32(); recordElement.Header.AlwaysOne2 = reader.ReadUInt16(); recordElement.Header.LocationId = reader.ReadUInt16(); recordElement.Header.NullValue5 = reader.ReadUInt32(); recordElement.Header.IsInterior = reader.ReadUInt16(); recordElement.Header.ExteriorLocationId = reader.ReadUInt32(); recordElement.Header.NullValue6 = reader.ReadBytes(26); recordElement.Header.LocationName = FileProxy.ReadCStringSkip(reader, 0, 32); recordElement.Header.Unknown3 = reader.ReadBytes(9); } /// <summary> /// Reads MapDItem data. /// </summary> /// <param name="reader">A binary reader to data.</param> /// <param name="region">Region index.</param> /// <param name="dfLocation">Destination DFLocation.</param> private void ReadMapDItem(ref BinaryReader reader, int region, ref DFLocation dfLocation) { // Exit if no data dfLocation.HasDungeon = false; if (reader.BaseStream.Length == 0) return; // Find dungeon offset bool found = false; UInt32 locationId = dfLocation.Exterior.RecordElement.Header.LocationId; UInt32 dungeonCount = reader.ReadUInt32(); DungeonOffset dungeonOffset = new DungeonOffset(); for (int i = 0; i < dungeonCount; i++) { // Search for dungeon offset matching location id dungeonOffset.Offset = reader.ReadUInt32(); dungeonOffset.IsDungeon = reader.ReadUInt16(); dungeonOffset.ExteriorLocationId = reader.ReadUInt16(); if (dungeonOffset.ExteriorLocationId == locationId) { found = true; break; } } // Exit if correct offset not found if (!found) return; // Position reader at dungeon record by reading offset and adding to end of offset table reader.BaseStream.Position = 4 + dungeonCount * 8 + dungeonOffset.Offset; // Read LocationRecordElement ReadLocationRecordElement(ref reader, region, ref dfLocation.Dungeon.RecordElement); // Read DungeonHeader dfLocation.Dungeon.Header.NullValue1 = reader.ReadUInt16(); dfLocation.Dungeon.Header.Unknown1 = reader.ReadUInt32(); dfLocation.Dungeon.Header.Unknown2 = reader.ReadUInt32(); dfLocation.Dungeon.Header.BlockCount = reader.ReadUInt16(); dfLocation.Dungeon.Header.Unknown3 = reader.ReadBytes(5); // Read DungeonBlock elements dfLocation.Dungeon.Blocks = new DFLocation.DungeonBlock[dfLocation.Dungeon.Header.BlockCount]; for (int i = 0; i < dfLocation.Dungeon.Header.BlockCount; i++) { // Read data dfLocation.Dungeon.Blocks[i].X = reader.ReadSByte(); dfLocation.Dungeon.Blocks[i].Z = reader.ReadSByte(); dfLocation.Dungeon.Blocks[i].BlockNumberStartIndexBitfield = reader.ReadUInt16(); // Decompose bitfield UInt16 bitfield = dfLocation.Dungeon.Blocks[i].BlockNumberStartIndexBitfield; dfLocation.Dungeon.Blocks[i].BlockNumber = (UInt16)(bitfield & 0x3ff); dfLocation.Dungeon.Blocks[i].IsStartingBlock = ((bitfield & 0x400) == 0x400); dfLocation.Dungeon.Blocks[i].BlockIndex = (Byte)(bitfield >> 11); // Compose block name dfLocation.Dungeon.Blocks[i].BlockName = String.Format("{0}{1:0000000}.RDB", rdbBlockLetters[dfLocation.Dungeon.Blocks[i].BlockIndex], dfLocation.Dungeon.Blocks[i].BlockNumber); } // Set dungeon flag dfLocation.HasDungeon = true; } #endregion #region ExperimentalSmallerDungeons // Generates a smaller dungeon by overwriting the block layout // Creates a single interior block surrounded by 4 border blocks (smallest viable dungeon) // Should not be called for main story dungeons // Will filter out dungeons that are already below a threshold size void GenerateSmallerDungeon(ref DFLocation dfLocation) { // Smallest viable dungeon block count, comprised of 1x interior block and 4x border blocks const int threshold = 5; // Must not be called for main story dungeons if (DaggerfallWorkshop.DaggerfallDungeon.IsMainStoryDungeon(dfLocation.MapTableData.MapId)) throw new Exception("GenerateSmallerDungeon() must not be called on a main story dungeon."); // Ignore small dungeons under threshold - this will exclude already small crypts and the like if (dfLocation.Dungeon.Blocks == null || dfLocation.Dungeon.Blocks.Length <= threshold) return; // Dungeon layout might be looked up multiple times in a row by different systems // It is expected to see this output more than once in log when generating quests, etc. // Disabling for now just to reduce spam to logs //UnityEngine.Debug.LogFormat("Generating smaller dungeon for {0}/{1}", dfLocation.RegionName, dfLocation.Name); // TODO: Some potential issues for later: // * Quests assigned to a dungeon will probably break/crash as marker layout different in smaller dungeon, must handle this // * Might need to ensure automap cache is cleared when switching smaller dungeons setting on/off // Seed random generation with map ID so we get the same layout each time map is looked up DaggerfallWorkshop.DFRandom.Seed = (uint)dfLocation.MapTableData.MapId; // Generate new dungeon layout with smallest viable dungeon (1x normal block surrounded by 4x border blocks) DFLocation.DungeonBlock[] layout = new DFLocation.DungeonBlock[5]; layout[0] = GenerateRDBBlock(0, 0, false, true, dfLocation); // Central starting block layout[1] = GenerateRDBBlock(0, -1, true, false, dfLocation); // North border block layout[2] = GenerateRDBBlock(-1, 0, true, false, dfLocation); // West border block layout[3] = GenerateRDBBlock(1, 0, true, false, dfLocation); // East border block layout[4] = GenerateRDBBlock(0, 1, true, false, dfLocation); // South border block // Inject new block array into location dfLocation.Dungeon.Blocks = layout; } /// <summary> /// Generates a new dungeon block by selecting one at random from a reference dungeon layout. /// </summary> /// <param name="x">X block tile position.</param> /// <param name="z">Z block tile position.</param> /// <param name="borderBlock">True to select a border block, false to select an interior block.</param> /// <param name="startingBlock">True to make this a starting block (must only be one).</param> /// <param name="dfLocation">Reference location to select a random block from.</param> /// <returns>DFLocation.DungeonBlock</returns> DFLocation.DungeonBlock GenerateRDBBlock(sbyte x, sbyte z, bool borderBlock, bool startingBlock, in DFLocation dfLocation) { // Get random block from reference location and overwrite some properties DFLocation.DungeonBlock block = GetRandomBlock(borderBlock, dfLocation); block.X = x; block.Z = z; block.IsStartingBlock = startingBlock; return block; } /// <summary> /// Gets a random block from reference location. /// </summary> /// <param name="borderBlock">True to select a border block, false to select an interior block.</param> /// <param name="dfLocation">Reference location to select a random block from.</param> /// <returns>DFLocation.DungeonBlock</returns> DFLocation.DungeonBlock GetRandomBlock(bool borderBlock, in DFLocation dfLocation) { List<DFLocation.DungeonBlock> filteredBlocks = new List<DFLocation.DungeonBlock>(); foreach (DFLocation.DungeonBlock block in dfLocation.Dungeon.Blocks) { // Is this a border block? bool isBorderBlock = block.BlockName.StartsWith("B", StringComparison.InvariantCultureIgnoreCase); // Collect blocks based on params if (borderBlock && isBorderBlock) filteredBlocks.Add(block); else if (!borderBlock && !isBorderBlock) filteredBlocks.Add(block); } // Should have found at least one block if (filteredBlocks.Count == 0) throw new Exception(string.Format("GetRandomBlock() failed to find a suitable block. borderBlock={0}, region={1}, location={2}", borderBlock.ToString(), dfLocation.RegionName, dfLocation.Name)); // Select a random index from pool and return this block return filteredBlocks[DaggerfallWorkshop.DFRandom.random_range(filteredBlocks.Count)]; } #endregion } }
42.523673
210
0.580418
[ "MIT" ]
marcospampi/daggerfall-unity
Assets/Scripts/API/MapsFile.cs
59,278
C#
using System.Web.Mvc; using Abp.Web.Mvc.Authorization; namespace ShopCart.Web.Controllers { [AbpMvcAuthorize] public class HomeController : ShopCartControllerBase { public ActionResult Index() { return View(); } } }
19
56
0.639098
[ "MIT" ]
Nil9666/ShopCart-EF
src/ShopCart.Web/Controllers/HomeController.cs
268
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Draco.Api.InternalModels.Extensions; using Draco.Core.Interfaces; using Draco.Core.ObjectStorage.Interfaces; using Draco.Core.ObjectStorage.Models; using Newtonsoft.Json.Linq; using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Draco.Api.Proxies { /// <summary> /// This provider acts as a proxy to (output) object provider API (/src/draco/api/ObjectStorageProvider.Api) endpoints. /// For more information on object providers, see /doc/architecture/execution-objects.md#object-providers. /// </summary> public class ProxyOutputObjectAccessorProvider : IOutputObjectAccessorProvider { private readonly IJsonHttpClient jsonHttpClient; private readonly ProxyConfiguration proxyConfig; public ProxyOutputObjectAccessorProvider(IJsonHttpClient jsonHttpClient, ProxyConfiguration proxyConfig) { this.jsonHttpClient = jsonHttpClient; this.proxyConfig = proxyConfig; } public async Task<JObject> GetReadableAccessorAsync(OutputObjectAccessorRequest accessorRequest) { if (accessorRequest == null) { throw new ArgumentNullException(nameof(accessorRequest)); } var apiModel = accessorRequest.ToApiModel(); var apiUrl = $"{proxyConfig.BaseUrl.TrimEnd('/')}/readable"; var apiResponse = await jsonHttpClient.PostAsync<JObject>(apiUrl, apiModel); switch (apiResponse.StatusCode) { case HttpStatusCode.OK: return apiResponse.Content; default: throw new HttpRequestException($"[Request {accessorRequest.ExecutionMetadata.ExecutionId}]: " + $"[Output Object {accessorRequest.ObjectMetadata.Name}]: " + $"Object provider API [{apiUrl}] responded with an unexpected status code: [{apiResponse.StatusCode}]."); } } public async Task<JObject> GetWritableAccessorAsync(OutputObjectAccessorRequest accessorRequest) { if (accessorRequest == null) { throw new ArgumentNullException(nameof(accessorRequest)); } var apiModel = accessorRequest.ToApiModel(); var apiUrl = $"{proxyConfig.BaseUrl.TrimEnd('/')}/writable"; var apiResponse = await jsonHttpClient.PostAsync<JObject>(apiUrl, apiModel); switch (apiResponse.StatusCode) { case HttpStatusCode.OK: return apiResponse.Content; default: throw new HttpRequestException($"[Request {accessorRequest.ExecutionMetadata.ExecutionId}]: " + $"[Output Object {accessorRequest.ObjectMetadata.Name}]: " + $"Object provider API [{apiUrl}] responded with an unexpected status code: [{apiResponse.StatusCode}]."); } } } }
42.184211
156
0.614785
[ "MIT" ]
timmyreilly/draco
src/draco/api/Api.Proxies/ProxyOutputObjectAccessorProvider.cs
3,208
C#
using System; using System.Net.Http; using System.Net.Mime; using System.Threading.Tasks; using MediaBrowser.Common.Net; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using MyShows.Configuration; namespace MyShows.Api { [ApiController] [Route("MyShows/v2")] [Produces(MediaTypeNames.Application.Json)] public class Api20Controller : ControllerBase { private readonly IHttpClientFactory _httpClientFactory; public Api20Controller( IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; } [HttpPost("login")] [ProducesResponseType(StatusCodes.Status200OK)] public async Task<object> LogIn( [FromForm] string id, [FromForm] string login, [FromForm] string password) { try { var httpClient = GetHttpClient(); var (token, error) = await OAuthHelper.GetToken(httpClient, login, password); if (error != null) { return new { success = false, statusText = error.error_description }; } Plugin.Instance.PluginConfiguration.AddUser(new UserConfig { ApiVersion = MyShowsApi.MyShowsApiVersion.V20, AccessToken = token.access_token, RefreshToken = token.refresh_token, ExpirationTime = DateTime.Now.AddSeconds(token.expires_in), Id = id, Name = login }); } catch (HttpRequestException e) { return new { success = false, statusText = e.Message }; } return new { success = true }; } private HttpClient GetHttpClient() { var client = _httpClientFactory.CreateClient(NamedClient.Default); return client; } } }
28.986667
93
0.520699
[ "MIT" ]
shemanaev/jellyfin-plugin-myshows
MyShows/Api/Api20Controller.cs
2,174
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Puzzle { virtual public string ToString(string id) { return ""; } }
16
46
0.651042
[ "Apache-2.0", "MIT" ]
BenRQ/valkyrie
unity/Assets/Scripts/Quest/Puzzle.cs
192
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using BuildXL.Utilities.Collections; using BuildXL.Utilities.Configuration.Resolvers; namespace BuildXL.Utilities.Configuration { /// <summary> /// Settings for MSBuild resolver /// </summary> public interface IMsBuildResolverSettings : IProjectGraphResolverSettings, IUntrackingSettings { /// <summary> /// The directory where the resolver starts parsing the enlistment /// (including all sub-directories recursively). Not necessarily the /// same as <see cref="IProjectGraphResolverSettings.Root"/> for cases where the codebase to process /// starts in a subdirectory of the enlistment. /// </summary> /// <remarks> /// If this is not specified, it will default to <see cref="IProjectGraphResolverSettings.Root"/> /// </remarks> AbsolutePath RootTraversal { get; } /// <summary> /// Whether pips scheduled by this resolver should run in an isolated container. /// </summary> bool RunInContainer { get; } /// <summary> /// Collection of directories to search for the required MsBuild assemblies and MsBuild.exe. /// </summary> /// <remarks> /// If this is not defined, locations in %PATH% are used /// Locations are traversed in order /// </remarks> IReadOnlyList<DirectoryArtifact> MsBuildSearchLocations { get; } /// <summary> /// Whether to use the full framework or dotnet core version of MSBuild. /// </summary> /// <remarks> /// Selected runtime is used both for build evaluation and execution. /// Default is full framework. /// Observe that using the full framework version means that msbuild.exe is expected to be found in msbuildSearchLocations /// (or PATH if not specified). If using the dotnet core version, the same logic applies but to msbuild.dll /// </remarks> string MsBuildRuntime { get; } /// <summary> /// Collection of directories to search for dotnet.exe, when DotNetCore is specified as the msBuildRuntime. /// </summary> /// <remarks> /// If not specified, locations in %PATH% are used. /// Locations are traversed in specification order. /// </remarks> IReadOnlyList<DirectoryArtifact> DotNetSearchLocations { get; } /// <summary> /// Optional file paths for the projects or solutions that should be used to start parsing. These are relative /// paths with respect to the root traversal. /// </summary> /// <remarks> /// If not provided, BuildXL will attempt to find a candidate under the root traversal. If more than one /// candidate is available, the process will fail. /// </remarks> IReadOnlyList<RelativePath> FileNameEntryPoints { get; } /// <summary> /// Targets to execute on the entry point project. /// </summary> /// <remarks> /// If not provided, the default targets are used. /// Initial targets are mapped to /target (or /t) when invoking MSBuild for the entry point project. /// </remarks> IReadOnlyList<string> InitialTargets { get; } /// <summary> /// Global properties to use for all projects. /// </summary> IReadOnlyDictionary<string, string> GlobalProperties { get; } /// <summary> /// Allows requesting additional MSBuild log output. /// When "none" or null, no additional MSBuild logging is performed besides normal level console /// output. Otherwise an additional text log 'msbuild.log' is generated for /// MSBuild projects, alongside other log files, with the requested verbosity. /// Typically the value requested here is 'diag' or 'diagnostic' /// to get a lot of (expensive) logging. /// </summary> string LogVerbosity { get; } /// <summary> /// When true, an msbuild.binlog is generated for each MSBuild project alongside /// any existing logs. /// </summary> bool? EnableBinLogTracing { get; } /// <summary> /// When true, additional engine trace outputs are requested from MSBuild. /// </summary> bool? EnableEngineTracing { get; } /// <summary> /// Whether each project has implicit access to the transitive closure of its references. /// </summary> /// <remarks> /// Turning this option on may imply a decrease in build performance, but many existing MSBuild repos rely on an equivalent feature. /// Defaults to false. /// </remarks> bool? EnableTransitiveProjectReferences { get; } /// <summary> /// When true, MSBuild projects are not treated as first class citizens and MSBuild is instructed to build each project using the legacy mode, /// which relies on SDK conventions to respect the boundaries of a project and not build dependencies. /// </summary> /// <remarks> /// The legacy mode is less restrictive than the /// default mode, where explicit project references to represent project dependencies are strictly enforced, but a decrease in build performance and /// other build failures may occur (e.g. double writes due to overbuilds). /// Defaults to false. /// </remarks> bool? UseLegacyProjectIsolation { get; } /// <summary> /// Policy to apply when a double write occurs. /// </summary> /// <remarks> /// By default double writes are only allowed if the produced content is the same. /// </remarks> RewritePolicy? DoubleWritePolicy { get; } /// <summary> /// Whether projects are allowed to not specify their target protocol. /// </summary> /// <remarks> /// When true, default targets will be used as a heuristic. Defaults to false. /// </remarks> bool? AllowProjectsToNotSpecifyTargetProtocol { get; } /// <summary> /// Whether VBCSCompiler is allowed to be launched as a service to serve managed compilation requests /// </summary> /// <remarks> /// Defaults to on. /// This option will only be honored when process breakaway is supported by the underlying sandbox. /// </remarks> bool? UseManagedSharedCompilation { get; } } /// <nodoc/> public static class MsBuildResolverSettingsExtensions { /// <summary> /// Whether MSBuildRuntime is DotNetCore. /// </summary> /// <remarks> /// Keep in sync with Public\Sdk\Public\Prelude\Prelude.Configuration.Resolvers.dsc /// If not specified, the default is full framework, so this function returns false in that case. /// </remarks> public static bool ShouldRunDotNetCoreMSBuild(this IMsBuildResolverSettings msBuildResolverSettings) => msBuildResolverSettings.MsBuildRuntime == "DotNetCore"; } }
44.572289
168
0.615624
[ "MIT" ]
Microsoft/BuildXL
Public/Src/Utilities/Configuration/Resolvers/IMsBuildResolverSettings.cs
7,399
C#
using System; using System.Collections.Generic; using System.IO; using System.Diagnostics; using System.Linq; using System.Threading; using Java.Interop; namespace Java.InteropTests { public class TestJVM : JreRuntime { static JreRuntimeOptions CreateBuilder (string[] jars) { var dir = Path.GetDirectoryName (typeof (TestJVM).Assembly.Location); var builder = new JreRuntimeOptions () { JvmLibraryPath = Environment.GetEnvironmentVariable ("JI_JVM_PATH"), JniAddNativeMethodRegistrationAttributePresent = true, }; if (jars != null) { foreach (var jar in jars) builder.ClassPath.Add (Path.Combine (dir, jar)); } builder.AddOption ("-Xcheck:jni"); builder.TypeManager = new JreTypeManager (); return builder; } Dictionary<string, Type> typeMappings; public TestJVM (string[] jars = null, Dictionary<string, Type> typeMappings = null) : base (CreateBuilder (jars)) { this.typeMappings = typeMappings; } class JreTypeManager : JniTypeManager { protected override IEnumerable<Type> GetTypesForSimpleReference (string jniSimpleReference) { foreach (var t in base.GetTypesForSimpleReference (jniSimpleReference)) yield return t; var mappings = ((TestJVM) Runtime).typeMappings; Type target; if (mappings != null && mappings.TryGetValue (jniSimpleReference, out target)) yield return target; } protected override IEnumerable<string> GetSimpleReferences (Type type) { return base.GetSimpleReferences (type) .Concat (CreateSimpleReferencesEnumerator (type)); } IEnumerable<string> CreateSimpleReferencesEnumerator (Type type) { var mappings = ((TestJVM) Runtime).typeMappings; if (mappings == null) yield break; foreach (var e in mappings) { if (e.Value == type) yield return e.Key; } } } } }
26.549296
94
0.697082
[ "MIT" ]
dellis1972/Java.Interop
tests/TestJVM/TestJVM.cs
1,885
C#
/* * Generated code file by Il2CppInspector - http://www.djkaty.com - https://github.com/djkaty */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; // Image 46: Assembly-CSharp.dll - Assembly: Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - Types 4339-9572 public class MessageLogManager : Singleton<MessageLogManager> // TypeDefIndex: 5814 { // Fields private List<string> messageList; // 0x10 private const int MessageLogMaxLine = 150; // Metadata: 0x00611F9D // Constructors public MessageLogManager() {} // 0x008979D0-0x00897A70 // Methods public void Add2(string message) {} // 0x00896FA0-0x00897210 public void Add(string message) {} // 0x00897210-0x00897350 public bool GetLinkExist() => default; // 0x00897350-0x008974D0 public bool CheckLink(string text) => default; // 0x008974D0-0x00897700 public List<string> GetList() => default; // 0x00897710-0x00897980 public void Clear() {} // 0x00897980-0x008979D0 }
34.266667
133
0.752918
[ "Unlicense" ]
tech-ticks/RTDXTools
Assets/Scripts/Stubs/Generated/Assembly-CSharp/MessageLogManager.cs
1,030
C#
namespace ACMEForms { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.tabControl1 = new System.Windows.Forms.TabControl(); this.accountTabPage = new System.Windows.Forms.TabPage(); this.accountPanel = new System.Windows.Forms.Panel(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.accountDetailsTabControl = new System.Windows.Forms.TabControl(); this.accountDetailsTabPage = new System.Windows.Forms.TabPage(); this.accountPropertyGrid = new System.Windows.Forms.PropertyGrid(); this.contactEmailsLabel = new System.Windows.Forms.Label(); this.contactEmailsTextBox = new System.Windows.Forms.TextBox(); this.agreeTosTableLayout = new System.Windows.Forms.TableLayoutPanel(); this.agreeTosLinkLabel = new System.Windows.Forms.LinkLabel(); this.agreeTosLabel = new System.Windows.Forms.Label(); this.agreeTosCheckbox = new System.Windows.Forms.CheckBox(); this.caServerLabel = new System.Windows.Forms.Label(); this.caServerComboBox = new System.Windows.Forms.ComboBox(); this.accountButtonsFlowLayoutPanel = new System.Windows.Forms.FlowLayoutPanel(); this.createAccountButton = new System.Windows.Forms.Button(); this.refreshAccountButton = new System.Windows.Forms.Button(); this.updateAccountButton = new System.Windows.Forms.Button(); this.caServerTextBox = new System.Windows.Forms.TextBox(); this.ordersTabPage = new System.Windows.Forms.TabPage(); this.orderTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.orderDetailsTabControl = new System.Windows.Forms.TabControl(); this.orderDetailsTabPage = new System.Windows.Forms.TabPage(); this.orderPropertyGrid = new System.Windows.Forms.PropertyGrid(); this.authorizationsTabPage = new System.Windows.Forms.TabPage(); this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel(); this.authorizationsListBox = new System.Windows.Forms.ListBox(); this.authorizationsTabControl = new System.Windows.Forms.TabControl(); this.authorizationDetailsTabPage = new System.Windows.Forms.TabPage(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.authorizationPropertyGrid = new System.Windows.Forms.PropertyGrid(); this.challengesTabControl = new System.Windows.Forms.TabControl(); this.dnsChallengeTabPage = new System.Windows.Forms.TabPage(); this.tableLayoutPanel7 = new System.Windows.Forms.TableLayoutPanel(); this.dnsRecordValueTextBox = new System.Windows.Forms.TextBox(); this.dnsRecordNameTextBox = new System.Windows.Forms.TextBox(); this.dnsRecordValueLabel = new System.Windows.Forms.Label(); this.dnsRecordTypeTextBox = new System.Windows.Forms.TextBox(); this.dnsRecordTypeLabel = new System.Windows.Forms.Label(); this.dnsRecordNameLabel = new System.Windows.Forms.Label(); this.flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel(); this.submitDnsAnswerButton = new System.Windows.Forms.Button(); this.testDnsAnswerButton = new System.Windows.Forms.Button(); this.httpChallengeTabPage = new System.Windows.Forms.TabPage(); this.tableLayoutPanel5 = new System.Windows.Forms.TableLayoutPanel(); this.httpResourceValueLabel = new System.Windows.Forms.Label(); this.httpResourceValueTextBox = new System.Windows.Forms.TextBox(); this.httpResourceContentTypeLabel = new System.Windows.Forms.Label(); this.httpResourceUrlTextBox = new System.Windows.Forms.TextBox(); this.httpResourcePathLabel = new System.Windows.Forms.Label(); this.httpResourcePathTextBox = new System.Windows.Forms.TextBox(); this.httpResourceUrlLabel = new System.Windows.Forms.Label(); this.httpResourceContentTypeTextBox = new System.Windows.Forms.TextBox(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.submitHttpAnswerButton = new System.Windows.Forms.Button(); this.testHttpAnswerButton = new System.Windows.Forms.Button(); this.challengesTabPage = new System.Windows.Forms.TabPage(); this.challengesTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.miscChallengeTypesListBox = new System.Windows.Forms.ListBox(); this.challengeDetailsTabControl = new System.Windows.Forms.TabControl(); this.challengeDetailsTabPage = new System.Windows.Forms.TabPage(); this.challengePopertyGrid = new System.Windows.Forms.PropertyGrid(); this.challengeErrorTabPage = new System.Windows.Forms.TabPage(); this.challengeErrorTextBox = new System.Windows.Forms.TextBox(); this.validationRecordsTabPage = new System.Windows.Forms.TabPage(); this.validationRecordsTextBox = new System.Windows.Forms.TextBox(); this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel(); this.notAfterDateTimePicker = new System.Windows.Forms.DateTimePicker(); this.notAfterLabel = new System.Windows.Forms.Label(); this.notBeforeDateTimePicker = new System.Windows.Forms.DateTimePicker(); this.notBeforeLabel = new System.Windows.Forms.Label(); this.orderButtonsFlowLayoutPanel = new System.Windows.Forms.FlowLayoutPanel(); this.createOrderButton = new System.Windows.Forms.Button(); this.refreshOrderButton = new System.Windows.Forms.Button(); this.clearOrderButton = new System.Windows.Forms.Button(); this.dnsIdentifiersLabel = new System.Windows.Forms.Label(); this.dnsIdentifiersTextBox = new System.Windows.Forms.TextBox(); this.mainStatusStrip = new System.Windows.Forms.StatusStrip(); this.mainStatusLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.tabControl1.SuspendLayout(); this.accountTabPage.SuspendLayout(); this.accountPanel.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); this.accountDetailsTabControl.SuspendLayout(); this.accountDetailsTabPage.SuspendLayout(); this.agreeTosTableLayout.SuspendLayout(); this.accountButtonsFlowLayoutPanel.SuspendLayout(); this.ordersTabPage.SuspendLayout(); this.orderTableLayoutPanel.SuspendLayout(); this.orderDetailsTabControl.SuspendLayout(); this.orderDetailsTabPage.SuspendLayout(); this.authorizationsTabPage.SuspendLayout(); this.tableLayoutPanel4.SuspendLayout(); this.authorizationsTabControl.SuspendLayout(); this.authorizationDetailsTabPage.SuspendLayout(); this.tableLayoutPanel2.SuspendLayout(); this.challengesTabControl.SuspendLayout(); this.dnsChallengeTabPage.SuspendLayout(); this.tableLayoutPanel7.SuspendLayout(); this.flowLayoutPanel2.SuspendLayout(); this.httpChallengeTabPage.SuspendLayout(); this.tableLayoutPanel5.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); this.challengesTabPage.SuspendLayout(); this.challengesTableLayoutPanel.SuspendLayout(); this.challengeDetailsTabControl.SuspendLayout(); this.challengeDetailsTabPage.SuspendLayout(); this.challengeErrorTabPage.SuspendLayout(); this.validationRecordsTabPage.SuspendLayout(); this.tableLayoutPanel3.SuspendLayout(); this.orderButtonsFlowLayoutPanel.SuspendLayout(); this.mainStatusStrip.SuspendLayout(); this.SuspendLayout(); // // tabControl1 // this.tabControl1.Controls.Add(this.accountTabPage); this.tabControl1.Controls.Add(this.ordersTabPage); this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl1.Location = new System.Drawing.Point(0, 0); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(1344, 1521); this.tabControl1.TabIndex = 0; // // accountTabPage // this.accountTabPage.Controls.Add(this.accountPanel); this.accountTabPage.Location = new System.Drawing.Point(8, 39); this.accountTabPage.Name = "accountTabPage"; this.accountTabPage.Padding = new System.Windows.Forms.Padding(3); this.accountTabPage.Size = new System.Drawing.Size(1328, 1474); this.accountTabPage.TabIndex = 0; this.accountTabPage.Text = "Account"; this.accountTabPage.UseVisualStyleBackColor = true; // // accountPanel // this.accountPanel.Controls.Add(this.tableLayoutPanel1); this.accountPanel.Controls.Add(this.caServerTextBox); this.accountPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.accountPanel.Location = new System.Drawing.Point(3, 3); this.accountPanel.Name = "accountPanel"; this.accountPanel.Size = new System.Drawing.Size(1322, 1468); this.accountPanel.TabIndex = 2; // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 2; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 24F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.Controls.Add(this.accountDetailsTabControl, 1, 6); this.tableLayoutPanel1.Controls.Add(this.contactEmailsLabel, 1, 2); this.tableLayoutPanel1.Controls.Add(this.contactEmailsTextBox, 1, 3); this.tableLayoutPanel1.Controls.Add(this.agreeTosTableLayout, 1, 4); this.tableLayoutPanel1.Controls.Add(this.caServerLabel, 1, 0); this.tableLayoutPanel1.Controls.Add(this.caServerComboBox, 1, 1); this.tableLayoutPanel1.Controls.Add(this.accountButtonsFlowLayoutPanel, 1, 5); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 7; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(1322, 1468); this.tableLayoutPanel1.TabIndex = 16; // // accountDetailsTabControl // this.accountDetailsTabControl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.accountDetailsTabControl.Controls.Add(this.accountDetailsTabPage); this.accountDetailsTabControl.Location = new System.Drawing.Point(27, 378); this.accountDetailsTabControl.Name = "accountDetailsTabControl"; this.accountDetailsTabControl.SelectedIndex = 0; this.accountDetailsTabControl.Size = new System.Drawing.Size(1292, 1087); this.accountDetailsTabControl.TabIndex = 15; // // accountDetailsTabPage // this.accountDetailsTabPage.Controls.Add(this.accountPropertyGrid); this.accountDetailsTabPage.Location = new System.Drawing.Point(8, 39); this.accountDetailsTabPage.Name = "accountDetailsTabPage"; this.accountDetailsTabPage.Padding = new System.Windows.Forms.Padding(3); this.accountDetailsTabPage.Size = new System.Drawing.Size(1276, 1040); this.accountDetailsTabPage.TabIndex = 0; this.accountDetailsTabPage.Text = "Account Details"; this.accountDetailsTabPage.UseVisualStyleBackColor = true; // // accountPropertyGrid // this.accountPropertyGrid.Dock = System.Windows.Forms.DockStyle.Fill; this.accountPropertyGrid.Location = new System.Drawing.Point(3, 3); this.accountPropertyGrid.Name = "accountPropertyGrid"; this.accountPropertyGrid.PropertySort = System.Windows.Forms.PropertySort.NoSort; this.accountPropertyGrid.Size = new System.Drawing.Size(1270, 1034); this.accountPropertyGrid.TabIndex = 14; this.accountPropertyGrid.ToolbarVisible = false; // // contactEmailsLabel // this.contactEmailsLabel.AutoSize = true; this.contactEmailsLabel.Location = new System.Drawing.Point(27, 64); this.contactEmailsLabel.Name = "contactEmailsLabel"; this.contactEmailsLabel.Size = new System.Drawing.Size(162, 25); this.contactEmailsLabel.TabIndex = 0; this.contactEmailsLabel.Text = "Contact Emails:"; this.contactEmailsLabel.TextAlign = System.Drawing.ContentAlignment.TopRight; // // contactEmailsTextBox // this.contactEmailsTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.contactEmailsTextBox.Location = new System.Drawing.Point(27, 92); this.contactEmailsTextBox.Multiline = true; this.contactEmailsTextBox.Name = "contactEmailsTextBox"; this.contactEmailsTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.contactEmailsTextBox.Size = new System.Drawing.Size(1292, 142); this.contactEmailsTextBox.TabIndex = 1; // // agreeTosTableLayout // this.agreeTosTableLayout.ColumnCount = 3; this.agreeTosTableLayout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.agreeTosTableLayout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.agreeTosTableLayout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.agreeTosTableLayout.Controls.Add(this.agreeTosLinkLabel, 2, 0); this.agreeTosTableLayout.Controls.Add(this.agreeTosLabel, 0, 0); this.agreeTosTableLayout.Controls.Add(this.agreeTosCheckbox, 0, 0); this.agreeTosTableLayout.Location = new System.Drawing.Point(24, 237); this.agreeTosTableLayout.Margin = new System.Windows.Forms.Padding(0); this.agreeTosTableLayout.Name = "agreeTosTableLayout"; this.agreeTosTableLayout.RowCount = 1; this.agreeTosTableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.agreeTosTableLayout.Size = new System.Drawing.Size(913, 36); this.agreeTosTableLayout.TabIndex = 10; // // agreeTosLinkLabel // this.agreeTosLinkLabel.AutoSize = true; this.agreeTosLinkLabel.Dock = System.Windows.Forms.DockStyle.Fill; this.agreeTosLinkLabel.Location = new System.Drawing.Point(127, 0); this.agreeTosLinkLabel.Margin = new System.Windows.Forms.Padding(0); this.agreeTosLinkLabel.Name = "agreeTosLinkLabel"; this.agreeTosLinkLabel.Size = new System.Drawing.Size(786, 36); this.agreeTosLinkLabel.TabIndex = 4; this.agreeTosLinkLabel.TabStop = true; this.agreeTosLinkLabel.Text = "Terms of Service"; this.agreeTosLinkLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.agreeTosLinkLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.agreeTosLinkLabel_LinkClicked); // // agreeTosLabel // this.agreeTosLabel.AutoSize = true; this.agreeTosLabel.Dock = System.Windows.Forms.DockStyle.Fill; this.agreeTosLabel.Location = new System.Drawing.Point(34, 0); this.agreeTosLabel.Margin = new System.Windows.Forms.Padding(0); this.agreeTosLabel.Name = "agreeTosLabel"; this.agreeTosLabel.Size = new System.Drawing.Size(93, 36); this.agreeTosLabel.TabIndex = 11; this.agreeTosLabel.Text = "Agree to"; this.agreeTosLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // agreeTosCheckbox // this.agreeTosCheckbox.AutoSize = true; this.agreeTosCheckbox.Dock = System.Windows.Forms.DockStyle.Fill; this.agreeTosCheckbox.Location = new System.Drawing.Point(3, 3); this.agreeTosCheckbox.Name = "agreeTosCheckbox"; this.agreeTosCheckbox.Size = new System.Drawing.Size(28, 30); this.agreeTosCheckbox.TabIndex = 2; this.agreeTosCheckbox.UseVisualStyleBackColor = true; // // caServerLabel // this.caServerLabel.AutoSize = true; this.caServerLabel.Location = new System.Drawing.Point(27, 0); this.caServerLabel.Name = "caServerLabel"; this.caServerLabel.Size = new System.Drawing.Size(116, 25); this.caServerLabel.TabIndex = 6; this.caServerLabel.Text = "CA Server:"; this.caServerLabel.TextAlign = System.Drawing.ContentAlignment.TopRight; // // caServerComboBox // this.caServerComboBox.DisplayMember = "Value"; this.caServerComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.caServerComboBox.FormattingEnabled = true; this.caServerComboBox.Location = new System.Drawing.Point(27, 28); this.caServerComboBox.Name = "caServerComboBox"; this.caServerComboBox.Size = new System.Drawing.Size(646, 33); this.caServerComboBox.TabIndex = 3; this.caServerComboBox.ValueMember = "Key"; this.caServerComboBox.SelectedIndexChanged += new System.EventHandler(this.caServerComboBox_SelectedIndexChanged); // // accountButtonsFlowLayoutPanel // this.accountButtonsFlowLayoutPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.accountButtonsFlowLayoutPanel.Controls.Add(this.createAccountButton); this.accountButtonsFlowLayoutPanel.Controls.Add(this.refreshAccountButton); this.accountButtonsFlowLayoutPanel.Controls.Add(this.updateAccountButton); this.accountButtonsFlowLayoutPanel.Location = new System.Drawing.Point(27, 276); this.accountButtonsFlowLayoutPanel.Name = "accountButtonsFlowLayoutPanel"; this.accountButtonsFlowLayoutPanel.Padding = new System.Windows.Forms.Padding(10); this.accountButtonsFlowLayoutPanel.Size = new System.Drawing.Size(1292, 96); this.accountButtonsFlowLayoutPanel.TabIndex = 14; // // createAccountButton // this.createAccountButton.AutoSize = true; this.createAccountButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.createAccountButton.Location = new System.Drawing.Point(20, 20); this.createAccountButton.Margin = new System.Windows.Forms.Padding(10); this.createAccountButton.Name = "createAccountButton"; this.createAccountButton.Padding = new System.Windows.Forms.Padding(10); this.createAccountButton.Size = new System.Drawing.Size(190, 55); this.createAccountButton.TabIndex = 5; this.createAccountButton.Text = "Create Account"; this.createAccountButton.UseVisualStyleBackColor = true; this.createAccountButton.Click += new System.EventHandler(this.createAccountButton_Click); // // refreshAccountButton // this.refreshAccountButton.AutoSize = true; this.refreshAccountButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.refreshAccountButton.Enabled = false; this.refreshAccountButton.Location = new System.Drawing.Point(230, 20); this.refreshAccountButton.Margin = new System.Windows.Forms.Padding(10); this.refreshAccountButton.Name = "refreshAccountButton"; this.refreshAccountButton.Padding = new System.Windows.Forms.Padding(10); this.refreshAccountButton.Size = new System.Drawing.Size(201, 55); this.refreshAccountButton.TabIndex = 6; this.refreshAccountButton.Text = "Refresh Account"; this.refreshAccountButton.UseVisualStyleBackColor = true; this.refreshAccountButton.Click += new System.EventHandler(this.refreshAccountButton_Click); // // updateAccountButton // this.updateAccountButton.AutoSize = true; this.updateAccountButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.updateAccountButton.Location = new System.Drawing.Point(451, 20); this.updateAccountButton.Margin = new System.Windows.Forms.Padding(10); this.updateAccountButton.Name = "updateAccountButton"; this.updateAccountButton.Padding = new System.Windows.Forms.Padding(10); this.updateAccountButton.Size = new System.Drawing.Size(195, 55); this.updateAccountButton.TabIndex = 6; this.updateAccountButton.Text = "Update Account"; this.updateAccountButton.UseVisualStyleBackColor = true; this.updateAccountButton.Click += new System.EventHandler(this.updateAccountButton_Click); // // caServerTextBox // this.caServerTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.caServerTextBox.Location = new System.Drawing.Point(627, 5); this.caServerTextBox.Name = "caServerTextBox"; this.caServerTextBox.Size = new System.Drawing.Size(230, 31); this.caServerTextBox.TabIndex = 7; this.caServerTextBox.Visible = false; // // ordersTabPage // this.ordersTabPage.Controls.Add(this.orderTableLayoutPanel); this.ordersTabPage.Location = new System.Drawing.Point(8, 39); this.ordersTabPage.Name = "ordersTabPage"; this.ordersTabPage.Padding = new System.Windows.Forms.Padding(3); this.ordersTabPage.Size = new System.Drawing.Size(1328, 1474); this.ordersTabPage.TabIndex = 1; this.ordersTabPage.Text = "Orders"; this.ordersTabPage.UseVisualStyleBackColor = true; // // orderTableLayoutPanel // this.orderTableLayoutPanel.ColumnCount = 2; this.orderTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 31F)); this.orderTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 84.2803F)); this.orderTableLayoutPanel.Controls.Add(this.orderDetailsTabControl, 1, 4); this.orderTableLayoutPanel.Controls.Add(this.tableLayoutPanel3, 1, 2); this.orderTableLayoutPanel.Controls.Add(this.orderButtonsFlowLayoutPanel, 1, 3); this.orderTableLayoutPanel.Controls.Add(this.dnsIdentifiersLabel, 1, 0); this.orderTableLayoutPanel.Controls.Add(this.dnsIdentifiersTextBox, 1, 1); this.orderTableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.orderTableLayoutPanel.Location = new System.Drawing.Point(3, 3); this.orderTableLayoutPanel.Name = "orderTableLayoutPanel"; this.orderTableLayoutPanel.RowCount = 6; this.orderTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.orderTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.orderTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.orderTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.orderTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.orderTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.orderTableLayoutPanel.Size = new System.Drawing.Size(1322, 1468); this.orderTableLayoutPanel.TabIndex = 1; // // orderDetailsTabControl // this.orderDetailsTabControl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.orderDetailsTabControl.Controls.Add(this.orderDetailsTabPage); this.orderDetailsTabControl.Controls.Add(this.authorizationsTabPage); this.orderDetailsTabControl.Location = new System.Drawing.Point(34, 300); this.orderDetailsTabControl.Name = "orderDetailsTabControl"; this.orderDetailsTabControl.SelectedIndex = 0; this.orderDetailsTabControl.Size = new System.Drawing.Size(1285, 1145); this.orderDetailsTabControl.TabIndex = 15; // // orderDetailsTabPage // this.orderDetailsTabPage.Controls.Add(this.orderPropertyGrid); this.orderDetailsTabPage.Location = new System.Drawing.Point(8, 39); this.orderDetailsTabPage.Name = "orderDetailsTabPage"; this.orderDetailsTabPage.Padding = new System.Windows.Forms.Padding(3); this.orderDetailsTabPage.Size = new System.Drawing.Size(1269, 1098); this.orderDetailsTabPage.TabIndex = 0; this.orderDetailsTabPage.Text = "Order Details"; this.orderDetailsTabPage.UseVisualStyleBackColor = true; // // orderPropertyGrid // this.orderPropertyGrid.Dock = System.Windows.Forms.DockStyle.Fill; this.orderPropertyGrid.Location = new System.Drawing.Point(3, 3); this.orderPropertyGrid.Name = "orderPropertyGrid"; this.orderPropertyGrid.PropertySort = System.Windows.Forms.PropertySort.Categorized; this.orderPropertyGrid.Size = new System.Drawing.Size(1263, 1092); this.orderPropertyGrid.TabIndex = 23; this.orderPropertyGrid.ToolbarVisible = false; // // authorizationsTabPage // this.authorizationsTabPage.Controls.Add(this.tableLayoutPanel4); this.authorizationsTabPage.Location = new System.Drawing.Point(8, 39); this.authorizationsTabPage.Name = "authorizationsTabPage"; this.authorizationsTabPage.Padding = new System.Windows.Forms.Padding(3); this.authorizationsTabPage.Size = new System.Drawing.Size(1269, 1098); this.authorizationsTabPage.TabIndex = 1; this.authorizationsTabPage.Text = "Authorizations"; this.authorizationsTabPage.UseVisualStyleBackColor = true; // // tableLayoutPanel4 // this.tableLayoutPanel4.ColumnCount = 2; this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 19F)); this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel4.Controls.Add(this.authorizationsListBox, 1, 0); this.tableLayoutPanel4.Controls.Add(this.authorizationsTabControl, 1, 1); this.tableLayoutPanel4.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel4.Location = new System.Drawing.Point(3, 3); this.tableLayoutPanel4.Name = "tableLayoutPanel4"; this.tableLayoutPanel4.RowCount = 2; this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel4.Size = new System.Drawing.Size(1263, 1092); this.tableLayoutPanel4.TabIndex = 0; // // authorizationsListBox // this.authorizationsListBox.Dock = System.Windows.Forms.DockStyle.Top; this.authorizationsListBox.FormattingEnabled = true; this.authorizationsListBox.ItemHeight = 25; this.authorizationsListBox.Location = new System.Drawing.Point(22, 3); this.authorizationsListBox.Name = "authorizationsListBox"; this.authorizationsListBox.Size = new System.Drawing.Size(1238, 104); this.authorizationsListBox.TabIndex = 17; this.authorizationsListBox.SelectedIndexChanged += new System.EventHandler(this.authorizationsListBox_SelectedIndexChanged); // // authorizationsTabControl // this.authorizationsTabControl.Controls.Add(this.authorizationDetailsTabPage); this.authorizationsTabControl.Controls.Add(this.challengesTabPage); this.authorizationsTabControl.Dock = System.Windows.Forms.DockStyle.Fill; this.authorizationsTabControl.Location = new System.Drawing.Point(22, 113); this.authorizationsTabControl.Name = "authorizationsTabControl"; this.authorizationsTabControl.SelectedIndex = 0; this.authorizationsTabControl.Size = new System.Drawing.Size(1238, 976); this.authorizationsTabControl.TabIndex = 33; // // authorizationDetailsTabPage // this.authorizationDetailsTabPage.Controls.Add(this.tableLayoutPanel2); this.authorizationDetailsTabPage.Location = new System.Drawing.Point(8, 39); this.authorizationDetailsTabPage.Name = "authorizationDetailsTabPage"; this.authorizationDetailsTabPage.Padding = new System.Windows.Forms.Padding(3); this.authorizationDetailsTabPage.Size = new System.Drawing.Size(1222, 929); this.authorizationDetailsTabPage.TabIndex = 0; this.authorizationDetailsTabPage.Text = "Details"; this.authorizationDetailsTabPage.UseVisualStyleBackColor = true; // // tableLayoutPanel2 // this.tableLayoutPanel2.ColumnCount = 2; this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 21F)); this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel2.Controls.Add(this.authorizationPropertyGrid, 1, 0); this.tableLayoutPanel2.Controls.Add(this.challengesTabControl, 1, 1); this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 3); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; this.tableLayoutPanel2.RowCount = 2; this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel2.Size = new System.Drawing.Size(1216, 923); this.tableLayoutPanel2.TabIndex = 0; // // authorizationPropertyGrid // this.authorizationPropertyGrid.Dock = System.Windows.Forms.DockStyle.Fill; this.authorizationPropertyGrid.HelpVisible = false; this.authorizationPropertyGrid.Location = new System.Drawing.Point(24, 3); this.authorizationPropertyGrid.Name = "authorizationPropertyGrid"; this.authorizationPropertyGrid.PropertySort = System.Windows.Forms.PropertySort.NoSort; this.authorizationPropertyGrid.Size = new System.Drawing.Size(1189, 498); this.authorizationPropertyGrid.TabIndex = 29; this.authorizationPropertyGrid.ToolbarVisible = false; // // challengesTabControl // this.challengesTabControl.Controls.Add(this.dnsChallengeTabPage); this.challengesTabControl.Controls.Add(this.httpChallengeTabPage); this.challengesTabControl.Dock = System.Windows.Forms.DockStyle.Bottom; this.challengesTabControl.Location = new System.Drawing.Point(24, 507); this.challengesTabControl.Name = "challengesTabControl"; this.challengesTabControl.SelectedIndex = 0; this.challengesTabControl.Size = new System.Drawing.Size(1189, 413); this.challengesTabControl.TabIndex = 25; this.challengesTabControl.SelectedIndexChanged += new System.EventHandler(this.challengesTabControl_SelectedIndexChanged); // // dnsChallengeTabPage // this.dnsChallengeTabPage.Controls.Add(this.tableLayoutPanel7); this.dnsChallengeTabPage.Location = new System.Drawing.Point(8, 39); this.dnsChallengeTabPage.Name = "dnsChallengeTabPage"; this.dnsChallengeTabPage.Padding = new System.Windows.Forms.Padding(3); this.dnsChallengeTabPage.Size = new System.Drawing.Size(1173, 366); this.dnsChallengeTabPage.TabIndex = 0; this.dnsChallengeTabPage.Text = "DNS Challenge"; this.dnsChallengeTabPage.UseVisualStyleBackColor = true; // // tableLayoutPanel7 // this.tableLayoutPanel7.ColumnCount = 2; this.tableLayoutPanel7.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 220F)); this.tableLayoutPanel7.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel7.Controls.Add(this.dnsRecordValueTextBox, 1, 2); this.tableLayoutPanel7.Controls.Add(this.dnsRecordNameTextBox, 1, 0); this.tableLayoutPanel7.Controls.Add(this.dnsRecordValueLabel, 0, 2); this.tableLayoutPanel7.Controls.Add(this.dnsRecordTypeTextBox, 1, 1); this.tableLayoutPanel7.Controls.Add(this.dnsRecordTypeLabel, 0, 1); this.tableLayoutPanel7.Controls.Add(this.dnsRecordNameLabel, 0, 0); this.tableLayoutPanel7.Controls.Add(this.flowLayoutPanel2, 1, 3); this.tableLayoutPanel7.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel7.Location = new System.Drawing.Point(3, 3); this.tableLayoutPanel7.Name = "tableLayoutPanel7"; this.tableLayoutPanel7.RowCount = 4; this.tableLayoutPanel7.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel7.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel7.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel7.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel7.Size = new System.Drawing.Size(1167, 360); this.tableLayoutPanel7.TabIndex = 0; // // dnsRecordValueTextBox // this.dnsRecordValueTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.dnsRecordValueTextBox.Location = new System.Drawing.Point(223, 77); this.dnsRecordValueTextBox.Multiline = true; this.dnsRecordValueTextBox.Name = "dnsRecordValueTextBox"; this.dnsRecordValueTextBox.ReadOnly = true; this.dnsRecordValueTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.dnsRecordValueTextBox.Size = new System.Drawing.Size(941, 194); this.dnsRecordValueTextBox.TabIndex = 8; this.dnsRecordValueTextBox.WordWrap = false; // // dnsRecordNameTextBox // this.dnsRecordNameTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dnsRecordNameTextBox.Location = new System.Drawing.Point(223, 3); this.dnsRecordNameTextBox.Name = "dnsRecordNameTextBox"; this.dnsRecordNameTextBox.ReadOnly = true; this.dnsRecordNameTextBox.Size = new System.Drawing.Size(941, 31); this.dnsRecordNameTextBox.TabIndex = 4; // // dnsRecordValueLabel // this.dnsRecordValueLabel.AutoSize = true; this.dnsRecordValueLabel.Location = new System.Drawing.Point(3, 74); this.dnsRecordValueLabel.Name = "dnsRecordValueLabel"; this.dnsRecordValueLabel.Size = new System.Drawing.Size(148, 25); this.dnsRecordValueLabel.TabIndex = 9; this.dnsRecordValueLabel.Text = "Record Value:"; // // dnsRecordTypeTextBox // this.dnsRecordTypeTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dnsRecordTypeTextBox.Location = new System.Drawing.Point(223, 40); this.dnsRecordTypeTextBox.Name = "dnsRecordTypeTextBox"; this.dnsRecordTypeTextBox.ReadOnly = true; this.dnsRecordTypeTextBox.Size = new System.Drawing.Size(941, 31); this.dnsRecordTypeTextBox.TabIndex = 6; // // dnsRecordTypeLabel // this.dnsRecordTypeLabel.AutoSize = true; this.dnsRecordTypeLabel.Location = new System.Drawing.Point(3, 37); this.dnsRecordTypeLabel.Name = "dnsRecordTypeLabel"; this.dnsRecordTypeLabel.Size = new System.Drawing.Size(141, 25); this.dnsRecordTypeLabel.TabIndex = 7; this.dnsRecordTypeLabel.Text = "Record Type:"; // // dnsRecordNameLabel // this.dnsRecordNameLabel.AutoSize = true; this.dnsRecordNameLabel.Location = new System.Drawing.Point(3, 0); this.dnsRecordNameLabel.Name = "dnsRecordNameLabel"; this.dnsRecordNameLabel.Size = new System.Drawing.Size(149, 25); this.dnsRecordNameLabel.TabIndex = 5; this.dnsRecordNameLabel.Text = "Record Name:"; // // flowLayoutPanel2 // this.flowLayoutPanel2.Controls.Add(this.submitDnsAnswerButton); this.flowLayoutPanel2.Controls.Add(this.testDnsAnswerButton); this.flowLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Bottom; this.flowLayoutPanel2.Location = new System.Drawing.Point(223, 277); this.flowLayoutPanel2.Name = "flowLayoutPanel2"; this.flowLayoutPanel2.Size = new System.Drawing.Size(941, 80); this.flowLayoutPanel2.TabIndex = 10; // // submitDnsAnswerButton // this.submitDnsAnswerButton.AutoSize = true; this.submitDnsAnswerButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.submitDnsAnswerButton.Location = new System.Drawing.Point(10, 10); this.submitDnsAnswerButton.Margin = new System.Windows.Forms.Padding(10); this.submitDnsAnswerButton.Name = "submitDnsAnswerButton"; this.submitDnsAnswerButton.Padding = new System.Windows.Forms.Padding(10); this.submitDnsAnswerButton.Size = new System.Drawing.Size(235, 55); this.submitDnsAnswerButton.TabIndex = 8; this.submitDnsAnswerButton.Text = "Submit DNS Answer"; this.submitDnsAnswerButton.UseVisualStyleBackColor = true; this.submitDnsAnswerButton.Click += new System.EventHandler(this.submitDnsAnswerButton_Click); // // testDnsAnswerButton // this.testDnsAnswerButton.AutoSize = true; this.testDnsAnswerButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.testDnsAnswerButton.Location = new System.Drawing.Point(265, 10); this.testDnsAnswerButton.Margin = new System.Windows.Forms.Padding(10); this.testDnsAnswerButton.Name = "testDnsAnswerButton"; this.testDnsAnswerButton.Padding = new System.Windows.Forms.Padding(10); this.testDnsAnswerButton.Size = new System.Drawing.Size(211, 55); this.testDnsAnswerButton.TabIndex = 9; this.testDnsAnswerButton.Text = "Test DNS Answer"; this.testDnsAnswerButton.UseVisualStyleBackColor = true; this.testDnsAnswerButton.Click += new System.EventHandler(this.testDnsAnswerButton_Click); // // httpChallengeTabPage // this.httpChallengeTabPage.Controls.Add(this.tableLayoutPanel5); this.httpChallengeTabPage.Location = new System.Drawing.Point(8, 39); this.httpChallengeTabPage.Name = "httpChallengeTabPage"; this.httpChallengeTabPage.Padding = new System.Windows.Forms.Padding(3); this.httpChallengeTabPage.Size = new System.Drawing.Size(1173, 366); this.httpChallengeTabPage.TabIndex = 1; this.httpChallengeTabPage.Text = "HTTP Challenge"; this.httpChallengeTabPage.UseVisualStyleBackColor = true; // // tableLayoutPanel5 // this.tableLayoutPanel5.ColumnCount = 2; this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 220F)); this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel5.Controls.Add(this.httpResourceValueLabel, 0, 3); this.tableLayoutPanel5.Controls.Add(this.httpResourceValueTextBox, 1, 3); this.tableLayoutPanel5.Controls.Add(this.httpResourceContentTypeLabel, 0, 2); this.tableLayoutPanel5.Controls.Add(this.httpResourceUrlTextBox, 1, 0); this.tableLayoutPanel5.Controls.Add(this.httpResourcePathLabel, 0, 1); this.tableLayoutPanel5.Controls.Add(this.httpResourcePathTextBox, 1, 1); this.tableLayoutPanel5.Controls.Add(this.httpResourceUrlLabel, 0, 0); this.tableLayoutPanel5.Controls.Add(this.httpResourceContentTypeTextBox, 1, 2); this.tableLayoutPanel5.Controls.Add(this.flowLayoutPanel1, 1, 4); this.tableLayoutPanel5.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel5.Location = new System.Drawing.Point(3, 3); this.tableLayoutPanel5.Name = "tableLayoutPanel5"; this.tableLayoutPanel5.RowCount = 5; this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel5.Size = new System.Drawing.Size(1167, 360); this.tableLayoutPanel5.TabIndex = 0; // // httpResourceValueLabel // this.httpResourceValueLabel.AutoSize = true; this.httpResourceValueLabel.Location = new System.Drawing.Point(3, 111); this.httpResourceValueLabel.Name = "httpResourceValueLabel"; this.httpResourceValueLabel.Size = new System.Drawing.Size(171, 25); this.httpResourceValueLabel.TabIndex = 13; this.httpResourceValueLabel.Text = "Resource Value:"; // // httpResourceValueTextBox // this.httpResourceValueTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.httpResourceValueTextBox.Location = new System.Drawing.Point(223, 114); this.httpResourceValueTextBox.Multiline = true; this.httpResourceValueTextBox.Name = "httpResourceValueTextBox"; this.httpResourceValueTextBox.ReadOnly = true; this.httpResourceValueTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.httpResourceValueTextBox.Size = new System.Drawing.Size(941, 157); this.httpResourceValueTextBox.TabIndex = 12; this.httpResourceValueTextBox.WordWrap = false; // // httpResourceContentTypeLabel // this.httpResourceContentTypeLabel.AutoSize = true; this.httpResourceContentTypeLabel.Location = new System.Drawing.Point(3, 74); this.httpResourceContentTypeLabel.Name = "httpResourceContentTypeLabel"; this.httpResourceContentTypeLabel.Size = new System.Drawing.Size(185, 25); this.httpResourceContentTypeLabel.TabIndex = 11; this.httpResourceContentTypeLabel.Text = "Res Content-type:"; // // httpResourceUrlTextBox // this.httpResourceUrlTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.httpResourceUrlTextBox.Location = new System.Drawing.Point(223, 3); this.httpResourceUrlTextBox.Name = "httpResourceUrlTextBox"; this.httpResourceUrlTextBox.ReadOnly = true; this.httpResourceUrlTextBox.Size = new System.Drawing.Size(941, 31); this.httpResourceUrlTextBox.TabIndex = 6; // // httpResourcePathLabel // this.httpResourcePathLabel.AutoSize = true; this.httpResourcePathLabel.Location = new System.Drawing.Point(3, 37); this.httpResourcePathLabel.Name = "httpResourcePathLabel"; this.httpResourcePathLabel.Size = new System.Drawing.Size(160, 25); this.httpResourcePathLabel.TabIndex = 9; this.httpResourcePathLabel.Text = "Resource Path:"; // // httpResourcePathTextBox // this.httpResourcePathTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.httpResourcePathTextBox.Location = new System.Drawing.Point(223, 40); this.httpResourcePathTextBox.Name = "httpResourcePathTextBox"; this.httpResourcePathTextBox.ReadOnly = true; this.httpResourcePathTextBox.Size = new System.Drawing.Size(941, 31); this.httpResourcePathTextBox.TabIndex = 8; // // httpResourceUrlLabel // this.httpResourceUrlLabel.AutoSize = true; this.httpResourceUrlLabel.Location = new System.Drawing.Point(3, 0); this.httpResourceUrlLabel.Name = "httpResourceUrlLabel"; this.httpResourceUrlLabel.Size = new System.Drawing.Size(158, 25); this.httpResourceUrlLabel.TabIndex = 7; this.httpResourceUrlLabel.Text = "Resource URL:"; // // httpResourceContentTypeTextBox // this.httpResourceContentTypeTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.httpResourceContentTypeTextBox.Location = new System.Drawing.Point(223, 77); this.httpResourceContentTypeTextBox.Name = "httpResourceContentTypeTextBox"; this.httpResourceContentTypeTextBox.ReadOnly = true; this.httpResourceContentTypeTextBox.Size = new System.Drawing.Size(941, 31); this.httpResourceContentTypeTextBox.TabIndex = 10; // // flowLayoutPanel1 // this.flowLayoutPanel1.Controls.Add(this.submitHttpAnswerButton); this.flowLayoutPanel1.Controls.Add(this.testHttpAnswerButton); this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Bottom; this.flowLayoutPanel1.Location = new System.Drawing.Point(223, 277); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(941, 80); this.flowLayoutPanel1.TabIndex = 14; // // submitHttpAnswerButton // this.submitHttpAnswerButton.AutoSize = true; this.submitHttpAnswerButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.submitHttpAnswerButton.Location = new System.Drawing.Point(10, 10); this.submitHttpAnswerButton.Margin = new System.Windows.Forms.Padding(10); this.submitHttpAnswerButton.Name = "submitHttpAnswerButton"; this.submitHttpAnswerButton.Padding = new System.Windows.Forms.Padding(10); this.submitHttpAnswerButton.Size = new System.Drawing.Size(246, 55); this.submitHttpAnswerButton.TabIndex = 7; this.submitHttpAnswerButton.Text = "Submit HTTP Answer"; this.submitHttpAnswerButton.UseVisualStyleBackColor = true; // // testHttpAnswerButton // this.testHttpAnswerButton.AutoSize = true; this.testHttpAnswerButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.testHttpAnswerButton.Location = new System.Drawing.Point(276, 10); this.testHttpAnswerButton.Margin = new System.Windows.Forms.Padding(10); this.testHttpAnswerButton.Name = "testHttpAnswerButton"; this.testHttpAnswerButton.Padding = new System.Windows.Forms.Padding(10); this.testHttpAnswerButton.Size = new System.Drawing.Size(222, 55); this.testHttpAnswerButton.TabIndex = 8; this.testHttpAnswerButton.Text = "Test HTTP Answer"; this.testHttpAnswerButton.UseVisualStyleBackColor = true; // // challengesTabPage // this.challengesTabPage.Controls.Add(this.challengesTableLayoutPanel); this.challengesTabPage.Location = new System.Drawing.Point(8, 39); this.challengesTabPage.Name = "challengesTabPage"; this.challengesTabPage.Padding = new System.Windows.Forms.Padding(3); this.challengesTabPage.Size = new System.Drawing.Size(1222, 929); this.challengesTabPage.TabIndex = 1; this.challengesTabPage.Text = "Full Challenge Details"; this.challengesTabPage.UseVisualStyleBackColor = true; // // challengesTableLayoutPanel // this.challengesTableLayoutPanel.ColumnCount = 2; this.challengesTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 21F)); this.challengesTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.challengesTableLayoutPanel.Controls.Add(this.miscChallengeTypesListBox, 1, 0); this.challengesTableLayoutPanel.Controls.Add(this.challengeDetailsTabControl, 1, 1); this.challengesTableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.challengesTableLayoutPanel.Location = new System.Drawing.Point(3, 3); this.challengesTableLayoutPanel.Name = "challengesTableLayoutPanel"; this.challengesTableLayoutPanel.RowCount = 2; this.challengesTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.challengesTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.challengesTableLayoutPanel.Size = new System.Drawing.Size(1216, 923); this.challengesTableLayoutPanel.TabIndex = 0; // // miscChallengeTypesListBox // this.miscChallengeTypesListBox.Dock = System.Windows.Forms.DockStyle.Top; this.miscChallengeTypesListBox.FormattingEnabled = true; this.miscChallengeTypesListBox.ItemHeight = 25; this.miscChallengeTypesListBox.Location = new System.Drawing.Point(24, 3); this.miscChallengeTypesListBox.Name = "miscChallengeTypesListBox"; this.miscChallengeTypesListBox.Size = new System.Drawing.Size(1189, 154); this.miscChallengeTypesListBox.TabIndex = 2; this.miscChallengeTypesListBox.SelectedIndexChanged += new System.EventHandler(this.miscChallengeTypesListBox_SelectedIndexChanged); // // challengeDetailsTabControl // this.challengeDetailsTabControl.Controls.Add(this.challengeDetailsTabPage); this.challengeDetailsTabControl.Controls.Add(this.challengeErrorTabPage); this.challengeDetailsTabControl.Controls.Add(this.validationRecordsTabPage); this.challengeDetailsTabControl.Dock = System.Windows.Forms.DockStyle.Fill; this.challengeDetailsTabControl.Location = new System.Drawing.Point(24, 163); this.challengeDetailsTabControl.Name = "challengeDetailsTabControl"; this.challengeDetailsTabControl.SelectedIndex = 0; this.challengeDetailsTabControl.Size = new System.Drawing.Size(1189, 757); this.challengeDetailsTabControl.TabIndex = 32; // // challengeDetailsTabPage // this.challengeDetailsTabPage.Controls.Add(this.challengePopertyGrid); this.challengeDetailsTabPage.Location = new System.Drawing.Point(8, 39); this.challengeDetailsTabPage.Name = "challengeDetailsTabPage"; this.challengeDetailsTabPage.Padding = new System.Windows.Forms.Padding(3); this.challengeDetailsTabPage.Size = new System.Drawing.Size(1173, 710); this.challengeDetailsTabPage.TabIndex = 0; this.challengeDetailsTabPage.Text = "Challenge Details"; this.challengeDetailsTabPage.UseVisualStyleBackColor = true; // // challengePopertyGrid // this.challengePopertyGrid.Dock = System.Windows.Forms.DockStyle.Fill; this.challengePopertyGrid.HelpVisible = false; this.challengePopertyGrid.Location = new System.Drawing.Point(3, 3); this.challengePopertyGrid.Name = "challengePopertyGrid"; this.challengePopertyGrid.PropertySort = System.Windows.Forms.PropertySort.NoSort; this.challengePopertyGrid.Size = new System.Drawing.Size(1167, 704); this.challengePopertyGrid.TabIndex = 28; this.challengePopertyGrid.ToolbarVisible = false; // // challengeErrorTabPage // this.challengeErrorTabPage.Controls.Add(this.challengeErrorTextBox); this.challengeErrorTabPage.Location = new System.Drawing.Point(8, 39); this.challengeErrorTabPage.Name = "challengeErrorTabPage"; this.challengeErrorTabPage.Padding = new System.Windows.Forms.Padding(3); this.challengeErrorTabPage.Size = new System.Drawing.Size(1173, 710); this.challengeErrorTabPage.TabIndex = 1; this.challengeErrorTabPage.Text = "Error"; this.challengeErrorTabPage.UseVisualStyleBackColor = true; // // challengeErrorTextBox // this.challengeErrorTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.challengeErrorTextBox.Location = new System.Drawing.Point(3, 3); this.challengeErrorTextBox.Multiline = true; this.challengeErrorTextBox.Name = "challengeErrorTextBox"; this.challengeErrorTextBox.ReadOnly = true; this.challengeErrorTextBox.Size = new System.Drawing.Size(1167, 704); this.challengeErrorTextBox.TabIndex = 2; this.challengeErrorTextBox.WordWrap = false; // // validationRecordsTabPage // this.validationRecordsTabPage.Controls.Add(this.validationRecordsTextBox); this.validationRecordsTabPage.Location = new System.Drawing.Point(8, 39); this.validationRecordsTabPage.Name = "validationRecordsTabPage"; this.validationRecordsTabPage.Padding = new System.Windows.Forms.Padding(3); this.validationRecordsTabPage.Size = new System.Drawing.Size(1173, 710); this.validationRecordsTabPage.TabIndex = 2; this.validationRecordsTabPage.Text = "Validation Records"; this.validationRecordsTabPage.UseVisualStyleBackColor = true; // // validationRecordsTextBox // this.validationRecordsTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.validationRecordsTextBox.Location = new System.Drawing.Point(3, 3); this.validationRecordsTextBox.Multiline = true; this.validationRecordsTextBox.Name = "validationRecordsTextBox"; this.validationRecordsTextBox.ReadOnly = true; this.validationRecordsTextBox.Size = new System.Drawing.Size(1167, 704); this.validationRecordsTextBox.TabIndex = 12; this.validationRecordsTextBox.WordWrap = false; // // tableLayoutPanel3 // this.tableLayoutPanel3.ColumnCount = 4; this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel3.Controls.Add(this.notAfterDateTimePicker, 3, 0); this.tableLayoutPanel3.Controls.Add(this.notAfterLabel, 2, 0); this.tableLayoutPanel3.Controls.Add(this.notBeforeDateTimePicker, 1, 0); this.tableLayoutPanel3.Controls.Add(this.notBeforeLabel, 0, 0); this.tableLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel3.Location = new System.Drawing.Point(34, 150); this.tableLayoutPanel3.Name = "tableLayoutPanel3"; this.tableLayoutPanel3.RowCount = 1; this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel3.Size = new System.Drawing.Size(1285, 44); this.tableLayoutPanel3.TabIndex = 10; // // notAfterDateTimePicker // this.notAfterDateTimePicker.Checked = false; this.notAfterDateTimePicker.Dock = System.Windows.Forms.DockStyle.Fill; this.notAfterDateTimePicker.Location = new System.Drawing.Point(762, 3); this.notAfterDateTimePicker.Name = "notAfterDateTimePicker"; this.notAfterDateTimePicker.ShowCheckBox = true; this.notAfterDateTimePicker.Size = new System.Drawing.Size(520, 31); this.notAfterDateTimePicker.TabIndex = 3; // // notAfterLabel // this.notAfterLabel.AutoSize = true; this.notAfterLabel.Dock = System.Windows.Forms.DockStyle.Fill; this.notAfterLabel.Location = new System.Drawing.Point(654, 0); this.notAfterLabel.Name = "notAfterLabel"; this.notAfterLabel.Size = new System.Drawing.Size(102, 44); this.notAfterLabel.TabIndex = 1; this.notAfterLabel.Text = "Not After:"; this.notAfterLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // notBeforeDateTimePicker // this.notBeforeDateTimePicker.Checked = false; this.notBeforeDateTimePicker.Dock = System.Windows.Forms.DockStyle.Fill; this.notBeforeDateTimePicker.Location = new System.Drawing.Point(129, 3); this.notBeforeDateTimePicker.Name = "notBeforeDateTimePicker"; this.notBeforeDateTimePicker.ShowCheckBox = true; this.notBeforeDateTimePicker.Size = new System.Drawing.Size(519, 31); this.notBeforeDateTimePicker.TabIndex = 2; // // notBeforeLabel // this.notBeforeLabel.AutoSize = true; this.notBeforeLabel.Dock = System.Windows.Forms.DockStyle.Fill; this.notBeforeLabel.Location = new System.Drawing.Point(3, 0); this.notBeforeLabel.Name = "notBeforeLabel"; this.notBeforeLabel.Size = new System.Drawing.Size(120, 44); this.notBeforeLabel.TabIndex = 0; this.notBeforeLabel.Text = "Not Before:"; this.notBeforeLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // orderButtonsFlowLayoutPanel // this.orderButtonsFlowLayoutPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.orderButtonsFlowLayoutPanel.Controls.Add(this.createOrderButton); this.orderButtonsFlowLayoutPanel.Controls.Add(this.refreshOrderButton); this.orderButtonsFlowLayoutPanel.Controls.Add(this.clearOrderButton); this.orderButtonsFlowLayoutPanel.Location = new System.Drawing.Point(34, 200); this.orderButtonsFlowLayoutPanel.Name = "orderButtonsFlowLayoutPanel"; this.orderButtonsFlowLayoutPanel.Padding = new System.Windows.Forms.Padding(10); this.orderButtonsFlowLayoutPanel.Size = new System.Drawing.Size(1285, 94); this.orderButtonsFlowLayoutPanel.TabIndex = 3; // // createOrderButton // this.createOrderButton.AutoSize = true; this.createOrderButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.createOrderButton.Location = new System.Drawing.Point(20, 20); this.createOrderButton.Margin = new System.Windows.Forms.Padding(10); this.createOrderButton.Name = "createOrderButton"; this.createOrderButton.Padding = new System.Windows.Forms.Padding(10); this.createOrderButton.Size = new System.Drawing.Size(166, 55); this.createOrderButton.TabIndex = 6; this.createOrderButton.Text = "Create Order"; this.createOrderButton.UseVisualStyleBackColor = true; this.createOrderButton.Click += new System.EventHandler(this.createOrderButton_Click); // // refreshOrderButton // this.refreshOrderButton.AutoSize = true; this.refreshOrderButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.refreshOrderButton.Location = new System.Drawing.Point(206, 20); this.refreshOrderButton.Margin = new System.Windows.Forms.Padding(10); this.refreshOrderButton.Name = "refreshOrderButton"; this.refreshOrderButton.Padding = new System.Windows.Forms.Padding(10); this.refreshOrderButton.Size = new System.Drawing.Size(189, 55); this.refreshOrderButton.TabIndex = 7; this.refreshOrderButton.Text = "Referesh Order"; this.refreshOrderButton.UseVisualStyleBackColor = true; this.refreshOrderButton.Click += new System.EventHandler(this.refreshOrderButton_Click); // // clearOrderButton // this.clearOrderButton.AutoSize = true; this.clearOrderButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.clearOrderButton.Location = new System.Drawing.Point(415, 20); this.clearOrderButton.Margin = new System.Windows.Forms.Padding(10); this.clearOrderButton.Name = "clearOrderButton"; this.clearOrderButton.Padding = new System.Windows.Forms.Padding(10); this.clearOrderButton.Size = new System.Drawing.Size(153, 55); this.clearOrderButton.TabIndex = 8; this.clearOrderButton.Text = "Clear Order"; this.clearOrderButton.UseVisualStyleBackColor = true; this.clearOrderButton.Click += new System.EventHandler(this.clearOrderButton_Click); // // dnsIdentifiersLabel // this.dnsIdentifiersLabel.AutoSize = true; this.dnsIdentifiersLabel.Location = new System.Drawing.Point(34, 0); this.dnsIdentifiersLabel.Name = "dnsIdentifiersLabel"; this.dnsIdentifiersLabel.Size = new System.Drawing.Size(161, 25); this.dnsIdentifiersLabel.TabIndex = 1; this.dnsIdentifiersLabel.Text = "DNS Identifiers:"; this.dnsIdentifiersLabel.TextAlign = System.Drawing.ContentAlignment.TopRight; // // dnsIdentifiersTextBox // this.dnsIdentifiersTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dnsIdentifiersTextBox.Location = new System.Drawing.Point(34, 28); this.dnsIdentifiersTextBox.Multiline = true; this.dnsIdentifiersTextBox.Name = "dnsIdentifiersTextBox"; this.dnsIdentifiersTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.dnsIdentifiersTextBox.Size = new System.Drawing.Size(1285, 116); this.dnsIdentifiersTextBox.TabIndex = 2; // // mainStatusStrip // this.mainStatusStrip.ImageScalingSize = new System.Drawing.Size(32, 32); this.mainStatusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mainStatusLabel}); this.mainStatusStrip.Location = new System.Drawing.Point(0, 1521); this.mainStatusStrip.Name = "mainStatusStrip"; this.mainStatusStrip.Size = new System.Drawing.Size(1344, 37); this.mainStatusStrip.TabIndex = 15; this.mainStatusStrip.Text = "statusStrip1"; // // mainStatusLabel // this.mainStatusLabel.Name = "mainStatusLabel"; this.mainStatusLabel.Size = new System.Drawing.Size(76, 32); this.mainStatusLabel.Text = "Hello."; // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(12F, 25F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1344, 1558); this.Controls.Add(this.tabControl1); this.Controls.Add(this.mainStatusStrip); this.Name = "MainForm"; this.Text = "ACME WinForms"; this.Load += new System.EventHandler(this.MainForm_Load); this.tabControl1.ResumeLayout(false); this.accountTabPage.ResumeLayout(false); this.accountPanel.ResumeLayout(false); this.accountPanel.PerformLayout(); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.accountDetailsTabControl.ResumeLayout(false); this.accountDetailsTabPage.ResumeLayout(false); this.agreeTosTableLayout.ResumeLayout(false); this.agreeTosTableLayout.PerformLayout(); this.accountButtonsFlowLayoutPanel.ResumeLayout(false); this.accountButtonsFlowLayoutPanel.PerformLayout(); this.ordersTabPage.ResumeLayout(false); this.orderTableLayoutPanel.ResumeLayout(false); this.orderTableLayoutPanel.PerformLayout(); this.orderDetailsTabControl.ResumeLayout(false); this.orderDetailsTabPage.ResumeLayout(false); this.authorizationsTabPage.ResumeLayout(false); this.tableLayoutPanel4.ResumeLayout(false); this.authorizationsTabControl.ResumeLayout(false); this.authorizationDetailsTabPage.ResumeLayout(false); this.tableLayoutPanel2.ResumeLayout(false); this.challengesTabControl.ResumeLayout(false); this.dnsChallengeTabPage.ResumeLayout(false); this.tableLayoutPanel7.ResumeLayout(false); this.tableLayoutPanel7.PerformLayout(); this.flowLayoutPanel2.ResumeLayout(false); this.flowLayoutPanel2.PerformLayout(); this.httpChallengeTabPage.ResumeLayout(false); this.tableLayoutPanel5.ResumeLayout(false); this.tableLayoutPanel5.PerformLayout(); this.flowLayoutPanel1.ResumeLayout(false); this.flowLayoutPanel1.PerformLayout(); this.challengesTabPage.ResumeLayout(false); this.challengesTableLayoutPanel.ResumeLayout(false); this.challengeDetailsTabControl.ResumeLayout(false); this.challengeDetailsTabPage.ResumeLayout(false); this.challengeErrorTabPage.ResumeLayout(false); this.challengeErrorTabPage.PerformLayout(); this.validationRecordsTabPage.ResumeLayout(false); this.validationRecordsTabPage.PerformLayout(); this.tableLayoutPanel3.ResumeLayout(false); this.tableLayoutPanel3.PerformLayout(); this.orderButtonsFlowLayoutPanel.ResumeLayout(false); this.orderButtonsFlowLayoutPanel.PerformLayout(); this.mainStatusStrip.ResumeLayout(false); this.mainStatusStrip.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage accountTabPage; private System.Windows.Forms.TextBox contactEmailsTextBox; private System.Windows.Forms.Label contactEmailsLabel; private System.Windows.Forms.TabPage ordersTabPage; private System.Windows.Forms.Panel accountPanel; private System.Windows.Forms.CheckBox agreeTosCheckbox; private System.Windows.Forms.LinkLabel agreeTosLinkLabel; private System.Windows.Forms.ComboBox caServerComboBox; private System.Windows.Forms.Button createAccountButton; private System.Windows.Forms.Label caServerLabel; private System.Windows.Forms.TextBox caServerTextBox; private System.Windows.Forms.Button updateAccountButton; private System.Windows.Forms.TableLayoutPanel agreeTosTableLayout; private System.Windows.Forms.Label agreeTosLabel; private System.Windows.Forms.Button refreshAccountButton; private System.Windows.Forms.FlowLayoutPanel accountButtonsFlowLayoutPanel; private System.Windows.Forms.StatusStrip mainStatusStrip; private System.Windows.Forms.ToolStripStatusLabel mainStatusLabel; private System.Windows.Forms.FlowLayoutPanel orderButtonsFlowLayoutPanel; private System.Windows.Forms.Button createOrderButton; private System.Windows.Forms.Button refreshOrderButton; private System.Windows.Forms.TextBox dnsIdentifiersTextBox; private System.Windows.Forms.Label dnsIdentifiersLabel; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3; private System.Windows.Forms.Label notBeforeLabel; private System.Windows.Forms.Label notAfterLabel; private System.Windows.Forms.DateTimePicker notBeforeDateTimePicker; private System.Windows.Forms.DateTimePicker notAfterDateTimePicker; private System.Windows.Forms.Button clearOrderButton; private System.Windows.Forms.TabControl orderDetailsTabControl; private System.Windows.Forms.TabPage orderDetailsTabPage; private System.Windows.Forms.TabPage authorizationsTabPage; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel4; private System.Windows.Forms.TabControl challengesTabControl; private System.Windows.Forms.TabPage dnsChallengeTabPage; private System.Windows.Forms.TabPage httpChallengeTabPage; private System.Windows.Forms.ListBox authorizationsListBox; private System.Windows.Forms.TextBox challengeErrorTextBox; private System.Windows.Forms.TextBox validationRecordsTextBox; private System.Windows.Forms.TextBox dnsRecordValueTextBox; private System.Windows.Forms.Label dnsRecordValueLabel; private System.Windows.Forms.TextBox dnsRecordTypeTextBox; private System.Windows.Forms.Label dnsRecordTypeLabel; private System.Windows.Forms.TextBox dnsRecordNameTextBox; private System.Windows.Forms.Label dnsRecordNameLabel; private System.Windows.Forms.TextBox httpResourceUrlTextBox; private System.Windows.Forms.Label httpResourceUrlLabel; private System.Windows.Forms.TextBox httpResourceValueTextBox; private System.Windows.Forms.Label httpResourceValueLabel; private System.Windows.Forms.TextBox httpResourceContentTypeTextBox; private System.Windows.Forms.Label httpResourceContentTypeLabel; private System.Windows.Forms.TextBox httpResourcePathTextBox; private System.Windows.Forms.Label httpResourcePathLabel; private System.Windows.Forms.ListBox miscChallengeTypesListBox; private System.Windows.Forms.PropertyGrid accountPropertyGrid; private System.Windows.Forms.PropertyGrid orderPropertyGrid; private System.Windows.Forms.PropertyGrid authorizationPropertyGrid; private System.Windows.Forms.PropertyGrid challengePopertyGrid; private System.Windows.Forms.TabControl accountDetailsTabControl; private System.Windows.Forms.TabPage accountDetailsTabPage; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.TableLayoutPanel orderTableLayoutPanel; private System.Windows.Forms.TabControl challengeDetailsTabControl; private System.Windows.Forms.TabPage challengeDetailsTabPage; private System.Windows.Forms.TabPage challengeErrorTabPage; private System.Windows.Forms.TabPage validationRecordsTabPage; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel5; private System.Windows.Forms.TabControl authorizationsTabControl; private System.Windows.Forms.TabPage authorizationDetailsTabPage; private System.Windows.Forms.TabPage challengesTabPage; private System.Windows.Forms.TableLayoutPanel challengesTableLayoutPanel; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel7; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.Button submitHttpAnswerButton; private System.Windows.Forms.Button testHttpAnswerButton; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel2; private System.Windows.Forms.Button submitDnsAnswerButton; private System.Windows.Forms.Button testDnsAnswerButton; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; } }
62.752765
176
0.672604
[ "MIT" ]
FLDOHWebmasters/ACMESharpCore
src/examples/ACMEForms/MainForm.Designer.cs
79,445
C#
using System; namespace Factory { internal static class Program { public static void Main(string[] args) { IRobot driver = Factory.Build("driver"); IRobot warrior1 = Factory.Build("warrior"); IRobot warrior2 = Factory.Build("warrior"); Console.WriteLine(driver.GetInfo()); Console.WriteLine(warrior1.GetInfo()); } } }
25.176471
55
0.558411
[ "MIT" ]
amirhnajafiz/Programming-Design-Patterns
Factory Pattern/CS/Program.cs
430
C#
using Microsoft.AspNetCore.Mvc; using WUMEI.Models.V2020; namespace WUMEI.Controllers.V2020 { /// <summary> /// The WIC Vendor Maintenance functional area provides functions for maintaining WIC Vendor information, /// including banking information that is needed by the WIC EBT System. /// </summary> [ApiVersion("2020.1")] [Route("WUMEISample/{version:apiVersion}/[controller]/[action]")] public class WicVendorController : Controller { /// <summary> /// The Add or Update WIC Vendor function is a required function that uses a message or batch based /// system interface to establish or modify WIC Vendor information in the WIC EBT System. /// </summary> /// <param name="vendor"> /// Details the vendor to be added or updated. /// </param> /// <response code="200"> /// Returns the updated message header and status code. /// </response> /// <returns> /// Returns an <see cref="IActionResult"/> instance carrying the result data for the API caller. /// </returns> [HttpPost] [Consumes("application/json")] [Produces("application/json")] [ProducesResponseType(typeof(AddUpdateWicVendorResult), 200)] public IActionResult AddUpdateWicVendor( [FromBody]AddUpdateWicVendor vendor) { return Ok(new AddUpdateWicVendorResult { MessageHeader = vendor.MessageHeader, }); } /// <summary> /// The Add or Update WIC Vendor Hierarchy Information function is an optional function that uses a /// message or batch system interface to create and update the WIC EBT system’s WIC Vendor corporate /// levels of information. /// </summary> /// <param name="hierarchy"></param> /// <returns></returns> [HttpPost] [Consumes("application/json")] [Produces("application/json")] [ProducesResponseType(typeof(MessageHeader), 200)] public IActionResult AddUpdateWicVendorHierarchyInformation( [FromBody] AddUpdateWicVendorHierarchyInformation hierarchy ) { return Ok(hierarchy.MessageHeader); } /// <summary> /// The Update WIC Vendor Banking Information function is an optional function that uses a message or /// batch based system interface to add, change or delete banking information for a WIC Vendor in the WIC /// EBT system. /// </summary> /// <param name="vendor"></param> /// <returns></returns> [HttpPost] [Consumes("application/json")] [Produces("application/json")] [ProducesResponseType(typeof(MessageHeader), 200)] public IActionResult UpdateWicVendorBankingInformation( [FromBody] UpdateWicVendorBankingInformation vendor ) { return Ok(vendor.MessageHeader); } } }
39.142857
113
0.618779
[ "MIT" ]
CDP-Inc/WUMEI
src/WUMEI/Controllers/2020.1/WicVendorController.cs
3,018
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.Redshift.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.Redshift.Model.Internal.MarshallTransformations { /// <summary> /// PurchaseReservedNodeOffering Request Marshaller /// </summary> public class PurchaseReservedNodeOfferingRequestMarshaller : IMarshaller<IRequest, PurchaseReservedNodeOfferingRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((PurchaseReservedNodeOfferingRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(PurchaseReservedNodeOfferingRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Redshift"); request.Parameters.Add("Action", "PurchaseReservedNodeOffering"); request.Parameters.Add("Version", "2012-12-01"); if(publicRequest != null) { if(publicRequest.IsSetNodeCount()) { request.Parameters.Add("NodeCount", StringUtils.FromInt(publicRequest.NodeCount)); } if(publicRequest.IsSetReservedNodeOfferingId()) { request.Parameters.Add("ReservedNodeOfferingId", StringUtils.FromString(publicRequest.ReservedNodeOfferingId)); } } return request; } private static PurchaseReservedNodeOfferingRequestMarshaller _instance = new PurchaseReservedNodeOfferingRequestMarshaller(); internal static PurchaseReservedNodeOfferingRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static PurchaseReservedNodeOfferingRequestMarshaller Instance { get { return _instance; } } } }
36.153846
171
0.647112
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/Redshift/Generated/Model/Internal/MarshallTransformations/PurchaseReservedNodeOfferingRequestMarshaller.cs
3,290
C#
using Microsoft.WindowsAzure.Storage.Table; namespace TechSmith.Hyde.Table.Azure { internal class ExecutableTableOperation { public string Table { get; private set; } public TableOperation Operation { get; private set; } public TableOperationType OperationType { get; private set; } public string PartitionKey { get; private set; } public string RowKey { get; private set; } public ExecutableTableOperation( string table, TableOperation operation, TableOperationType operationType, string partitionKey, string rowKey ) { Table = table; Operation = operation; OperationType = operationType; PartitionKey = partitionKey; RowKey = rowKey; } } }
19.543478
149
0.569522
[ "BSD-3-Clause" ]
dontjee/hyde
src/Hyde/Table/Azure/ExecutableTableOperation.cs
899
C#
using System; namespace HelpRequest.Tests { public class ContinuousIntegrationDeploymentHack { public ContinuousIntegrationDeploymentHack() { //new log4net.Appender.AdoNetAppender(); new NHibernate.ByteCode.Spring.ProxyFactoryFactory(); new System.Data.SQLite.SQLiteException(); throw new Exception("This class should never be called or instantiated"); } } }
28.75
86
0.63913
[ "MIT" ]
ucdavis/HelpRequest
HelpRequest.Tests/ContinuousDeploymentIntegrationHack.cs
462
C#
using System; using WasteMan.Common.Data; namespace WasteMan.Algorithm.Core { internal static class Haversine { public static float DistanceTo(this Coordinate source, Coordinate destination) { const float EARTH_RADIUS = 6371 * 1000; // in meters var deltaLatitude = (source.Latitude - destination.Latitude).ToRadians(); var deltaLongitude = (source.Longitude - destination.Longitude).ToRadians(); var a = (Math.Pow(Math.Sin(deltaLatitude / 2), 2) + Math.Cos(source.Latitude.ToRadians()) * Math.Cos(destination.Latitude.ToRadians()) * Math.Pow(Math.Sin(deltaLongitude / 2), 2)); var b = (2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a))); var distance = EARTH_RADIUS * b; var roundedDistance = (float)Math.Round(distance); return roundedDistance; } private static float ToRadians(this float value) => value * (float)(Math.PI / 180); } }
33.4375
91
0.582243
[ "MIT" ]
IanEscober/WasteMan
src/WasteMan.Algorithm/Core/Haversine.cs
1,072
C#
/* * Copyright 2010-2018 Mohawk College of Applied Arts and Technology * * 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. * * User: fyfej * Date: 1-9-2017 */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using MARC.HI.EHRS.SVC.Core.Services; using System.Reflection; using System.ComponentModel; namespace MARC.HI.EHRS.SVC.Core { /// <summary> /// Utility for starting / stopping hosted services /// </summary> public static class ServiceUtil { /// <summary> /// Helper function to start the services /// </summary> public static int Start(Guid activityId) { Trace.CorrelationManager.ActivityId = activityId; Trace.TraceInformation("Starting host context on Console Presentation System at {0}", DateTime.Now); // Detect platform if (System.Environment.OSVersion.Platform != PlatformID.Win32NT) Trace.TraceWarning("Not running on WindowsNT, some features may not function correctly"); // Do this because loading stuff is tricky ;) AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); try { // Initialize Trace.TraceInformation("Getting default message handler service."); if(ApplicationContext.Current.Start()) { Trace.TraceInformation("Service Started Successfully"); return 0; } else { Trace.TraceError("No message handler service started. Terminating program"); Stop(); return 1911; } } catch (Exception e) { Trace.TraceError("Fatal exception occurred: {0}", e.ToString()); Stop(); return 1064; } finally { } } /// <summary> /// Stop the service /// </summary> public static void Stop() { ApplicationContext.Current.Stop(); } /// <summary> /// Assembly resolution /// </summary> internal static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) if (args.Name == asm.FullName) return asm; /// Try for an non-same number Version foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) { string fAsmName = args.Name; if (fAsmName.Contains(",")) fAsmName = fAsmName.Substring(0, fAsmName.IndexOf(",")); if (fAsmName == asm.GetName().Name) return asm; } return null; } } }
31.928571
112
0.569072
[ "Apache-2.0" ]
MohawkMEDIC/servicecore
MARC.HI.EHRS.SVC.Core/ServiceUtil.cs
3,578
C#
using CoordinateConversionLibrary.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ProAppCoordConversionModule.Views { /// <summary> /// Interaction logic for ProAmbiguousCoordsView.xaml /// </summary> public partial class ProAmbiguousCoordsView : ArcGIS.Desktop.Framework.Controls.ProWindow { public ProAmbiguousCoordsView() { InitializeComponent(); } } }
25.666667
93
0.753247
[ "Apache-2.0" ]
ArcGIS/coordinate-tool-addin-dotnet
source/CoordinateConversion/ProAppCoordConversionModule/Views/ProAmbiguousCoordsView.xaml.cs
772
C#
//----------------------------------------------------------------------- // <copyright file="RotatingViewController.cs" company="Sphere 10 Software"> // // Copyright (c) Sphere 10 Software. All rights reserved. (http://www.sphere10.com) // // Distributed under the MIT software license, see the accompanying file // LICENSE or visit http://www.opensource.org/licenses/mit-license.php. // // <author>Herman Schoenfeld</author> // <date>2018</date> // </copyright> //----------------------------------------------------------------------- using System; using Foundation; using UIKit; using CoreGraphics; namespace Sphere10.Framework.iOS { [Foundation.Register("RotatingViewController")] public class RotatingViewController : UIViewController { public UIViewController LandscapeLeftViewController {get;set;} public UIViewController LandscapeRightViewController {get;set;} public UIViewController PortraitViewController {get;set;} private NSObject notificationObserver; public RotatingViewController (IntPtr handle) : base(handle) { } [Foundation.Export("initWithCoder:")] public RotatingViewController (NSCoder coder) : base(coder) { } public RotatingViewController (string nibName, NSBundle bundle) : base(nibName, bundle) { } public RotatingViewController () {} public override void ViewWillAppear (bool animated) { _showView(PortraitViewController.View); } private void _showView(UIView view){ if (this.NavigationController!=null) NavigationController.SetNavigationBarHidden(view!=PortraitViewController.View, false); _removeAllViews(); view.Frame = (CGRect)this.View.Frame; View.AddSubview(view); } public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation) { return true; } public override void ViewDidLoad() { notificationObserver = NSNotificationCenter.DefaultCenter.AddObserver(new NSString("UIDeviceOrientationDidChangeNotification"), DeviceRotated ); } public override void ViewDidAppear (bool animated) { UIDevice.CurrentDevice.BeginGeneratingDeviceOrientationNotifications(); } public override void ViewWillDisappear (bool animated) { UIDevice.CurrentDevice.EndGeneratingDeviceOrientationNotifications(); } private void DeviceRotated(NSNotification notification){ Console.WriteLine("rotated! "+UIDevice.CurrentDevice.Orientation); switch (UIDevice.CurrentDevice.Orientation){ case UIDeviceOrientation.Portrait: _showView(PortraitViewController.View); break; case UIDeviceOrientation.LandscapeLeft: _showView(LandscapeLeftViewController.View); break; case UIDeviceOrientation.LandscapeRight: _showView(LandscapeRightViewController.View); break; } } private void _removeAllViews(){ PortraitViewController.View.RemoveFromSuperview(); LandscapeLeftViewController.View.RemoveFromSuperview(); LandscapeRightViewController.View.RemoveFromSuperview(); } protected void OnDeviceRotated(){ } public override void ViewDidDisappear (bool animated) { base.ViewWillDisappear (animated); NSNotificationCenter.DefaultCenter.RemoveObserver (notificationObserver); } } }
27.404959
147
0.712606
[ "MIT" ]
Sphere10/Framework
src/Sphere10.Framework.iOS/UI/RotatingViewController.cs
3,316
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; namespace System.Net.Security { // This contains adapters to allow a single code path for sync/async logic public partial class SslStream { private interface ISslIOAdapter { ValueTask<int> ReadAsync(Memory<byte> buffer); ValueTask WriteAsync(byte[] buffer, int offset, int count); Task WaitAsync(TaskCompletionSource<bool> waiter); CancellationToken CancellationToken { get; } } private readonly struct AsyncSslIOAdapter : ISslIOAdapter { private readonly SslStream _sslStream; private readonly CancellationToken _cancellationToken; public AsyncSslIOAdapter(SslStream sslStream, CancellationToken cancellationToken) { _cancellationToken = cancellationToken; _sslStream = sslStream; } public ValueTask<int> ReadAsync(Memory<byte> buffer) => _sslStream.InnerStream.ReadAsync(buffer, _cancellationToken); public ValueTask WriteAsync(byte[] buffer, int offset, int count) => _sslStream.InnerStream.WriteAsync(new ReadOnlyMemory<byte>(buffer, offset, count), _cancellationToken); public Task WaitAsync(TaskCompletionSource<bool> waiter) => waiter.Task; public CancellationToken CancellationToken => _cancellationToken; } private readonly struct SyncSslIOAdapter : ISslIOAdapter { private readonly SslStream _sslStream; public SyncSslIOAdapter(SslStream sslStream) => _sslStream = sslStream; public ValueTask<int> ReadAsync(Memory<byte> buffer) => new ValueTask<int>(_sslStream.InnerStream.Read(buffer.Span)); public ValueTask WriteAsync(byte[] buffer, int offset, int count) { _sslStream.InnerStream.Write(buffer, offset, count); return default; } public Task WaitAsync(TaskCompletionSource<bool> waiter) { waiter.Task.Wait(); return Task.CompletedTask; } public CancellationToken CancellationToken => default; } } }
38.15625
184
0.654791
[ "MIT" ]
1shekhar/runtime
src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Implementation.Adapters.cs
2,442
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Omack.Web.ViewModels { public class UserIdentityModel { public int Id { get; set; } public string Name { get; set; } public string Email { get; set; } } }
20
41
0.656667
[ "MIT" ]
KishorTiwari/OnAirMoneyTrack
Omac.Web/ViewModels/UserIdentityModel.cs
302
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [AddComponentMenu("SpacePioneers/Game Mode/Game Mode Mechanics")] public class GameModeMechanics : GameEventListener { [SerializeField] private List<MonoBehaviour> actionMechanics = new List<MonoBehaviour>(); [SerializeField] private List<MonoBehaviour> planningMechanics = new List<MonoBehaviour>(); [SerializeField] private GameModeState globalState; // Start is called before the first frame update void Start() { Response.AddListener(this.OnModeChange); OnModeChange(); } public void OnModeChange() { if(globalState.actualGameMode == GameMode.ACTION) { enterActionMode(); } else if(globalState.actualGameMode == GameMode.PLANNING) { enterPlanningMode(); } } void enterPlanningMode() { foreach(MonoBehaviour m in actionMechanics) { m.enabled = false; } foreach(MonoBehaviour m in planningMechanics) { m.enabled = true; } } void enterActionMode() { foreach(MonoBehaviour m in planningMechanics) { m.enabled = false; } foreach(MonoBehaviour m in actionMechanics) { m.enabled = true; } } public bool IsActionMechanic<T>() { return ListHasClass<T>(actionMechanics); } public bool IsPlanningMechanic<T>() { return ListHasClass<T>(planningMechanics); } private bool ListHasClass<T>(List<MonoBehaviour> list) { foreach(var obj in list) { if(obj is T) { return true; } } return false; } }
21.807229
95
0.585635
[ "MIT" ]
EltonCN/Space-Pioneers
Space Pioneers/Assets/Scripts/GameMode/GameModeMechanics.cs
1,810
C#