content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.IO; namespace E2eTests; [TestClass] public class TheE2eTests : E2eTest { [TestMethod] public async Task HelloWorld() { var output = await BuildAndRunAsync(nameof(HelloWorld)); Assert.AreEqual("hello world", output); } [TestMethod] public async Task MultipleFunctions() { var output = await BuildAndRunAsync(nameof(MultipleFunctions)); Assert.AreEqual("3\n.14159", output); } [TestMethod] public async Task ConstVariable() { var output = await BuildAndRunAsync(nameof(ConstVariable)); Assert.AreEqual("apple", output); } [TestMethod] public async Task LetVariable() { var output = await BuildAndRunAsync(nameof(LetVariable)); Assert.AreEqual("7\n3", output); } [TestMethod] public async Task MultipleVariables() { var output = await BuildAndRunAsync(nameof(MultipleVariables)); Assert.AreEqual("99\napple", output); } [TestMethod] public async Task Math() { var output = await BuildAndRunAsync(nameof(Math)); Assert.AreEqual("4", output); } }
22.901961
71
0.63613
[ "MIT" ]
srmagura/Tungsten
E2eTests/TheE2eTests.cs
1,168
C#
using Microsoft.AspNetCore.Mvc; using ProductsArchive.Application.Common.Interfaces; using ProductsArchive.Application.Identity.Queries; namespace ProductsArchive.WebUI.Controllers; public class IdentityController : ApiControllerBase { private readonly ICurrentUserService _currentUser; public IdentityController(ICurrentUserService currentUser) { _currentUser = currentUser; } [HttpGet("{id}")] public async Task<ActionResult<string?>> GetRole(Guid id) { return await Mediator.Send(new GetUserRoleQuery(id)); } [HttpGet()] public ActionResult<string?> GetUserId() { return _currentUser.UserId; } }
24.214286
62
0.725664
[ "MIT" ]
MatteoZampariniDev/ProductsArchive
src/WebUI/Controllers/IdentityController.cs
680
C#
// ----------------------------------------------------------------------- // <copyright file="DataSetContainer.cs" company="JetCoders Solutions"> // TODO: Update copyright text. // </copyright> // ----------------------------------------------------------------------- namespace Connections { using System.Data; /// <summary> /// Dataset for Report. /// </summary> public class DataSetContainer { /// <summary> /// Report Dataset. /// </summary> public DataSet ReportDataSet { get; set; } /// <summary> /// Report file path. /// </summary> public string ReportPath { get; set; } //public ParameterFields ParameterFields { get; set; } } }
23.172414
75
0.501488
[ "MIT" ]
HananAbdelwahab/jewelry-inventory
JewelInventory/Connections/Objects/DataSetContainer.cs
674
C#
//------------------------------------------------------------------------------ // <auto-generated> // Этот код создан программой. // Исполняемая версия:4.0.30319.42000 // // Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае // повторной генерации кода. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("SignalR_Vuejs__Demo")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("SignalR_Vuejs__Demo")] [assembly: System.Reflection.AssemblyTitleAttribute("SignalR_Vuejs__Demo")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Создано классом WriteCodeFragment MSBuild.
42.208333
92
0.663376
[ "MIT" ]
Niversdack/Predzapis
obj/Debug/netcoreapp2.1/SignalR-Vuejs--Demo.AssemblyInfo.cs
1,161
C#
using System; using Windows.UI.Xaml; namespace Template10.Samples.VoiceAndInkSample.Services.SettingsServices { public partial class SettingsService { public void ApplyUseShellBackButton(bool value) { Template10.Common.BootStrapper.Current.NavigationService.Dispatcher.Dispatch(() => { Template10.Common.BootStrapper.Current.ShowShellBackButton = value; Template10.Common.BootStrapper.Current.UpdateShellBackButton(); Template10.Common.BootStrapper.Current.NavigationService.Refresh(); }); } public void ApplyAppTheme(ApplicationTheme value) { Views.Shell.HamburgerMenu.RefreshStyles(value); } private void ApplyCacheMaxDuration(TimeSpan value) { Template10.Common.BootStrapper.Current.CacheMaxDuration = value; } } }
30.466667
94
0.657549
[ "Apache-2.0" ]
ArtjomP/Template10
Samples/Voice and Ink to TextBox/Services/SettingsServices/SettingsService.Apply.cs
914
C#
using Newtonsoft.Json; namespace OutlookMatters.Core.Settings { public class ChannelSetting { [JsonProperty("id")] public string ChannelId { get; set; } [JsonProperty("display_name")] public string ChannelName { get; set; } [JsonProperty("type")] public ChannelTypeSetting Type { get; set; } } }
22.4375
52
0.62117
[ "MIT" ]
ConnectionMaster/outlook-matters
OutlookMatters.Core/Settings/ChannelSetting.cs
361
C#
namespace BugTrackingApplication { partial class ManagerDashboard { /// <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.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.developersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.testersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.projectsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.logOutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.informationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.usersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.reportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.developersToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.testersToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.optionsToolStripMenuItem, this.informationToolStripMenuItem, this.reportToolStripMenuItem, this.helpToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(20, 60); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(1326, 24); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "menuStrip1"; // // optionsToolStripMenuItem // this.optionsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.developersToolStripMenuItem, this.testersToolStripMenuItem, this.projectsToolStripMenuItem, this.toolStripSeparator1, this.logOutToolStripMenuItem}); this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem"; this.optionsToolStripMenuItem.Size = new System.Drawing.Size(61, 20); this.optionsToolStripMenuItem.Text = "Options"; // // developersToolStripMenuItem // this.developersToolStripMenuItem.Name = "developersToolStripMenuItem"; this.developersToolStripMenuItem.Size = new System.Drawing.Size(132, 22); this.developersToolStripMenuItem.Text = "Developers"; this.developersToolStripMenuItem.Click += new System.EventHandler(this.developersToolStripMenuItem_Click); // // testersToolStripMenuItem // this.testersToolStripMenuItem.Name = "testersToolStripMenuItem"; this.testersToolStripMenuItem.Size = new System.Drawing.Size(132, 22); this.testersToolStripMenuItem.Text = "Testers"; this.testersToolStripMenuItem.Click += new System.EventHandler(this.testersToolStripMenuItem_Click); // // projectsToolStripMenuItem // this.projectsToolStripMenuItem.Name = "projectsToolStripMenuItem"; this.projectsToolStripMenuItem.Size = new System.Drawing.Size(132, 22); this.projectsToolStripMenuItem.Text = "Projects"; this.projectsToolStripMenuItem.Click += new System.EventHandler(this.projectsToolStripMenuItem_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(129, 6); // // logOutToolStripMenuItem // this.logOutToolStripMenuItem.Name = "logOutToolStripMenuItem"; this.logOutToolStripMenuItem.Size = new System.Drawing.Size(132, 22); this.logOutToolStripMenuItem.Text = "Log Out"; this.logOutToolStripMenuItem.Click += new System.EventHandler(this.logOutToolStripMenuItem_Click); // // informationToolStripMenuItem // this.informationToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.usersToolStripMenuItem}); this.informationToolStripMenuItem.Name = "informationToolStripMenuItem"; this.informationToolStripMenuItem.Size = new System.Drawing.Size(82, 20); this.informationToolStripMenuItem.Text = "Information"; // // usersToolStripMenuItem // this.usersToolStripMenuItem.Name = "usersToolStripMenuItem"; this.usersToolStripMenuItem.Size = new System.Drawing.Size(102, 22); this.usersToolStripMenuItem.Text = "Users"; this.usersToolStripMenuItem.Click += new System.EventHandler(this.usersToolStripMenuItem_Click); // // reportToolStripMenuItem // this.reportToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.developersToolStripMenuItem1, this.testersToolStripMenuItem1}); this.reportToolStripMenuItem.Name = "reportToolStripMenuItem"; this.reportToolStripMenuItem.Size = new System.Drawing.Size(54, 20); this.reportToolStripMenuItem.Text = "Report"; // // developersToolStripMenuItem1 // this.developersToolStripMenuItem1.Name = "developersToolStripMenuItem1"; this.developersToolStripMenuItem1.Size = new System.Drawing.Size(152, 22); this.developersToolStripMenuItem1.Text = "Developers"; this.developersToolStripMenuItem1.Click += new System.EventHandler(this.developersToolStripMenuItem1_Click); // // testersToolStripMenuItem1 // this.testersToolStripMenuItem1.Name = "testersToolStripMenuItem1"; this.testersToolStripMenuItem1.Size = new System.Drawing.Size(152, 22); this.testersToolStripMenuItem1.Text = "Testers"; this.testersToolStripMenuItem1.Click += new System.EventHandler(this.testersToolStripMenuItem1_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(107, 22); this.aboutToolStripMenuItem.Text = "About"; this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click); // // ManagerDashboard // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1366, 740); this.Controls.Add(this.menuStrip1); this.MainMenuStrip = this.menuStrip1; this.Name = "ManagerDashboard"; this.Text = "ManagerDashboard"; this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.ManagerDashboard_FormClosed); this.Load += new System.EventHandler(this.ManagerDashboard_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 optionsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem developersToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem testersToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem projectsToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripMenuItem logOutToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem informationToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem usersToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem reportToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem developersToolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem testersToolStripMenuItem1; } }
54.349206
120
0.660826
[ "MIT" ]
codexponent/bugtrackingapplication
BugTrackingApplication/ManagerDashboard.Designer.cs
10,274
C#
/* * Copyright 2009 Kriztian Jake Sta. Teresa * * 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 Daemoniq.Framework; using NUnit.Framework; namespace Daemoniq.Tests.Core { [TestFixture] public class RunCommandTests : CommandTestBase { public RunCommandTests() { Action = ConfigurationAction.Run; } } }
31.241379
77
0.682119
[ "Apache-2.0" ]
jakelite/daemoniq
src/Daemoniq.Tests/Core/RunCommandTests.cs
906
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // 制御されます。アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更します。 [assembly: AssemblyTitle("SimplyMessageBox")] [assembly: AssemblyDescription("簡単にMessageBoxを作成できるアプリケーションです。")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("yossi.cloud-software")] [assembly: AssemblyProduct("SimplyMessageBox")] [assembly: AssemblyCopyright("Copyright (c) 2021 yossi")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、このアセンブリ内の型は COM コンポーネントから // 参照できなくなります。COM からこのアセンブリ内の型にアクセスする必要がある場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("ba09644e-6715-41d5-accd-7de307a8ad1f")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // リビジョン // // すべての値を指定するか、次を使用してビルド番号とリビジョン番号を既定に設定できます // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.1.0")]
31.108108
65
0.761077
[ "MIT" ]
fuyossi/SimplyMessageBox
SimplyMessageBox/Properties/AssemblyInfo.cs
1,799
C#
/* * LUSID API * * # Introduction This page documents the [LUSID APIs](https://www.lusid.com/api/swagger), which allows authorised clients to query and update their data within the LUSID platform. SDKs to interact with the LUSID APIs are available in the following languages and frameworks: * [C#](https://github.com/finbourne/lusid-sdk-csharp) * [Java](https://github.com/finbourne/lusid-sdk-java) * [JavaScript](https://github.com/finbourne/lusid-sdk-js) * [Python](https://github.com/finbourne/lusid-sdk-python) * [Angular](https://github.com/finbourne/lusid-sdk-angular) The LUSID platform is made up of a number of sub-applications. You can find the API / swagger documentation by following the links in the table below. | Application | Description | API / Swagger Documentation | | - -- -- | - -- -- | - -- - | | LUSID | Open, API-first, developer-friendly investment data platform. | [Swagger](https://www.lusid.com/api/swagger/index.html) | | Web app | User-facing front end for LUSID. | [Swagger](https://www.lusid.com/app/swagger/index.html) | | Scheduler | Automated job scheduler. | [Swagger](https://www.lusid.com/scheduler2/swagger/index.html) | | Insights |Monitoring and troubleshooting service. | [Swagger](https://www.lusid.com/insights/swagger/index.html) | | Identity | Identity management for LUSID (in conjuction with Access) | [Swagger](https://www.lusid.com/identity/swagger/index.html) | | Access | Access control for LUSID (in conjunction with Identity) | [Swagger](https://www.lusid.com/access/swagger/index.html) | | Drive | Secure file repository and manager for collaboration. | [Swagger](https://www.lusid.com/drive/swagger/index.html) | | Luminesce | Data virtualisation service (query data from multiple providers, including LUSID) | [Swagger](https://www.lusid.com/honeycomb/swagger/index.html) | | Notification | Notification service. | [Swagger](https://www.lusid.com/notifications/swagger/index.html) | | Configuration | File store for secrets and other sensitive information. | [Swagger](https://www.lusid.com/configuration/swagger/index.html) | # Error Codes | Code|Name|Description | | - --|- --|- -- | | <a name=\"-10\">-10</a>|Server Configuration Error| | | <a name=\"-1\">-1</a>|Unknown error|An unexpected error was encountered on our side. | | <a name=\"102\">102</a>|Version Not Found| | | <a name=\"103\">103</a>|Api Rate Limit Violation| | | <a name=\"104\">104</a>|Instrument Not Found| | | <a name=\"105\">105</a>|Property Not Found| | | <a name=\"106\">106</a>|Portfolio Recursion Depth| | | <a name=\"108\">108</a>|Group Not Found| | | <a name=\"109\">109</a>|Portfolio Not Found| | | <a name=\"110\">110</a>|Property Schema Not Found| | | <a name=\"111\">111</a>|Portfolio Ancestry Not Found| | | <a name=\"112\">112</a>|Portfolio With Id Already Exists| | | <a name=\"113\">113</a>|Orphaned Portfolio| | | <a name=\"119\">119</a>|Missing Base Claims| | | <a name=\"121\">121</a>|Property Not Defined| | | <a name=\"122\">122</a>|Cannot Delete System Property| | | <a name=\"123\">123</a>|Cannot Modify Immutable Property Field| | | <a name=\"124\">124</a>|Property Already Exists| | | <a name=\"125\">125</a>|Invalid Property Life Time| | | <a name=\"126\">126</a>|Property Constraint Style Excludes Properties| | | <a name=\"127\">127</a>|Cannot Modify Default Data Type| | | <a name=\"128\">128</a>|Group Already Exists| | | <a name=\"129\">129</a>|No Such Data Type| | | <a name=\"130\">130</a>|Undefined Value For Data Type| | | <a name=\"131\">131</a>|Unsupported Value Type Defined On Data Type| | | <a name=\"132\">132</a>|Validation Error| | | <a name=\"133\">133</a>|Loop Detected In Group Hierarchy| | | <a name=\"134\">134</a>|Undefined Acceptable Values| | | <a name=\"135\">135</a>|Sub Group Already Exists| | | <a name=\"138\">138</a>|Price Source Not Found| | | <a name=\"139\">139</a>|Analytic Store Not Found| | | <a name=\"141\">141</a>|Analytic Store Already Exists| | | <a name=\"143\">143</a>|Client Instrument Already Exists| | | <a name=\"144\">144</a>|Duplicate In Parameter Set| | | <a name=\"147\">147</a>|Results Not Found| | | <a name=\"148\">148</a>|Order Field Not In Result Set| | | <a name=\"149\">149</a>|Operation Failed| | | <a name=\"150\">150</a>|Elastic Search Error| | | <a name=\"151\">151</a>|Invalid Parameter Value| | | <a name=\"153\">153</a>|Command Processing Failure| | | <a name=\"154\">154</a>|Entity State Construction Failure| | | <a name=\"155\">155</a>|Entity Timeline Does Not Exist| | | <a name=\"156\">156</a>|Concurrency Conflict Failure| | | <a name=\"157\">157</a>|Invalid Request| | | <a name=\"158\">158</a>|Event Publish Unknown| | | <a name=\"159\">159</a>|Event Query Failure| | | <a name=\"160\">160</a>|Blob Did Not Exist| | | <a name=\"162\">162</a>|Sub System Request Failure| | | <a name=\"163\">163</a>|Sub System Configuration Failure| | | <a name=\"165\">165</a>|Failed To Delete| | | <a name=\"166\">166</a>|Upsert Client Instrument Failure| | | <a name=\"167\">167</a>|Illegal As At Interval| | | <a name=\"168\">168</a>|Illegal Bitemporal Query| | | <a name=\"169\">169</a>|Invalid Alternate Id| | | <a name=\"170\">170</a>|Cannot Add Source Portfolio Property Explicitly| | | <a name=\"171\">171</a>|Entity Already Exists In Group| | | <a name=\"173\">173</a>|Entity With Id Already Exists| | | <a name=\"174\">174</a>|Derived Portfolio Details Do Not Exist| | | <a name=\"176\">176</a>|Portfolio With Name Already Exists| | | <a name=\"177\">177</a>|Invalid Transactions| | | <a name=\"178\">178</a>|Reference Portfolio Not Found| | | <a name=\"179\">179</a>|Duplicate Id| | | <a name=\"180\">180</a>|Command Retrieval Failure| | | <a name=\"181\">181</a>|Data Filter Application Failure| | | <a name=\"182\">182</a>|Search Failed| | | <a name=\"183\">183</a>|Movements Engine Configuration Key Failure| | | <a name=\"184\">184</a>|Fx Rate Source Not Found| | | <a name=\"185\">185</a>|Accrual Source Not Found| | | <a name=\"186\">186</a>|Access Denied| | | <a name=\"187\">187</a>|Invalid Identity Token| | | <a name=\"188\">188</a>|Invalid Request Headers| | | <a name=\"189\">189</a>|Price Not Found| | | <a name=\"190\">190</a>|Invalid Sub Holding Keys Provided| | | <a name=\"191\">191</a>|Duplicate Sub Holding Keys Provided| | | <a name=\"192\">192</a>|Cut Definition Not Found| | | <a name=\"193\">193</a>|Cut Definition Invalid| | | <a name=\"194\">194</a>|Time Variant Property Deletion Date Unspecified| | | <a name=\"195\">195</a>|Perpetual Property Deletion Date Specified| | | <a name=\"196\">196</a>|Time Variant Property Upsert Date Unspecified| | | <a name=\"197\">197</a>|Perpetual Property Upsert Date Specified| | | <a name=\"200\">200</a>|Invalid Unit For Data Type| | | <a name=\"201\">201</a>|Invalid Type For Data Type| | | <a name=\"202\">202</a>|Invalid Value For Data Type| | | <a name=\"203\">203</a>|Unit Not Defined For Data Type| | | <a name=\"204\">204</a>|Units Not Supported On Data Type| | | <a name=\"205\">205</a>|Cannot Specify Units On Data Type| | | <a name=\"206\">206</a>|Unit Schema Inconsistent With Data Type| | | <a name=\"207\">207</a>|Unit Definition Not Specified| | | <a name=\"208\">208</a>|Duplicate Unit Definitions Specified| | | <a name=\"209\">209</a>|Invalid Units Definition| | | <a name=\"210\">210</a>|Invalid Instrument Identifier Unit| | | <a name=\"211\">211</a>|Holdings Adjustment Does Not Exist| | | <a name=\"212\">212</a>|Could Not Build Excel Url| | | <a name=\"213\">213</a>|Could Not Get Excel Version| | | <a name=\"214\">214</a>|Instrument By Code Not Found| | | <a name=\"215\">215</a>|Entity Schema Does Not Exist| | | <a name=\"216\">216</a>|Feature Not Supported On Portfolio Type| | | <a name=\"217\">217</a>|Quote Not Found| | | <a name=\"218\">218</a>|Invalid Quote Identifier| | | <a name=\"219\">219</a>|Invalid Metric For Data Type| | | <a name=\"220\">220</a>|Invalid Instrument Definition| | | <a name=\"221\">221</a>|Instrument Upsert Failure| | | <a name=\"222\">222</a>|Reference Portfolio Request Not Supported| | | <a name=\"223\">223</a>|Transaction Portfolio Request Not Supported| | | <a name=\"224\">224</a>|Invalid Property Value Assignment| | | <a name=\"230\">230</a>|Transaction Type Not Found| | | <a name=\"231\">231</a>|Transaction Type Duplication| | | <a name=\"232\">232</a>|Portfolio Does Not Exist At Given Date| | | <a name=\"233\">233</a>|Query Parser Failure| | | <a name=\"234\">234</a>|Duplicate Constituent| | | <a name=\"235\">235</a>|Unresolved Instrument Constituent| | | <a name=\"236\">236</a>|Unresolved Instrument In Transition| | | <a name=\"237\">237</a>|Missing Side Definitions| | | <a name=\"299\">299</a>|Invalid Recipe| | | <a name=\"300\">300</a>|Missing Recipe| | | <a name=\"301\">301</a>|Dependencies| | | <a name=\"304\">304</a>|Portfolio Preprocess Failure| | | <a name=\"310\">310</a>|Valuation Engine Failure| | | <a name=\"311\">311</a>|Task Factory Failure| | | <a name=\"312\">312</a>|Task Evaluation Failure| | | <a name=\"313\">313</a>|Task Generation Failure| | | <a name=\"314\">314</a>|Engine Configuration Failure| | | <a name=\"315\">315</a>|Model Specification Failure| | | <a name=\"320\">320</a>|Market Data Key Failure| | | <a name=\"321\">321</a>|Market Resolver Failure| | | <a name=\"322\">322</a>|Market Data Failure| | | <a name=\"330\">330</a>|Curve Failure| | | <a name=\"331\">331</a>|Volatility Surface Failure| | | <a name=\"332\">332</a>|Volatility Cube Failure| | | <a name=\"350\">350</a>|Instrument Failure| | | <a name=\"351\">351</a>|Cash Flows Failure| | | <a name=\"352\">352</a>|Reference Data Failure| | | <a name=\"360\">360</a>|Aggregation Failure| | | <a name=\"361\">361</a>|Aggregation Measure Failure| | | <a name=\"370\">370</a>|Result Retrieval Failure| | | <a name=\"371\">371</a>|Result Processing Failure| | | <a name=\"372\">372</a>|Vendor Result Processing Failure| | | <a name=\"373\">373</a>|Vendor Result Mapping Failure| | | <a name=\"374\">374</a>|Vendor Library Unauthorised| | | <a name=\"375\">375</a>|Vendor Connectivity Error| | | <a name=\"376\">376</a>|Vendor Interface Error| | | <a name=\"377\">377</a>|Vendor Pricing Failure| | | <a name=\"378\">378</a>|Vendor Translation Failure| | | <a name=\"379\">379</a>|Vendor Key Mapping Failure| | | <a name=\"380\">380</a>|Vendor Reflection Failure| | | <a name=\"381\">381</a>|Vendor Process Failure| | | <a name=\"382\">382</a>|Vendor System Failure| | | <a name=\"390\">390</a>|Attempt To Upsert Duplicate Quotes| | | <a name=\"391\">391</a>|Corporate Action Source Does Not Exist| | | <a name=\"392\">392</a>|Corporate Action Source Already Exists| | | <a name=\"393\">393</a>|Instrument Identifier Already In Use| | | <a name=\"394\">394</a>|Properties Not Found| | | <a name=\"395\">395</a>|Batch Operation Aborted| | | <a name=\"400\">400</a>|Invalid Iso4217 Currency Code| | | <a name=\"401\">401</a>|Cannot Assign Instrument Identifier To Currency| | | <a name=\"402\">402</a>|Cannot Assign Currency Identifier To Non Currency| | | <a name=\"403\">403</a>|Currency Instrument Cannot Be Deleted| | | <a name=\"404\">404</a>|Currency Instrument Cannot Have Economic Definition| | | <a name=\"405\">405</a>|Currency Instrument Cannot Have Lookthrough Portfolio| | | <a name=\"406\">406</a>|Cannot Create Currency Instrument With Multiple Identifiers| | | <a name=\"407\">407</a>|Specified Currency Is Undefined| | | <a name=\"410\">410</a>|Index Does Not Exist| | | <a name=\"411\">411</a>|Sort Field Does Not Exist| | | <a name=\"413\">413</a>|Negative Pagination Parameters| | | <a name=\"414\">414</a>|Invalid Search Syntax| | | <a name=\"415\">415</a>|Filter Execution Timeout| | | <a name=\"420\">420</a>|Side Definition Inconsistent| | | <a name=\"450\">450</a>|Invalid Quote Access Metadata Rule| | | <a name=\"451\">451</a>|Access Metadata Not Found| | | <a name=\"452\">452</a>|Invalid Access Metadata Identifier| | | <a name=\"460\">460</a>|Standard Resource Not Found| | | <a name=\"461\">461</a>|Standard Resource Conflict| | | <a name=\"462\">462</a>|Calendar Not Found| | | <a name=\"463\">463</a>|Date In A Calendar Not Found| | | <a name=\"464\">464</a>|Invalid Date Source Data| | | <a name=\"465\">465</a>|Invalid Timezone| | | <a name=\"601\">601</a>|Person Identifier Already In Use| | | <a name=\"602\">602</a>|Person Not Found| | | <a name=\"603\">603</a>|Cannot Set Identifier| | | <a name=\"617\">617</a>|Invalid Recipe Specification In Request| | | <a name=\"618\">618</a>|Inline Recipe Deserialisation Failure| | | <a name=\"619\">619</a>|Identifier Types Not Set For Entity| | | <a name=\"620\">620</a>|Cannot Delete All Client Defined Identifiers| | | <a name=\"650\">650</a>|The Order requested was not found.| | | <a name=\"654\">654</a>|The Allocation requested was not found.| | | <a name=\"655\">655</a>|Cannot build the fx forward target with the given holdings.| | | <a name=\"656\">656</a>|Group does not contain expected entities.| | | <a name=\"665\">665</a>|Destination directory not found| | | <a name=\"667\">667</a>|Relation definition already exists| | | <a name=\"672\">672</a>|Could not retrieve file contents| | | <a name=\"673\">673</a>|Missing entitlements for entities in Group| | | <a name=\"674\">674</a>|Next Best Action not found| | | <a name=\"676\">676</a>|Relation definition not defined| | | <a name=\"677\">677</a>|Invalid entity identifier for relation| | | <a name=\"681\">681</a>|Sorting by specified field not supported|One or more of the provided fields to order by were either invalid or not supported. | | <a name=\"682\">682</a>|Too many fields to sort by|The number of fields to sort the data by exceeds the number allowed by the endpoint | | <a name=\"684\">684</a>|Sequence Not Found| | | <a name=\"685\">685</a>|Sequence Already Exists| | | <a name=\"686\">686</a>|Non-cycling sequence has been exhausted| | | <a name=\"687\">687</a>|Legal Entity Identifier Already In Use| | | <a name=\"688\">688</a>|Legal Entity Not Found| | | <a name=\"689\">689</a>|The supplied pagination token is invalid| | | <a name=\"690\">690</a>|Property Type Is Not Supported| | | <a name=\"691\">691</a>|Multiple Tax-lots For Currency Type Is Not Supported| | | <a name=\"692\">692</a>|This endpoint does not support impersonation| | | <a name=\"693\">693</a>|Entity type is not supported for Relationship| | | <a name=\"694\">694</a>|Relationship Validation Failure| | | <a name=\"695\">695</a>|Relationship Not Found| | | <a name=\"697\">697</a>|Derived Property Formula No Longer Valid| | | <a name=\"698\">698</a>|Story is not available| | | <a name=\"703\">703</a>|Corporate Action Does Not Exist| | | <a name=\"720\">720</a>|The provided sort and filter combination is not valid| | | <a name=\"721\">721</a>|A2B generation failed| | | <a name=\"722\">722</a>|Aggregated Return Calculation Failure| | | <a name=\"723\">723</a>|Custom Entity Definition Identifier Already In Use| | | <a name=\"724\">724</a>|Custom Entity Definition Not Found| | | <a name=\"725\">725</a>|The Placement requested was not found.| | | <a name=\"726\">726</a>|The Execution requested was not found.| | | <a name=\"727\">727</a>|The Block requested was not found.| | | <a name=\"728\">728</a>|The Participation requested was not found.| | | <a name=\"729\">729</a>|The Package requested was not found.| | | <a name=\"730\">730</a>|The OrderInstruction requested was not found.| | | <a name=\"732\">732</a>|Custom Entity not found.| | | <a name=\"733\">733</a>|Custom Entity Identifier already in use.| | | <a name=\"735\">735</a>|Calculation Failed.| | | <a name=\"736\">736</a>|An expected key on HttpResponse is missing.| | | <a name=\"737\">737</a>|A required fee detail is missing.| | | <a name=\"738\">738</a>|Zero rows were returned from Luminesce| | | <a name=\"739\">739</a>|Provided Weekend Mask was invalid| | | <a name=\"742\">742</a>|Custom Entity fields do not match the definition| | | <a name=\"746\">746</a>|The provided sequence is not valid.| | | <a name=\"751\">751</a>|The type of the Custom Entity is different than the type provided in the definition.| | | <a name=\"752\">752</a>|Luminesce process returned an error.| | | <a name=\"753\">753</a>|File name or content incompatible with operation.| | | <a name=\"755\">755</a>|Schema of response from Drive is not as expected.| | | <a name=\"757\">757</a>|Schema of response from Luminesce is not as expected.| | | <a name=\"758\">758</a>|Luminesce timed out.| | | <a name=\"763\">763</a>|Invalid Lusid Entity Identifier Unit| | | <a name=\"768\">768</a>|Fee rule not found.| | | <a name=\"769\">769</a>|Cannot update the base currency of a portfolio with transactions loaded| | * * The version of the OpenAPI document: 0.11.3984 * Contact: info@finbourne.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Lusid.Sdk.Client.OpenAPIDateConverter; namespace Lusid.Sdk.Model { /// <summary> /// A paginated list of resource that can be returned from a request. /// </summary> [DataContract(Name = "PagedResourceListOfPackage")] public partial class PagedResourceListOfPackage : IEquatable<PagedResourceListOfPackage> { /// <summary> /// Initializes a new instance of the <see cref="PagedResourceListOfPackage" /> class. /// </summary> [JsonConstructorAttribute] protected PagedResourceListOfPackage() { } /// <summary> /// Initializes a new instance of the <see cref="PagedResourceListOfPackage" /> class. /// </summary> /// <param name="nextPage">The next page of results..</param> /// <param name="previousPage">The previous page of results..</param> /// <param name="values">The resources to list. (required).</param> /// <param name="href">The URI of the resource list..</param> /// <param name="links">Collection of links..</param> public PagedResourceListOfPackage(string nextPage = default(string), string previousPage = default(string), List<Package> values = default(List<Package>), string href = default(string), List<Link> links = default(List<Link>)) { // to ensure "values" is required (not null) this.Values = values ?? throw new ArgumentNullException("values is a required property for PagedResourceListOfPackage and cannot be null"); this.NextPage = nextPage; this.PreviousPage = previousPage; this.Href = href; this.Links = links; } /// <summary> /// The next page of results. /// </summary> /// <value>The next page of results.</value> [DataMember(Name = "nextPage", EmitDefaultValue = true)] public string NextPage { get; set; } /// <summary> /// The previous page of results. /// </summary> /// <value>The previous page of results.</value> [DataMember(Name = "previousPage", EmitDefaultValue = true)] public string PreviousPage { get; set; } /// <summary> /// The resources to list. /// </summary> /// <value>The resources to list.</value> [DataMember(Name = "values", IsRequired = true, EmitDefaultValue = false)] public List<Package> Values { get; set; } /// <summary> /// The URI of the resource list. /// </summary> /// <value>The URI of the resource list.</value> [DataMember(Name = "href", EmitDefaultValue = true)] public string Href { get; set; } /// <summary> /// Collection of links. /// </summary> /// <value>Collection of links.</value> [DataMember(Name = "links", EmitDefaultValue = true)] public List<Link> Links { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class PagedResourceListOfPackage {\n"); sb.Append(" NextPage: ").Append(NextPage).Append("\n"); sb.Append(" PreviousPage: ").Append(PreviousPage).Append("\n"); sb.Append(" Values: ").Append(Values).Append("\n"); sb.Append(" Href: ").Append(Href).Append("\n"); sb.Append(" Links: ").Append(Links).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as PagedResourceListOfPackage); } /// <summary> /// Returns true if PagedResourceListOfPackage instances are equal /// </summary> /// <param name="input">Instance of PagedResourceListOfPackage to be compared</param> /// <returns>Boolean</returns> public bool Equals(PagedResourceListOfPackage input) { if (input == null) return false; return ( this.NextPage == input.NextPage || (this.NextPage != null && this.NextPage.Equals(input.NextPage)) ) && ( this.PreviousPage == input.PreviousPage || (this.PreviousPage != null && this.PreviousPage.Equals(input.PreviousPage)) ) && ( this.Values == input.Values || this.Values != null && input.Values != null && this.Values.SequenceEqual(input.Values) ) && ( this.Href == input.Href || (this.Href != null && this.Href.Equals(input.Href)) ) && ( this.Links == input.Links || this.Links != null && input.Links != null && this.Links.SequenceEqual(input.Links) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.NextPage != null) hashCode = hashCode * 59 + this.NextPage.GetHashCode(); if (this.PreviousPage != null) hashCode = hashCode * 59 + this.PreviousPage.GetHashCode(); if (this.Values != null) hashCode = hashCode * 59 + this.Values.GetHashCode(); if (this.Href != null) hashCode = hashCode * 59 + this.Href.GetHashCode(); if (this.Links != null) hashCode = hashCode * 59 + this.Links.GetHashCode(); return hashCode; } } } }
124.78866
16,891
0.617002
[ "MIT" ]
EiriniMavroudi/lusid-sdk-csharp-preview
sdk/Lusid.Sdk/Model/PagedResourceListOfPackage.cs
24,209
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. namespace SolToBoogie { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using BoogieAST; using SolidityAST; public class TranslatorContext { public BoogieProgram Program { get; private set; } public Dictionary<int, ASTNode> IdToNodeMap { get; set; } public string SourceDirectory { get; set; } // source file path of ASTNode public Dictionary<ASTNode, string> ASTNodeToSourcePathMap { get; private set; } // source file line number of ASTNode public Dictionary<ASTNode, int> ASTNodeToSourceLineNumberMap { get; private set; } // all contracts defined in the program public HashSet<ContractDefinition> ContractDefinitions { get; private set; } // map from each contract to its sub types (including itself) public Dictionary<ContractDefinition, HashSet<ContractDefinition>> ContractToSubTypesMap { get; private set; } // all state variables explicitly defined in each contract public Dictionary<ContractDefinition, HashSet<VariableDeclaration>> ContractToStateVarsMap { get; private set; } public Dictionary<VariableDeclaration, ContractDefinition> StateVarToContractMap { get; private set; } // all mappings explicitly defined in each contract public Dictionary<ContractDefinition, HashSet<VariableDeclaration>> ContractToMappingsMap { get; private set; } // all arrays explicityly defined in each contract public Dictionary<ContractDefinition, HashSet<VariableDeclaration>> ContractToArraysMap { get; private set; } // explicit constructor defined in each contract // solidity only allows at most one constructor for each contract public Dictionary<ContractDefinition, FunctionDefinition> ContractToConstructorMap { get; private set; } // all events explicitly defined in each contract public Dictionary<ContractDefinition, HashSet<EventDefinition>> ContractToEventsMap { get; private set; } public Dictionary<EventDefinition, ContractDefinition> EventToContractMap { get; private set; } // all functions explicitly defined in each contract // FIXME: getters for public state variables public Dictionary<ContractDefinition, HashSet<FunctionDefinition>> ContractToFunctionsMap { get; private set; } public Dictionary<ContractDefinition, HashSet<string>> ContractToFuncSigsMap { get; private set; } public Dictionary<FunctionDefinition, ContractDefinition> FunctionToContractMap { get; private set; } // FunctionSignature -> (DynamicType -> FunctionDefinition) public Dictionary<string, Dictionary<ContractDefinition, FunctionDefinition>> FuncSigResolutionMap { get; private set; } // all functions (including private ones) visible in each contract public Dictionary<ContractDefinition, HashSet<FunctionDefinition>> ContractToVisibleFunctionsMap { get; private set; } // StateVarName -> (Dynamictype -> StateVariableDeclaration) public Dictionary<string, Dictionary<ContractDefinition, VariableDeclaration>> StateVarNameResolutionMap { get; private set; } // all state variables (including private ones) visible in each contract public Dictionary<ContractDefinition, HashSet<VariableDeclaration>> ContractToVisibleStateVarsMap { get; private set; } // M -> BoogieProcedure(A) for Modifier M {Stmt A; _; Stmt B} public Dictionary<string, BoogieProcedure> ModifierToBoogiePreProc { get; private set;} // M -> BoogieProcedure(B) for Modifier M {Stmt A; _; Stmt B} public Dictionary<string, BoogieProcedure> ModifierToBoogiePostProc { get; private set;} // M -> BoogieImplementation(A) for Modifier M {Stmt A; _; Stmt B} public Dictionary<string, BoogieImplementation> ModifierToBoogiePreImpl { get; private set;} // M -> BoogieImplementation(B) for Modifier M {Stmt A; _; Stmt B} public Dictionary<string, BoogieImplementation> ModifierToBoogiePostImpl { get; private set;} // Options flags public TranslatorFlags TranslateFlags { get; private set; } // num of fresh identifiers, should be incremented when making new fresh id private int freshIdentifierCount = 0; // methods whose translation has to be skipped private HashSet<Tuple<string, string>> IgnoreMethods; // do we generate inline attributes (required for unbounded verification) private bool genInlineAttrInBpl; public TranslatorContext(HashSet<Tuple<string, string>> ignoreMethods, bool _genInlineAttrInBpl, TranslatorFlags _translateFlags = null) { Program = new BoogieProgram(); ContractDefinitions = new HashSet<ContractDefinition>(); ASTNodeToSourcePathMap = new Dictionary<ASTNode, string>(); ASTNodeToSourceLineNumberMap = new Dictionary<ASTNode, int>(); ContractToSubTypesMap = new Dictionary<ContractDefinition, HashSet<ContractDefinition>>(); ContractToStateVarsMap = new Dictionary<ContractDefinition, HashSet<VariableDeclaration>>(); ContractToMappingsMap = new Dictionary<ContractDefinition, HashSet<VariableDeclaration>>(); ContractToArraysMap = new Dictionary<ContractDefinition, HashSet<VariableDeclaration>>(); StateVarToContractMap = new Dictionary<VariableDeclaration, ContractDefinition>(); ContractToConstructorMap = new Dictionary<ContractDefinition, FunctionDefinition>(); ContractToEventsMap = new Dictionary<ContractDefinition, HashSet<EventDefinition>>(); EventToContractMap = new Dictionary<EventDefinition, ContractDefinition>(); ContractToFunctionsMap = new Dictionary<ContractDefinition, HashSet<FunctionDefinition>>(); ContractToFuncSigsMap = new Dictionary<ContractDefinition, HashSet<string>>(); FunctionToContractMap = new Dictionary<FunctionDefinition, ContractDefinition>(); FuncSigResolutionMap = new Dictionary<string, Dictionary<ContractDefinition, FunctionDefinition>>(); ContractToVisibleFunctionsMap = new Dictionary<ContractDefinition, HashSet<FunctionDefinition>>(); StateVarNameResolutionMap = new Dictionary<string, Dictionary<ContractDefinition, VariableDeclaration>>(); ContractToVisibleStateVarsMap = new Dictionary<ContractDefinition, HashSet<VariableDeclaration>>(); ModifierToBoogiePreProc = new Dictionary<string, BoogieProcedure>(); ModifierToBoogiePostProc = new Dictionary<string, BoogieProcedure>(); ModifierToBoogiePreImpl = new Dictionary<string, BoogieImplementation>(); ModifierToBoogiePostImpl = new Dictionary<string, BoogieImplementation>(); IgnoreMethods = ignoreMethods; genInlineAttrInBpl = _genInlineAttrInBpl; TranslateFlags = _translateFlags; } public bool HasASTNodeId(int id) { return IdToNodeMap.ContainsKey(id); } public ASTNode GetASTNodeById(int id) { Debug.Assert(IdToNodeMap.ContainsKey(id), $"Unknown id: {id}"); return IdToNodeMap[id]; } public void AddSourceInfoForASTNode(ASTNode node, string absolutePath, int lineNumber) { Debug.Assert(!ASTNodeToSourcePathMap.ContainsKey(node)); Debug.Assert(!ASTNodeToSourceLineNumberMap.ContainsKey(node)); ASTNodeToSourcePathMap[node] = absolutePath; ASTNodeToSourceLineNumberMap[node] = lineNumber; } public string GetAbsoluteSourcePathOfASTNode(ASTNode node) { Debug.Assert(ASTNodeToSourcePathMap.ContainsKey(node)); return ASTNodeToSourcePathMap[node]; } public int GetLineNumberOfASTNode(ASTNode node) { Debug.Assert(ASTNodeToSourceLineNumberMap.ContainsKey(node)); return ASTNodeToSourceLineNumberMap[node]; } public HashSet<FunctionDefinition> GetFuncDefintionsInContract(ContractDefinition contract) { if (ContractToFunctionsMap.ContainsKey(contract)) { return ContractToFunctionsMap[contract]; } return new HashSet<FunctionDefinition>(); } public HashSet<EventDefinition> GetEventDefintionsInContract(ContractDefinition contract) { if (ContractToEventsMap.ContainsKey(contract)) { return ContractToEventsMap[contract]; } return new HashSet<EventDefinition>(); } public void AddContract(ContractDefinition contract) { ContractDefinitions.Add(contract); } public bool HasContractName(string contractName) { foreach (ContractDefinition contract in ContractDefinitions) { if (contract.Name.Equals(contractName)) { return true; } } return false; } public ContractDefinition GetContractByName(string contractName) { foreach (ContractDefinition contract in ContractDefinitions) { if (contract.Name.Equals(contractName)) { return contract; } } Debug.Assert(false, $"Cannot find contract: {contractName}"); return null; } public void AddSubTypeToContract(ContractDefinition contract, ContractDefinition subtype) { if (!ContractToSubTypesMap.ContainsKey(contract)) { ContractToSubTypesMap[contract] = new HashSet<ContractDefinition>(); } ContractToSubTypesMap[contract].Add(subtype); } public HashSet<ContractDefinition> GetSubTypesOfContract(ContractDefinition contract) { Debug.Assert(ContractToSubTypesMap.ContainsKey(contract), $"Cannot find {contract.Name} in the sub type map"); return ContractToSubTypesMap[contract]; } public void AddStateVarToContract(ContractDefinition contract, VariableDeclaration varDecl) { Debug.Assert(varDecl.StateVariable, $"{varDecl.Name} is not a state variable"); if (!ContractToStateVarsMap.ContainsKey(contract)) { ContractToStateVarsMap[contract] = new HashSet<VariableDeclaration>(); } Debug.Assert(!ContractToStateVarsMap[contract].Contains(varDecl), $"Duplicated state variable: {varDecl.Name}"); ContractToStateVarsMap[contract].Add(varDecl); Debug.Assert(!StateVarToContractMap.ContainsKey(varDecl), $"Duplicated state variable: {varDecl.Name}"); StateVarToContractMap[varDecl] = contract; } public void AddMappingtoContract(ContractDefinition contract, VariableDeclaration mappingDecl) { Debug.Assert(mappingDecl.TypeName is Mapping, $"{mappingDecl.Name} is not a mapping"); if (!ContractToMappingsMap.ContainsKey(contract)) { ContractToMappingsMap[contract] = new HashSet<VariableDeclaration>(); } Debug.Assert(!ContractToMappingsMap[contract].Contains(mappingDecl), $"Duplicated state mapping: {mappingDecl.Name}"); ContractToMappingsMap[contract].Add(mappingDecl); } public void AddArrayToContract(ContractDefinition contract, VariableDeclaration arrayDecl) { Debug.Assert(arrayDecl.TypeName is ArrayTypeName, $"{arrayDecl.Name} is not an array"); if (!ContractToArraysMap.ContainsKey(contract)) { ContractToArraysMap[contract] = new HashSet<VariableDeclaration>(); } Debug.Assert(!ContractToArraysMap[contract].Contains(arrayDecl), $"Duplicated state array: {arrayDecl.Name}"); ContractToArraysMap[contract].Add(arrayDecl); } public bool HasStateVarInContract(ContractDefinition contract, VariableDeclaration varDecl) { if (!ContractToStateVarsMap.ContainsKey(contract)) { return false; } return ContractToStateVarsMap[contract].Contains(varDecl); } public HashSet<VariableDeclaration> GetStateVarsByContract(ContractDefinition contract) { return ContractToStateVarsMap.ContainsKey(contract) ? ContractToStateVarsMap[contract] : new HashSet<VariableDeclaration>(); } public void AddConstructorToContract(ContractDefinition contract, FunctionDefinition ctor) { Debug.Assert(ctor.IsConstructorForContract(contract.Name), $"{ctor.Name} is not a constructor"); Debug.Assert(!ContractToConstructorMap.ContainsKey(contract), $"Multiple constructors are defined"); ContractToConstructorMap[contract] = ctor; } public bool IsConstructorDefined(ContractDefinition contract) { return ContractToConstructorMap.ContainsKey(contract); } public FunctionDefinition GetConstructorByContract(ContractDefinition contract) { if (ContractToConstructorMap.ContainsKey(contract)) { return ContractToConstructorMap[contract]; } throw new System.Exception($"Contract {contract.Name} does not have any constructors"); } public void AddEventToContract(ContractDefinition contract, EventDefinition eventDef) { if (!ContractToEventsMap.ContainsKey(contract)) { ContractToEventsMap[contract] = new HashSet<EventDefinition>(); } Debug.Assert(!ContractToEventsMap[contract].Contains(eventDef), $"Duplicated event definition: {eventDef.Name} in {contract.Name}"); ContractToEventsMap[contract].Add(eventDef); } public bool HasEventNameInContract(ContractDefinition contract, string eventName) { if (!ContractToEventsMap.ContainsKey(contract)) { return false; } foreach (EventDefinition eventDef in ContractToEventsMap[contract]) { if (eventName.Equals(eventDef.Name)) { return true; } } return false; } public void AddFunctionToContract(ContractDefinition contract, FunctionDefinition funcDef) { if (!ContractToFunctionsMap.ContainsKey(contract)) { Debug.Assert(!ContractToFuncSigsMap.ContainsKey(contract)); ContractToFunctionsMap[contract] = new HashSet<FunctionDefinition>(); ContractToFuncSigsMap[contract] = new HashSet<string>(); } Debug.Assert(!ContractToFunctionsMap[contract].Contains(funcDef), $"Duplicated function definition: {funcDef.Name}"); ContractToFunctionsMap[contract].Add(funcDef); string signature = TransUtils.ComputeFunctionSignature(funcDef); Debug.Assert(!ContractToFuncSigsMap[contract].Contains(signature), $"Duplicated function signature: {signature}"); ContractToFuncSigsMap[contract].Add(signature); Debug.Assert(!FunctionToContractMap.ContainsKey(funcDef), $"Duplicated function: {funcDef.Name}"); FunctionToContractMap[funcDef] = contract; } public bool HasFuncSigInContract(ContractDefinition contract, string signature) { return ContractToFuncSigsMap.ContainsKey(contract); } public FunctionDefinition GetFunctionBySignature(ContractDefinition contract, string signature) { foreach (FunctionDefinition funcDef in ContractToFunctionsMap[contract]) { if (TransUtils.ComputeFunctionSignature(funcDef).Equals(signature)) { return funcDef; } } Debug.Assert(false, $"Cannot find function signature: {signature}"); return null; } public ContractDefinition GetContractByFunction(FunctionDefinition funcDef) { Debug.Assert(FunctionToContractMap.ContainsKey(funcDef)); return FunctionToContractMap[funcDef]; } public bool HasFuncSigInDynamicType(string funcSig, ContractDefinition dynamicType) { if (FuncSigResolutionMap.ContainsKey(funcSig) && FuncSigResolutionMap[funcSig].ContainsKey(dynamicType)) { return true; } return false; } public void AddFunctionToDynamicType(string funcSig, ContractDefinition dynamicType, FunctionDefinition funcDef) { if (!FuncSigResolutionMap.ContainsKey(funcSig)) { FuncSigResolutionMap[funcSig] = new Dictionary<ContractDefinition, FunctionDefinition>(); } // may potentially override the previous value due to inheritance FuncSigResolutionMap[funcSig][dynamicType] = funcDef; } public bool HasFuncSignature(string funcSig) { return FuncSigResolutionMap.ContainsKey(funcSig); } public Dictionary<ContractDefinition, FunctionDefinition> GetAllFuncDefinitions(string funcSig) { return FuncSigResolutionMap[funcSig]; } public FunctionDefinition GetFunctionByDynamicType(string funcSig, ContractDefinition dynamicType) { return FuncSigResolutionMap[funcSig][dynamicType]; } public void AddStateVarToDynamicType(string varName, ContractDefinition dynamicType, VariableDeclaration varDecl) { Debug.Assert(varDecl.StateVariable); if (!StateVarNameResolutionMap.ContainsKey(varName)) { StateVarNameResolutionMap[varName] = new Dictionary<ContractDefinition, VariableDeclaration>(); } // may potentially override the previous value due to inheritance StateVarNameResolutionMap[varName][dynamicType] = varDecl; } public void AddVisibleFunctionToContract(FunctionDefinition funcDef, ContractDefinition contract) { if (!ContractToVisibleFunctionsMap.ContainsKey(contract)) { ContractToVisibleFunctionsMap[contract] = new HashSet<FunctionDefinition>(); } ContractToVisibleFunctionsMap[contract].Add(funcDef); } public HashSet<FunctionDefinition> GetVisibleFunctionsByContract(ContractDefinition contract) { return ContractToVisibleFunctionsMap.ContainsKey(contract) ? ContractToVisibleFunctionsMap[contract] : new HashSet<FunctionDefinition>(); } public ContractDefinition GetContractByStateVarDecl(VariableDeclaration varDecl) { Debug.Assert(varDecl.StateVariable, $"{varDecl.Name} is not a state variable"); return StateVarToContractMap[varDecl]; } public bool HasStateVarName(string varName) { return StateVarNameResolutionMap.ContainsKey(varName); } public VariableDeclaration GetStateVarByDynamicType(string varName, ContractDefinition dynamicType) { return StateVarNameResolutionMap[varName][dynamicType]; } public void AddVisibleStateVarToContract(VariableDeclaration varDecl, ContractDefinition contract) { if (!ContractToVisibleStateVarsMap.ContainsKey(contract)) { ContractToVisibleStateVarsMap[contract] = new HashSet<VariableDeclaration>(); } ContractToVisibleStateVarsMap[contract].Add(varDecl); } public HashSet<VariableDeclaration> GetVisibleStateVarsByContract(ContractDefinition contract) { return ContractToVisibleStateVarsMap.ContainsKey(contract) ? ContractToVisibleStateVarsMap[contract] : new HashSet<VariableDeclaration>(); } public BoogieTypedIdent MakeFreshTypedIdent(BoogieType type) { int index = ++freshIdentifierCount; string name = "__var_" + index; return new BoogieTypedIdent(name, type); } public void AddModiferToPreProc(string modifier, BoogieProcedure procedure) { if (ModifierToBoogiePreProc.ContainsKey(modifier)) { throw new SystemException("duplicated modifier"); } else { ModifierToBoogiePreProc[modifier] = procedure; } } public void AddModiferToPostProc(string modifier, BoogieProcedure procedure) { if (ModifierToBoogiePostProc.ContainsKey(modifier)) { throw new SystemException("duplicated modifier"); } else { ModifierToBoogiePostProc[modifier] = procedure; } } public void AddModiferToPreImpl(string modifier, BoogieImplementation procedure) { if (ModifierToBoogiePreImpl.ContainsKey(modifier)) { throw new SystemException("duplicated modifier"); } else { ModifierToBoogiePreImpl[modifier] = procedure; } } public void AddModiferToPostImpl(string modifier, BoogieImplementation procedure) { if (ModifierToBoogiePostImpl.ContainsKey(modifier)) { throw new SystemException("duplicated modifier"); } else { ModifierToBoogiePostImpl[modifier] = procedure; } } public bool IsMethodInIgnoredSet(FunctionDefinition func, ContractDefinition contract) { return IgnoreMethods.Any(x => x.Item2.Equals(contract.Name) && (x.Item1.Equals("*") || x.Item1.Equals(func.Name))) ; } } }
43.782101
144
0.655883
[ "MIT" ]
XinxingLiu/verisol
Sources/SolToBoogie/TranslatorContext.cs
22,506
C#
using Newtonsoft.Json; using System.IO; namespace Lava.Net { /// <summary> /// Configuration class for Lava.Net. Reads values from config.json when initialized. /// </summary> public sealed class LavaConfig { static LavaConfig() { JsonConvert.DeserializeObject<LavaConfig>(File.ReadAllText("config.json")); } [JsonProperty("server")] public static readonly ServerConfig Server; public struct ServerConfig { public string Uri => $"{Server.Address}:{Server.Port}"; [JsonProperty("address")] public readonly string Address; [JsonProperty("port")] public readonly ushort Port; [JsonProperty("password")] public readonly string Authorization; } [JsonProperty("sources")] public static readonly SourcesConfig Sources; public struct SourcesConfig { [JsonProperty("youtube")] public readonly bool Youtube; [JsonProperty("bandcamp")] public readonly bool Bandcamp; [JsonProperty("soundcloud")] public readonly bool Soundcloud; [JsonProperty("twitch")] public readonly bool Twitch; [JsonProperty("vimeo")] public readonly bool Vimeo; [JsonProperty("mixer")] public readonly bool Mixer; [JsonProperty("http")] public readonly bool Http; [JsonProperty("local")] public readonly bool Local; } } }
25.5
89
0.561887
[ "MIT" ]
WorkingRobot/Lava.Net
LavaConfig.cs
1,634
C#
using Microsoft.EntityFrameworkCore; using ParkyAPI.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ParkyAPI.Data { public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<NationalPark> NationalParks { get; set; } } }
21.7
99
0.725806
[ "MIT" ]
nhatvu148/Parky
ParkyAPI/Data/ApplicationDbContext.cs
436
C#
using System; using System.Collections.Generic; using System.Text; namespace DotNetCore_BeehooeServer.Model { public class ResponseBase { /// <summary> /// 状态 (0失败 1 成功) /// </summary> public string Status { set; get; } /// <summary> /// 提示信息 /// </summary> public string Message { set; get; } /// <summary> /// 返回数据 /// </summary> public Object Response { set; get; } public ResponseBase(string status, string message=null, Object response=null) { Status = status; Message = message; Response = response; } } }
21.40625
85
0.519708
[ "Apache-2.0" ]
shunchuan/DotNetCore_BeehooeServer
DotNetCore_BeehooeServer.Model/ResponseBase.cs
719
C#
using System; using System.IO; using System.Linq; using System.Threading.Tasks; using IndicoV2; using IndicoV2.StrawberryShake; namespace Examples.AddDataSetFiles { public class Program { private static async Task Main() { Console.WriteLine("Adding files to the DataSet."); var token = File.ReadAllText(Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "indico_api_token.txt")); var client = new IndicoClient(token); var dataSetsClient = client.DataSets(); var dataSetAwaiter = client.DataSetAwaiter(); var dataSets = await dataSetsClient.ListFullAsync(1); var dataSetId = dataSets.Single().Id; await dataSetsClient.AddFilesAsync(dataSetId, new[] {"workflow-sample.pdf"}, default); await dataSetAwaiter.WaitFilesDownloadedOrFailedAsync(dataSetId, TimeSpan.FromSeconds(0.5), default); var statusesResult = await dataSetsClient.FileUploadStatusAsync(dataSetId, default); var downloadedFileIds = statusesResult.Dataset.Files .Where(f => f.Status == FileStatus.Downloaded) .Select(f => f.Id.Value); await dataSetsClient.ProcessFileAsync(dataSetId, downloadedFileIds, default); await dataSetAwaiter.WaitFilesProcessedOrFailedAsync(dataSetId, TimeSpan.FromSeconds(0.5), default); Console.WriteLine("Adding files to the DataSet - finished."); } } }
40.25641
113
0.653503
[ "MIT" ]
IndicoDataSolutions/indico-client-csharp
Examples/Examples.AddDataSetFiles/Program.cs
1,572
C#
using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using Dg.fifth.Authorization; using Dg.fifth.Authorization.Roles; using Dg.fifth.Authorization.Users; using Dg.fifth.Editions; using Dg.fifth.MultiTenancy; namespace Dg.fifth.Identity { public static class IdentityRegistrar { public static IdentityBuilder Register(IServiceCollection services) { services.AddLogging(); return services.AddAbpIdentity<Tenant, User, Role>() .AddAbpTenantManager<TenantManager>() .AddAbpUserManager<UserManager>() .AddAbpRoleManager<RoleManager>() .AddAbpEditionManager<EditionManager>() .AddAbpUserStore<UserStore>() .AddAbpRoleStore<RoleStore>() .AddAbpLogInManager<LogInManager>() .AddAbpSignInManager<SignInManager>() .AddAbpSecurityStampValidator<SecurityStampValidator>() .AddAbpUserClaimsPrincipalFactory<UserClaimsPrincipalFactory>() .AddPermissionChecker<PermissionChecker>() .AddDefaultTokenProviders(); } } }
36.060606
79
0.658824
[ "MIT" ]
PowerDG/Dg.KMS.Web
Dg.fifth/4.8.0/aspnet-core/src/Dg.fifth.Core/Identity/IdentityRegistrar.cs
1,192
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using Whatfits.DataAccess.DTOs; using Whatfits.DataAccess.DTOs.ContentDTOs; using Whatfits.DataAccess.DTOs.CoreDTOs; using Whatfits.Models.Context.Content; using Whatfits.Models.Context.Core; using Whatfits.Models.Models; namespace Whatfits.DataAccess.Gateways.ContentGateways { public class FollowsGateway { private FollowsContext fdb = new FollowsContext(); private AccountContext adb = new AccountContext(); public bool DoesUserNameExists(Credential obj) { // Find username inside database based on obj.UserName var foundUserName = (from credentials in fdb.Crendtials where credentials.UserName == obj.UserName select credentials.UserName).FirstOrDefault(); // Checking if it found a user if (foundUserName == null) // returns false if passed username does not exists in database return false; else // returns true if passed username does exists in database return true; } public IEnumerable<FollowsDTO> GetFollowers(string userName) { // get userID based on userName var requestedUsername = userName; var requiredID = 0; var foundCredential = (from u in adb.Credentials where u.UserName == requestedUsername select u).FirstOrDefault(); ResponseDTO<LoginDTO> response = new ResponseDTO<LoginDTO>(); if (foundCredential != null) { // Found user in database, creating LoginDTO to send // credential infromation response.Data = new LoginDTO { UserID = foundCredential.UserID, }; requiredID = foundCredential.UserID; response.IsSuccessful = true; } return (from c in fdb.Crendtials join b in (from d in fdb.Following where d.UserID == requiredID select new {d.PersonFollowing }) on c.UserID equals b.PersonFollowing select new FollowsDTO { PersonFollowing = c.UserID, UserName = c.UserName }).ToList(); } public bool AddtoFollow(string userName, string follouserName) { // Get Requested User ID var requestedUsername = userName; var requiredID = 0; var foundCredential = (from u in adb.Credentials where u.UserName == requestedUsername select u).FirstOrDefault(); ResponseDTO<LoginDTO> response = new ResponseDTO<LoginDTO>(); if (foundCredential != null) { // Found user in database, creating LoginDTO to send // credential infromation response.Data = new LoginDTO { UserID = foundCredential.UserID, }; requiredID = foundCredential.UserID; response.IsSuccessful = true; } // Get Want to Follow User ID var wantedfolloname = follouserName; var wantedfolloID = 0; var foundFollo = (from u in adb.Credentials where u.UserName == wantedfolloname select u).FirstOrDefault(); ResponseDTO<LoginDTO> responseFollo = new ResponseDTO<LoginDTO>(); if (foundFollo != null) { // Found user in database, creating LoginDTO to send // credential infromation responseFollo.Data = new LoginDTO { UserID = foundFollo.UserID, }; wantedfolloID = foundFollo.UserID; responseFollo.IsSuccessful = true; } // Add wanted follow userid into requested user following list using (var dbTransaction = fdb.Database.BeginTransaction()) { try { var folo = (from c in fdb.Following where c.UserID == requiredID select c).FirstOrDefault(); // if required user not in the following table if (folo == null) { Following newfolo = new Following() { UserID = requiredID, PersonFollowing = wantedfolloID }; fdb.Following.Add(newfolo); fdb.SaveChanges(); dbTransaction.Commit(); return true; } else // if required user already in the following table { folo.PersonFollowing = wantedfolloID; fdb.Following.Add(folo); fdb.SaveChanges(); dbTransaction.Commit(); return true; } } catch (Exception) { dbTransaction.Rollback(); return false; } } } public bool DeletefromFollow(string userName, string follouserName) { // Get Requested User ID var requestedUsername = userName; var requiredID = 0; var foundCredential = (from u in adb.Credentials where u.UserName == requestedUsername select u).FirstOrDefault(); ResponseDTO<LoginDTO> response = new ResponseDTO<LoginDTO>(); if (foundCredential != null) { // Found user in database, creating LoginDTO to send // credential infromation response.Data = new LoginDTO { UserID = foundCredential.UserID, }; requiredID = foundCredential.UserID; response.IsSuccessful = true; } // Get Want to UnFollow User ID var wantedfolloname = follouserName; var wantedfolloID = 0; var foundFollo = (from u in adb.Credentials where u.UserName == wantedfolloname select u).FirstOrDefault(); ResponseDTO<LoginDTO> responseFollo = new ResponseDTO<LoginDTO>(); if (foundFollo != null) { // Found user in database, creating LoginDTO to send // credential infromation responseFollo.Data = new LoginDTO { UserID = foundFollo.UserID, }; wantedfolloID = foundFollo.UserID; responseFollo.IsSuccessful = true; } // Delete wanted follow userid from requested user following list using (var dbTransaction = fdb.Database.BeginTransaction()) { try { var newFolo = (from c in fdb.Following where (c.UserID == requiredID && c.PersonFollowing == wantedfolloID) select c).FirstOrDefault(); Following folo = new Following(); fdb.Following.Remove(newFolo); fdb.SaveChanges(); dbTransaction.Commit(); return true; } catch (Exception) { dbTransaction.Rollback(); return false; } } } public bool IsFollow(string userName, string follouserName) { // Get Requested User ID var requestedUsername = userName; var requiredID = 0; var foundCredential = (from u in adb.Credentials where u.UserName == requestedUsername select u).FirstOrDefault(); ResponseDTO<LoginDTO> response = new ResponseDTO<LoginDTO>(); if (foundCredential != null) { // Found user in database, creating LoginDTO to send // credential infromation response.Data = new LoginDTO { UserID = foundCredential.UserID, }; requiredID = foundCredential.UserID; response.IsSuccessful = true; } // Get Want to UnFollow User ID var wantedfolloname = follouserName; var wantedfolloID = 0; var foundFollo = (from u in adb.Credentials where u.UserName == wantedfolloname select u).FirstOrDefault(); ResponseDTO<LoginDTO> responseFollo = new ResponseDTO<LoginDTO>(); if (foundFollo != null) { // Found user in database, creating LoginDTO to send // credential infromation responseFollo.Data = new LoginDTO { UserID = foundFollo.UserID, }; wantedfolloID = foundFollo.UserID; responseFollo.IsSuccessful = true; } // check if userid is in requested user's following list using (var dbTransaction = fdb.Database.BeginTransaction()) { try { bool IfFolo = (from c in fdb.Following where (c.UserID == requiredID && c.PersonFollowing == wantedfolloID) select c).Any(); return IfFolo; } catch (Exception) { dbTransaction.Rollback(); return false; } } } } }
40.244361
104
0.478842
[ "MIT" ]
apham42/WhatFits
server/Whatfits.Gateways/Gateways/ContentGateways/FollowsGateway.cs
10,707
C#
// <auto-generated /> using System; using Cican_Micro.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Cican_Micro.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.4-rtm-31024") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Cican_Micro.Models.Produits", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Categorie"); b.Property<string>("ImageUrl"); b.Property<string>("Modele"); b.Property<string>("Nom"); b.Property<decimal>("Prix"); b.HasKey("ID"); b.ToTable("Produits"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
34.579365
125
0.485311
[ "MIT" ]
maximefalardeau/Cican_Micro
Cican_Micro/Data/Migrations/ApplicationDbContextModelSnapshot.cs
8,716
C#
using System; using FluentNHibernate.Mapping; using QS.Test.TestApp.Domain; namespace QS.Test.TestApp.HibernateMapping { public class Document2Map : ClassMap<Document2> { public Document2Map() { Id(x => x.Id); Map(x => x.Date); } } }
14.823529
48
0.690476
[ "Apache-2.0" ]
Art8m/QSProjects
QS.LibsTest/TestApp/HibernateMapping/Document2Map.cs
254
C#
namespace PublicProfile.UserRegistration.Storage { using Microsoft.AspNet.Identity; using System.Threading.Tasks; public class UserStore : IUserStore<User> { private readonly IUserDataStorage userDataStorage; public UserStore(IUserDataStorage storage) { this.userDataStorage = storage; } public async Task CreateAsync(User user) { await this.userDataStorage.Store(user); } public async Task DeleteAsync(User user) { await userDataStorage.Delete(user.Id); } public void Dispose() { } public async Task<User> FindByIdAsync(string userId) { var storedUser = await userDataStorage.GetUserById(userId); return new User(storedUser); } public async Task<User> FindByNameAsync(string userName) { return await this.FindByIdAsync(userName); } public async Task UpdateAsync(User user) { await userDataStorage.Store(user); } } }
24.772727
71
0.601835
[ "MIT" ]
enata/PublicProfile
PublicProfile.UserRegistration.Storage/UserStore.cs
1,092
C#
using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; using System.Net; namespace xperdex.classes.UpdateService { static public class EventListener { static List<EventWatcher> watchers = new List<EventWatcher>(); public class EventWatcher { public delegate void OnEvent(); internal String name; internal OnEvent event_handler; internal EventWatcher( String event_name, OnEvent handler ) { name = event_name; event_handler = handler; EventListener.watchers.Add( this ); } } static UdpClient socket; static void Recieve( IAsyncResult packet ) { IPEndPoint remote = null; byte[] data = socket.EndReceive( packet, ref remote ); ASCIIEncoding ae = new ASCIIEncoding(); String test = ae.GetString( data ); foreach( EventWatcher watcher in watchers ) { if( watcher.name == test ) { watcher.event_handler(); } } socket.BeginReceive( Recieve, null ); } static EventListener() { socket = new UdpClient(); socket.ExclusiveAddressUse = false; socket.EnableBroadcast = true; try { socket.Client.Bind( new IPEndPoint( 0, 3090 ) ); socket.BeginReceive( Recieve, null ); } catch { } } public static void ListenFor( String name, EventWatcher.OnEvent handler ) { EventWatcher w = new EventWatcher( name, handler ); } } }
21.731343
76
0.650412
[ "MIT" ]
d3x0r/xperdex
xperdex.peer_events/UpdateService/EventListener.cs
1,456
C#
using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Numerics; using System.Text; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Training20201015.Algorithms; using Training20201015.Collections; using Training20201015.Numerics; using Training20201015.Questions; namespace Training20201015.Questions { public class QuestionD : AtCoderQuestionBase { [MethodImpl(MethodImplOptions.AggressiveOptimization)] public override void Solve(IOManager io) { throw new NotImplementedException(); } } }
24.962963
62
0.768546
[ "MIT" ]
terry-u16/AtCoder
Training20201015/Training20201015/Training20201015/Questions/QuestionD.cs
676
C#
using Groundbeef.Events; using System.Collections.Generic; using System.Globalization; using System.Threading; namespace Groundbeef.Localisation { [System.Runtime.InteropServices.ComVisible(true)] public static class ResourceManagerService { private static readonly Dictionary<string, System.Resources.ResourceManager> s_managers; public static event ValueChangedEventHandler<Locale?>? LocaleChanged; /// <summary> /// Current application locale /// </summary> public static Locale? CurrentLocale { get; private set; } /// <summary> /// Initializes a new instance of the ResourceManager class. /// </summary> static ResourceManagerService() { s_managers = new Dictionary<string, System.Resources.ResourceManager>(); // Set to default culture ChangeLocale(CultureInfo.CurrentCulture.IetfLanguageTag); } /// <summary> /// Retreives a string resource with the given key from the given /// resource manager. /// Will load the string relevant to the current culture. /// </summary> /// <param name="managerName">Name of the ResourceManager</param> /// <param name="resourceKey">Resource to lookup</param> public static string? GetResourceString(in string managerName, in string resourceKey) { string? resource = null!; if (s_managers.TryGetValue(managerName, out var manager)) resource = manager.GetString(resourceKey); return resource; } /// <summary> /// Changes the current locale /// </summary> /// <param name="newLocaleName">IETF locale name (e.g. en-US, en-GB)</param> public static void ChangeLocale(in string newLocaleName) { CultureInfo newCultureInfo = new CultureInfo(newLocaleName); Thread.CurrentThread.CurrentCulture = newCultureInfo; Thread.CurrentThread.CurrentUICulture = newCultureInfo; Locale newLocale = new Locale() { Name = newLocaleName, RTL = newCultureInfo.TextInfo.IsRightToLeft }; Locale? oldLocale = CurrentLocale?.Clone(); CurrentLocale = newLocale; LocaleChanged?.Invoke(null, new ValueChangedEventArgs<Locale?>(oldLocale, newLocale)); } /// <summary> /// Fires the LocaleChange event to reload bindings /// </summary> public static void Refresh() { ChangeLocale(CultureInfo.CurrentCulture.IetfLanguageTag); } /// <summary> /// Register a ResourceManager, does not fire a refresh /// </summary> /// <param name="managerName">Name to store the manager under, used with GetResourceString/UnregisterManager</param> /// <param name="manager">ResourceManager to store</param> public static void RegisterManager(in string managerName, in System.Resources.ResourceManager manager) { RegisterManager(managerName, manager, false); } /// <summary> /// Register a ResourceManager /// </summary> /// <param name="managerName">Name to store the manager under, used with GetResourceString/UnregisterManager</param> /// <param name="manager">ResourceManager to store</param> /// <param name="refresh">Whether to fire the LocaleChanged event to refresh bindings</param> public static void RegisterManager(in string managerName, in System.Resources.ResourceManager manager, bool refresh) { if (!s_managers.TryGetValue(managerName, out _)) s_managers.Add(managerName, manager); if (refresh) Refresh(); } /// <summary> /// Remove a ResourceManager /// </summary> /// <param name="name">Name of the manager to remove</param> public static void UnregisterManager(in string name) { if (!s_managers.TryGetValue(name, out _)) s_managers.Remove(name); } } }
39.371429
124
0.626754
[ "MIT" ]
ProphetLamb-Organistion/Groundbeef
src/Localisation/ResourceManagerService.cs
4,136
C#
/* * @author : Blake Pell * @website : http://www.blakepell.com * @initial date : 2021-02-09 * @last updated : 2021-02-09 * @copyright : Copyright (c) 2003-2021, All rights reserved. * @license : MIT */ using System.IO; using System.Text; using Argus.Extensions; using Xunit; namespace Argus.UnitTests { public class StreamTests { [Fact] public void ToText() { var ms = new MemoryStream(); using (var sw = new StreamWriter(ms)) { sw.Write("This is a test"); sw.Flush(); Assert.Equal("This is a test", ms.ToText()); } } [Fact] public void ToBase64FromMemoryStream() { var ms = new MemoryStream(); using (var sw = new StreamWriter(ms)) { sw.Write("This is a test"); sw.Flush(); Assert.Equal("VGhpcyBpcyBhIHRlc3Q=", ms.ToBase64()); } ms.Dispose(); } [Fact] public void ToBase64FromStream() { Stream s = new MemoryStream(); using (var sw = new StreamWriter(s)) { sw.Write("This is a test"); sw.Flush(); Assert.Equal("VGhpcyBpcyBhIHRlc3Q=", s.ToBase64()); } s.Dispose(); } } }
21.691176
69
0.453559
[ "MIT" ]
blakepell/ArgusFramework
tests/Argus.UnitTests/Extensions/StreamTests.cs
1,477
C#
// SPDX-License-Identifier: Apache-2.0 // Licensed to the Ed-Fi Alliance under one or more agreements. // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. using System; using System.ComponentModel.DataAnnotations; using EdFi.Ods.Api.Validation; namespace EdFi.Ods.Api.Attributes { [AttributeUsage(AttributeTargets.Property)] public sealed class NoDangerousTextAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { string s = value as string; if (string.IsNullOrEmpty(s)) { return ValidationResult.Success; } return CrossSiteScriptingValidation.IsDangerousString(s, out int matchIndex) ? new ValidationResult($"{validationContext.DisplayName} contains a potentially dangerous value.") : ValidationResult.Success; } } }
35.4
114
0.693974
[ "Apache-2.0" ]
AxelMarquez/Ed-Fi-ODS
Application/EdFi.Ods.Api/Attributes/NoDangerousTextAttribute.cs
1,064
C#
// This source code is dual-licensed under the Apache License, version // 2.0, and the Mozilla Public License, version 1.1. // // The APL v2.0: // //--------------------------------------------------------------------------- // Copyright (C) 2007-2014 GoPivotal, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //--------------------------------------------------------------------------- // // The MPL v1.1: // //--------------------------------------------------------------------------- // The contents of this file are subject to the Mozilla Public License // Version 1.1 (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.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See // the License for the specific language governing rights and // limitations under the License. // // The Original Code is RabbitMQ. // // The Initial Developer of the Original Code is GoPivotal, Inc. // Copyright (c) 2007-2014 GoPivotal, Inc. All rights reserved. //--------------------------------------------------------------------------- using System; namespace RabbitMQ.Client.Events { ///<summary>Delegate used to process connection unblocked events.</summary> public delegate void ConnectionUnblockedEventHandler(IConnection sender); }
39.6
79
0.610101
[ "MIT" ]
CymaticLabs/Unity3D.Amqp
lib/rabbitmq-dotnet-client-rabbitmq_v3_4_4/projects/client/RabbitMQ.Client/src/client/events/ConnectionUnblockedEventHandler.cs
1,980
C#
using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MonoEngine.core { public class JanitorAgent : AIAgent { public JanitorAgent(Vector2 position, float health) : base(position, health) { CurHealth = health; MaxHealth = health; WorldState.Add("seeLitter", true); WorldState.Add("seeFullBin", true); WorldState.Add("idle", true); Goals.Add(new AIGoalPickupLitter(this)); Goals.Add(new AIGoalIdle(this)); Actions.Add(new AIActionPickupLitter(this)); Actions.Add(new AIActionRandomWander(this)); } public override void UpdateWorldState(float dt) { WorldState["seeLitter"] = false; foreach(var l in Game1.Litter) { if(Vector2.Distance(Position, ((GameObject)l).CurrentTile.Position) < 10000) { WorldState["seeLitter"] = true; } } } } }
24.489796
93
0.536667
[ "MIT" ]
JoelWhittle/MonoGOAP
core/JanitorAgent.cs
1,202
C#
using UnityEngine; namespace Barebones.Logging { public class LogAppenders { public delegate string LogFormatter(Logger logger, LogLevel level, object message); public static void UnityConsoleAppender(Logger logger, LogLevel logLevel, object message) { if (logLevel <= LogLevel.Info) { Debug.Log(string.Format("[{0}] {1}", logLevel, message)); } else if (logLevel <= LogLevel.Warn) { Debug.LogWarning(string.Format("[{0}] {1}", logLevel, message)); } else if (logLevel <= LogLevel.Fatal) { Debug.LogError(string.Format("[{0}] {1}", logLevel, message)); } } public static void UnityConsoleAppenderWithNames(Logger logger, LogLevel logLevel, object message) { if (logLevel <= LogLevel.Info) { Debug.Log(string.Format("[{0} | {1}] {2}", logLevel, logger.Name, message)); } else if (logLevel <= LogLevel.Warn) { Debug.LogWarning(string.Format("[{0} | {1}] {2}", logLevel, logger.Name, message)); } else if (logLevel <= LogLevel.Fatal) { Debug.LogError(string.Format("[{0} | {1}] {2}", logLevel, logger.Name, message)); } } } }
34.292683
106
0.516358
[ "MIT" ]
aevien/master-server-framework
Assets/Barebones/Tools/Logger/LogAppenders.cs
1,408
C#
/* Project Orleans Cloud Service SDK ver. 1.0 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. */ using System; using System.Threading.Tasks; using Orleans;  namespace UnitTests.GrainInterfaces { public interface ISampleStreaming_ProducerGrain : IGrainWithGuidKey { Task BecomeProducer(Guid streamId, string streamNamespace, string providerToUse); Task StartPeriodicProducing(); Task StopPeriodicProducing(); Task<int> GetNumberProduced(); Task ClearNumberProduced(); Task Produce(); } public interface ISampleStreaming_ConsumerGrain : IGrainWithGuidKey { Task BecomeConsumer(Guid streamId, string streamNamespace, string providerToUse); Task StopConsuming(); Task<int> GetNumberConsumed(); } public interface ISampleStreaming_InlineConsumerGrain : ISampleStreaming_ConsumerGrain { } }
34.333333
126
0.762902
[ "MIT" ]
rikace/orleans
src/TestGrainInterfaces/ISampleStreamingGrain.cs
1,959
C#
// // MonoLinkerSupport.cs // // Author: // Martin Baulig <mabaul@microsoft.com> // // Copyright (c) 2019 Microsoft Corporation // // 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 System.Runtime.CompilerServices { #if !INSIDE_CORLIB public #endif static class MonoLinkerSupport { [MethodImpl(MethodImplOptions.NoInlining)] public static bool IsWeakInstanceOf<T> (object obj) => obj is T; [MethodImpl(MethodImplOptions.NoInlining)] public static bool IsTypeAvailable<T> () => true; // This should only be used in tests. [MethodImpl(MethodImplOptions.NoInlining)] public static bool IsTypeAvailable (string type) => true; [MethodImpl(MethodImplOptions.NoInlining)] public static bool AsWeakInstanceOf<T> (object obj, out T instance) where T : class { instance = obj as T; return instance != null; } [MethodImpl(MethodImplOptions.NoInlining)] public static bool IsFeatureSupported (MonoLinkerFeature feature) => true; [MethodImpl(MethodImplOptions.NoInlining)] public static void RequireFeature (MonoLinkerFeature feature) { } } }
36.448276
85
0.755913
[ "MIT" ]
xamarin/linker-optimizer
Mono.Linker.Optimizer/System.Runtime.CompilerServices/MonoLinkerSupport.cs
2,114
C#
namespace ACUnicep.Domain.Entities { public enum NivelAcesso { Aluno = 1, Professor = 2 } }
13.444444
35
0.561983
[ "MIT" ]
DaniloAlv/ACUnicep_WebAPI
ACUnicep.Domain/Entities/NivelAcesso.cs
123
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.Extensions.Logging; namespace OElite.Restme.Dapper { public enum RestmeDbQueryType { Select = 0, Insert = 10, Update = 20, Delete = 30 } public interface IRestmeDbQuery<T> { RestmeDb DbCentre { get; set; } string DefaultOrderByClauseInQuery { get; } string CustomSelectTableSource { get; } string CustomUpdateTableSource { get; } string CustomDeleteTableSource { get; } string CustomInsertTableSource { get; } string DefaultTableSource { get; } Dictionary<string, string> MapSelectColumns<A>(string[] chosenColumnsOnly = null, string[] columnsToExclude = null) where A : IRestmeDbEntity; Dictionary<string, string> MapUpdateColumns<A>(string[] chosenColumnsOnly = null, string[] columnsToExclude = null) where A : IRestmeDbEntity; Dictionary<string, string> MapInsertColumns<A>(string[] chosenColumnsOnly = null, string[] columnsToExclude = null) where A : IRestmeDbEntity; Dictionary<string, string> MapDeleteColumns<A>(string[] chosenColumnsOnly = null, string[] columnsToExclude = null) where A : IRestmeDbEntity; Dictionary<string, object> PrepareParamValues<A>(RestmeDbQueryType queryType, A data, string[] chosenColumnsOnly = null, string[] columnsToExclude = null) where A : IRestmeDbEntity; } public class RestmeDbQuery<T> : IRestmeDbQuery<T> where T : IRestmeDbEntity { public RestmeDb DbCentre { get; set; } public virtual string DefaultOrderByClauseInQuery { get; private set; } public virtual string CustomSelectTableSource { get; private set; } public virtual string CustomUpdateTableSource { get; private set; } public virtual string CustomDeleteTableSource { get; private set; } public virtual string CustomInsertTableSource { get; private set; } public virtual string DefaultTableSource { get; private set; } private static Dictionary<string, Dictionary<string, RestmeDbColumnAttribute>> _defaultAttributesFromTypes = new Dictionary<string, Dictionary<string, RestmeDbColumnAttribute>>(); public RestmeDbQuery(RestmeDb dbCentre, string customSelectTableSource = null, string customInsertTableSource = null, string customUpdateTableSource = null, string customDeleteTableSource = null) { DbCentre = dbCentre; var tableAttribute = GetTableAttribute<T>(); DefaultTableSource = tableAttribute.DbTableName; CustomSelectTableSource = customSelectTableSource; CustomInsertTableSource = customInsertTableSource; CustomUpdateTableSource = customUpdateTableSource; CustomDeleteTableSource = customDeleteTableSource; DefaultOrderByClauseInQuery = tableAttribute.DefaultOrderByClauseInQuery; } public Dictionary<string, object> PrepareParamValues<A>(RestmeDbQueryType queryType, A data, string[] chosenColumnsOnly = null, string[] columnsToExclude = null) where A : IRestmeDbEntity { var paramValues = new Dictionary<string, object>(); List<KeyValuePair<string, string>> props; switch (queryType) { case RestmeDbQueryType.Update: props = MapUpdateColumns<T>(chosenColumnsOnly, columnsToExclude)?.ToList(); break; case RestmeDbQueryType.Delete: props = MapDeleteColumns<T>(chosenColumnsOnly, columnsToExclude)?.ToList(); break; case RestmeDbQueryType.Insert: props = MapInsertColumns<T>(chosenColumnsOnly, columnsToExclude)?.ToList(); break; default: //when executing select query, use type <A> so all properties will be used props = MapSelectColumns<A>(chosenColumnsOnly, columnsToExclude)?.ToList(); break; } if (props?.Count > 0) { if (chosenColumnsOnly?.Length > 0) props = props.Where(item => chosenColumnsOnly.Contains(item.Key)).ToList(); else if (columnsToExclude?.Length > 0) props = props.Where(item => !columnsToExclude.Contains(item.Key)).ToList(); foreach (var prop in props) { try { var objValue = data.GetPropertyValue(prop.Key); if (objValue != null && objValue is DateTime) { paramValues.Add(prop.Key, DateTimeUtils.IsValidSqlDateTimeValue(objValue) ? objValue : null); } else if (objValue != null && (objValue is int || objValue is long)) { if (IsForeignKey<T>(prop) && NumericUtils.GetLongIntegerValueFromObject(objValue) == 0) paramValues.Add(prop.Key, null); else paramValues.Add(prop.Key, objValue); } else if (objValue != null && objValue.GetType().GetTypeInfo().IsEnum) { paramValues.Add(prop.Key, (int)objValue); } else paramValues.Add(prop.Key, objValue); } catch (Exception ex) { RestmeDb.Logger?.LogError(ex.Message, ex); } } } return paramValues; } private bool IsForeignKey<A>(KeyValuePair<string, string> prop) where A : IRestmeDbEntity { var columnAttr = GetTypeColumnAttributes<A>().Where(item => item.Key == prop.Key).Select(c => c.Value) .FirstOrDefault(); return (columnAttr?.ColumnType == RestmeDbColumnType.ForeignKey); } public RestmeTableAttribute GetTableAttribute<A>() where A : IRestmeDbEntity { var attribute = typeof(A).GetTypeInfo().GetCustomAttribute(typeof(RestmeTableAttribute)); if (attribute == null) throw new ArgumentException($"{typeof(A)} does not contain valid QueryTableAttribute"); return (RestmeTableAttribute)attribute; } public Dictionary<string, RestmeDbColumnAttribute> GetTypeColumnAttributes<A>() where A : IRestmeDbEntity { var existingRepo = _defaultAttributesFromTypes.Where(item => item.Key == typeof(A).AssemblyQualifiedName) .Select(item => item.Value).FirstOrDefault(); if (existingRepo != null) return existingRepo; var dic = new Dictionary<string, RestmeDbColumnAttribute>(); var properties = typeof(A).GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public).Where(prop => prop.IsDefined(typeof(RestmeDbColumnAttribute), true)); var propertyInfos = properties as PropertyInfo[] ?? properties.ToArray(); if (!propertyInfos.Any()) return dic; foreach (var prop in propertyInfos) { var attribute = prop.GetCustomAttribute<RestmeDbColumnAttribute>(true); if (attribute != null && !dic.ContainsKey(attribute.DbColumnName)) { dic.Add(attribute.DbColumnName, attribute); } } var keyName = typeof(A).AssemblyQualifiedName; if (keyName.IsNotNullOrEmpty()) { lock (_defaultAttributesFromTypes) { try { if (_defaultAttributesFromTypes.ContainsKey(keyName)) { _defaultAttributesFromTypes[keyName] = dic; RestmeDb.Logger?.LogDebug( $"Adding column attribute repository for an existing identified type - which is unlikely to happen.\n Type: {keyName}"); } else _defaultAttributesFromTypes.Add(keyName, dic); } catch (Exception ex) { RestmeDb.Logger?.LogDebug( $"DEBUGGING POTENTIAL ERROR: Key Name: {keyName} DIC Count: {dic?.Count} defaultAttributeFromTypes: {_defaultAttributesFromTypes == null} -- {_defaultAttributesFromTypes?.Count}"); throw ex; } } } return dic; } private Dictionary<string, string> GenerateDefaultColumnsInQuery<A>( string[] chosenColumnsOnly = null, string[] columnsToExclude = null, bool? inSelect = null, bool? inInsert = null, bool? inUpdate = null, bool? inDelete = null) where A : IRestmeDbEntity { var defaultTypeAttributes = GetTypeColumnAttributes<A>(); var tableAttribute = GetTableAttribute<A>(); var columnAttributes = defaultTypeAttributes?.Where(dic => (inSelect == null || dic.Value.InSelect == inSelect) && (inInsert == null || dic.Value.InInsert == inInsert) && (inUpdate == null || dic.Value.InUpdate == inUpdate) && (inDelete == null || dic.Value.InDelete == inDelete) && (chosenColumnsOnly == null || chosenColumnsOnly.Contains(dic.Key)) && (columnsToExclude == null || !columnsToExclude.Contains(dic.Key)) && ( tableAttribute.ExcludedColumns == null || !tableAttribute.ExcludedColumns.Contains( dic.Key) ))?.ToDictionary(d => d.Key, d => d.Value.DbColumnName) ?? new Dictionary<string, string>(); if (chosenColumnsOnly == null || !chosenColumnsOnly.Any()) return columnAttributes; var unIdentifiedColumns = chosenColumnsOnly.Where(item => defaultTypeAttributes?.ContainsKey(item) != true); var identifiedColumns = unIdentifiedColumns as string[] ?? unIdentifiedColumns.ToArray(); if (!identifiedColumns.Any()) return columnAttributes; foreach (var col in identifiedColumns) { columnAttributes.Add(Guid.NewGuid().ToString(), col); } return columnAttributes; } public virtual Dictionary<string, string> MapSelectColumns<A>(string[] chosenColumnsOnly = null, string[] columnsToExclude = null) where A : IRestmeDbEntity => GenerateDefaultColumnsInQuery<A>(chosenColumnsOnly, columnsToExclude, inSelect: true); public virtual Dictionary<string, string> MapUpdateColumns<A>(string[] chosenColumnsOnly = null, string[] columnsToExclude = null) where A : IRestmeDbEntity => GenerateDefaultColumnsInQuery<A>(chosenColumnsOnly, columnsToExclude, inUpdate: true); public virtual Dictionary<string, string> MapInsertColumns<A>(string[] chosenColumnsOnly = null, string[] columnsToExclude = null) where A : IRestmeDbEntity => GenerateDefaultColumnsInQuery<A>(chosenColumnsOnly, columnsToExclude, inInsert: true); public virtual Dictionary<string, string> MapDeleteColumns<A>(string[] chosenColumnsOnly = null, string[] columnsToExclude = null) where A : IRestmeDbEntity => GenerateDefaultColumnsInQuery<A>(chosenColumnsOnly, columnsToExclude, inDelete: true); } }
47.144444
215
0.555032
[ "MIT" ]
oelite/RESTme.Dapper
OElite.Restme.Dapper/RestmeDbQuery.cs
12,731
C#
using System; using System.Collections.Generic; using System.Text; namespace SortingAlgorithms { public interface ISort<T> where T : IComparable { void Sort(T[] array, Comparison<T> comparable); void Sort(T[] array); } }
19.615385
55
0.658824
[ "MIT" ]
Omarmtz/DataStructuresAndAlgorithms
src/Libraries/SortingAlgorithms/ISort.cs
257
C#
/* * Copyright 2010-2013 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. */ using System; using System.Net; using Amazon.StorageGateway.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; namespace Amazon.StorageGateway.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ShutdownGateway operation /// </summary> internal class ShutdownGatewayResponseUnmarshaller : JsonResponseUnmarshaller { public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { ShutdownGatewayResponse response = new ShutdownGatewayResponse(); context.Read(); response.ShutdownGatewayResult = ShutdownGatewayResultUnmarshaller.GetInstance().Unmarshall(context); return response; } public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerErrorException")) { InternalServerErrorException ex = new InternalServerErrorException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); return ex; } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidGatewayRequestException")) { InvalidGatewayRequestException ex = new InvalidGatewayRequestException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); return ex; } return new AmazonStorageGatewayException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static ShutdownGatewayResponseUnmarshaller instance; public static ShutdownGatewayResponseUnmarshaller GetInstance() { if (instance == null) { instance = new ShutdownGatewayResponseUnmarshaller(); } return instance; } } }
40
199
0.690541
[ "Apache-2.0" ]
jdluzen/aws-sdk-net-android
AWSSDK/Amazon.StorageGateway/Model/Internal/MarshallTransformations/ShutdownGatewayResponseUnmarshaller.cs
2,960
C#
using Akka.Actor; namespace WinTail { public class ValidationActor:UntypedActor { private readonly IActorRef _consoleWriterActor; public ValidationActor(IActorRef consoleWriterActor) { _consoleWriterActor = consoleWriterActor; } protected override void OnReceive(object message) { var msg = message as string; if(string.IsNullOrEmpty(msg)) { _consoleWriterActor.Tell(new Messages.InputError("No input recieved.")); } else { if(IsValid(msg)) { _consoleWriterActor.Tell(new Messages.InputSuccess("Valid message.")); } else { _consoleWriterActor.Tell(new Messages.InputError("Invalid input. Message had odd number of characters.")); } } Sender.Tell(new Messages.ContinueProcessing()); } private static bool IsValid(string msg) { return msg.Length % 2 == 0; } } }
27.536585
126
0.528787
[ "Apache-2.0" ]
Quatzequatel/akka-bootcamp
src/Unit-1/DoThis/ValidationActor.cs
1,131
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; namespace src.API { public class WebApiApplication : HttpApplication { protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); } } }
17.058824
56
0.768966
[ "MIT" ]
choi4450/angular-aspnet-mvc5-boilerplate
src.API/Global.asax.cs
292
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace mThink.Agents { public abstract class Predator : Agent { public static int NumberOfPredators = 0; public Predator(View view) : base(view) { } } }
17
48
0.643599
[ "MIT" ]
davidson-bruno/mThink
v2/Agents/Predator.cs
291
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Newtonsoft.Json; namespace Microsoft.CodeAnalysis.Sarif.Writers { /// <summary>An implementation of <see cref="IResultLogWriter"/> that writes the results as JSON to a /// <see cref="TextWriter"/>.</summary> /// <seealso cref="T:Microsoft.CodeAnalysis.Sarif.IResultLogWriter"/> public sealed class ResultLogJsonWriter : IResultLogWriter, IDisposable { [Flags] private enum Conditions { None = 0x00, RunInitialized = 0x001, ToolWritten = 0x002, FilesWritten = 0x004, InvocationsWritten = 0x008, ResultsInitialized = 0x010, ResultsClosed = 0x020, LogicalLocationsWritten = 0x040, RunCompleted = 0x080, Disposed = 0x40000000 } private Run _run; private Conditions _writeConditions; private readonly JsonWriter _jsonWriter; private readonly JsonSerializer _serializer; /// <summary>Initializes a new instance of the <see cref="ResultLogJsonWriter"/> class.</summary> /// <param name="jsonWriter">The JSON writer. This class does not take ownership of the JSON /// writer; the caller is responsible for destroying it.</param> public ResultLogJsonWriter(JsonWriter jsonWriter) { _jsonWriter = jsonWriter; _serializer = new JsonSerializer(); } /// <summary> /// Initializes the SARIF log by emitting properties and other constructs /// sufficient to being populating a run with results. /// </summary> /// <param name="run"></param> public void Initialize(Run run) { if (run == null) { throw new ArgumentNullException(nameof(run)); } _run = run; this.EnsureStateNotAlreadySet(Conditions.Disposed | Conditions.RunInitialized); SarifVersion sarifVersion = SarifVersion.Current; _jsonWriter.WriteStartObject(); // Begin: sarifLog _jsonWriter.WritePropertyName("$schema"); _jsonWriter.WriteValue(sarifVersion.ConvertToSchemaUri().OriginalString); _jsonWriter.WritePropertyName("version"); _jsonWriter.WriteValue(sarifVersion.ConvertToText()); _jsonWriter.WritePropertyName("runs"); _jsonWriter.WriteStartArray(); // Begin: runs _jsonWriter.WriteStartObject(); // Begin: run _writeConditions |= Conditions.RunInitialized; } /// <summary> /// A list containing information about the relevant files. This information may appear /// after the results, as the full list of scanned files might not be known until /// all results have been generated. /// </summary> /// <param name="artifacts"> /// A dictionary whose keys are the URIs of scanned files and whose values provide /// information about those files. /// </param> public void WriteArtifacts(IList<Artifact> artifacts) { if (artifacts == null) { throw new ArgumentNullException(nameof(artifacts)); } EnsureInitialized(); EnsureResultsArrayIsNotOpen(); EnsureStateNotAlreadySet(Conditions.Disposed | Conditions.FilesWritten); if (artifacts.HasAtLeastOneNonNullValue()) { _jsonWriter.WritePropertyName("artifacts"); _serializer.Serialize(_jsonWriter, artifacts); } _writeConditions |= Conditions.FilesWritten; } /// <summary> /// Write information about the logical locations where results were produced to /// the log. This information may appear after the results, as the full list of /// logical locations will not be known until all results have been generated. /// </summary> /// <param name="logicalLocationDictionary"> /// A dictionary whose keys are strings specifying a logical location and /// whose values provide information about each component of the logical location. /// </param> public void WriteLogicalLocations(IList<LogicalLocation> logicalLocations) { if (logicalLocations == null) { throw new ArgumentNullException(nameof(logicalLocations)); } EnsureInitialized(); EnsureResultsArrayIsNotOpen(); EnsureStateNotAlreadySet(Conditions.Disposed | Conditions.LogicalLocationsWritten); if (logicalLocations.HasAtLeastOneNonNullValue()) { _jsonWriter.WritePropertyName("logicalLocations"); _serializer.Serialize(_jsonWriter, logicalLocations); } _writeConditions |= Conditions.LogicalLocationsWritten; } public void WriteInvocations(IEnumerable<Invocation> invocations) { if (invocations == null) { throw new ArgumentNullException(nameof(invocations)); } EnsureInitialized(); EnsureResultsArrayIsNotOpen(); EnsureStateNotAlreadySet(Conditions.Disposed | Conditions.InvocationsWritten); if (invocations.HasAtLeastOneNonNullValue()) { _jsonWriter.WritePropertyName("invocations"); _serializer.Serialize(_jsonWriter, invocations); } _writeConditions |= Conditions.InvocationsWritten; } public void WriteTool(Tool tool) { if (tool == null) { throw new ArgumentNullException(nameof(tool)); } EnsureInitialized(); EnsureResultsArrayIsNotOpen(); EnsureStateNotAlreadySet(Conditions.Disposed | Conditions.ToolWritten); SerializeIfNotNull(tool, "tool"); _writeConditions |= Conditions.ToolWritten; } public void OpenResults() { EnsureInitialized(); EnsureResultsArrayIsNotOpen(); EnsureStateNotAlreadySet(Conditions.Disposed | Conditions.ResultsClosed); _jsonWriter.WritePropertyName("results"); _jsonWriter.WriteStartArray(); // Begin: results _writeConditions |= Conditions.ResultsInitialized; } /// <summary> /// Writes a result to the log. /// </summary> /// <remarks> /// This function makes a copy of the data stored in <paramref name="result"/>; if a /// client wishes to reuse the result instance to avoid allocations they can do so. (This function /// may invoke an internal copy of the result or serialize it in place to disk, etc.) /// </remarks> /// <exception cref="IOException"> /// A file IO error occured. Clients implementing /// <see cref="ToolFileConverterBase"/> should allow these exceptions to propagate. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown if the tool info is not yet written. /// </exception> /// <param name="result"> /// The result to write. /// </param> /// <seealso cref="M:Microsoft.CodeAnalysis.Sarif.IsarifWriter.WriteResult(Result)"/> public void WriteResult(Result result) { if (result == null) { throw new ArgumentNullException(nameof(result)); } EnsureStateNotAlreadySet(Conditions.Disposed | Conditions.ResultsClosed); if ((_writeConditions & Conditions.ResultsInitialized) != Conditions.ResultsInitialized) { OpenResults(); } _serializer.Serialize(_jsonWriter, result); } /// <summary> /// Writes a set of results to the log. /// </summary> /// <remarks> /// This function makes a copy of the data stored in <paramref name="results"/>; if a /// client wishes to reuse the result instance to avoid allocations they can do so. (This function /// may invoke an internal copy of the result or serialize it in place to disk, etc.) /// </remarks> /// <exception cref="IOException"> /// A file IO error occured. Clients implementing /// <see cref="ToolFileConverterBase"/> should allow these exceptions to propagate. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown if the tool info is not yet written. /// </exception> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="result"/> is null. /// </exception> /// <param name="results"> /// The results to write. /// </param> public void WriteResults(IEnumerable<Result> results) { if (results == null) { throw new ArgumentNullException(nameof(results)); } if (results.Any()) { foreach (Result result in results) { WriteResult(result); } } else { if ((_writeConditions & Conditions.ResultsInitialized) != Conditions.ResultsInitialized) { OpenResults(); } } } public void CloseResults() { EnsureStateNotAlreadySet(Conditions.Disposed); // We allow some resilience for writers that stream individual results to // the log without explicit opening/closing the results object if ((_writeConditions & Conditions.ResultsInitialized) != Conditions.ResultsInitialized || (_writeConditions & Conditions.ResultsClosed) == Conditions.ResultsClosed) { return; } _jsonWriter.WriteEndArray(); _writeConditions |= Conditions.ResultsClosed; } public void CompleteRun() { if (_writeConditions.HasFlag(Conditions.RunCompleted)) { return; } if ((_writeConditions & Conditions.ResultsInitialized) == Conditions.ResultsInitialized && (_writeConditions & Conditions.ResultsClosed) != Conditions.ResultsClosed) { CloseResults(); } // NOTE: These components are written in schema declaration order, except for Results. // This should be as similar to serializing the whole object as possible. if ((_writeConditions & Conditions.ToolWritten) != Conditions.ToolWritten) { WriteTool(_run.Tool); } if ((_writeConditions & Conditions.InvocationsWritten) != Conditions.InvocationsWritten && _run.Invocations?.Count > 0) { WriteInvocations(_run.Invocations); } SerializeIfNotNull(_run.Tags, "tags"); SerializeIfNotNull(_run.Conversion, "conversion"); SerializeIfNotDefault(_run.Language, "language", "en-US"); SerializeIfNotNull(_run.VersionControlProvenance, "versionControlProvenance"); SerializeIfNotNull(_run.OriginalUriBaseIds, "originalUriBaseIds"); if ((_writeConditions & Conditions.FilesWritten) != Conditions.FilesWritten && _run.Artifacts != null) { WriteArtifacts(_run.Artifacts); } if ((_writeConditions & Conditions.LogicalLocationsWritten) != Conditions.LogicalLocationsWritten && _run.LogicalLocations != null) { WriteLogicalLocations(_run.LogicalLocations); } SerializeIfNotNull(_run.Graphs, "graphs"); // Results go here in schema order SerializeIfNotNull(_run.AutomationDetails, "automationDetails"); SerializeIfNotNull(_run.RunAggregates, "runAggregates"); SerializeIfNotNull(_run.BaselineGuid, "baselineGuid"); SerializeIfNotNull(_run.RedactionTokens, "redactionTokens"); SerializeIfNotNull(_run.DefaultEncoding, "defaultEncoding"); SerializeIfNotNull(_run.DefaultSourceLanguage, "defaultSourceLanguage"); SerializeIfNotNull(_run.NewlineSequences, "newlineSequences"); SerializeIfNotNull(_run.ColumnKind == ColumnKind.UnicodeCodePoints ? "unicodeCodePoints" : "utf16CodeUnits", "columnKind"); SerializeIfNotNull(_run.ExternalPropertyFileReferences, "externalPropertyFileReferences"); SerializeIfNotNull(_run.ThreadFlowLocations, "threadFlowLocations"); SerializeIfNotNull(_run.Taxonomies, "taxonomies"); SerializeIfNotNull(_run.Addresses, "addresses"); SerializeIfNotNull(_run.Translations, "translations"); SerializeIfNotNull(_run.Policies, "policies"); SerializeIfNotNull(_run.WebRequests, "webRequests"); SerializeIfNotNull(_run.WebResponses, "webResponses"); SerializeIfNotNull(_run.SpecialLocations, "specialLocations"); SerializeIfNotNull(_run.Properties, "properties"); // Log complete. Write the end object. _jsonWriter.WriteEndObject(); // End: run _jsonWriter.WriteEndArray(); // End: runs _jsonWriter.WriteEndObject(); // End: sarifLog _writeConditions |= Conditions.RunCompleted; } /// <summary>Writes the log footer and closes the underlying <see cref="JsonWriter"/>.</summary> /// <seealso cref="M:System.IDisposable.Dispose()"/> public void Dispose() { EnsureInitialized(); if ((_writeConditions & Conditions.Disposed) == Conditions.Disposed) { return; } CompleteRun(); _writeConditions |= Conditions.Disposed; } private void SerializeIfNotNull(object value, string propertyName) { // Don't serialize null objects or empty enumerables if (value == null || ExtensionMethods.IsEmptyEnumerable(value)) { return; } Serialize(value, propertyName); } private void SerializeIfNotDefault(string value, string propertyName, string defaultValue) { if (value == defaultValue) { return; } Serialize(value, propertyName); } private void Serialize(object value, string propertyName) { _jsonWriter.WritePropertyName(propertyName); _serializer.Serialize(_jsonWriter, value); } private void EnsureInitialized() { if (_writeConditions == Conditions.None) { Initialize(new Run() { Tool = new Tool() }); } } private void EnsureStateNotAlreadySet(Conditions invalidConditions) { Conditions observedInvalidConditions = _writeConditions & invalidConditions; if (observedInvalidConditions != Conditions.None) { // InvalidState One or more invalid states were detected during serialization: {0} throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SdkResources.InvalidState, observedInvalidConditions)); } } private void EnsureResultsArrayIsNotOpen() { // This method ensures that no in-progress serialization // underway. Currently, only the results serialization // is a multi-step process if ((_writeConditions & Conditions.ResultsInitialized) == Conditions.ResultsInitialized && (_writeConditions & Conditions.ResultsClosed) != Conditions.ResultsClosed) { throw new InvalidOperationException(SdkResources.ResultsSerializationNotComplete); } } } }
39.21957
151
0.603603
[ "MIT" ]
LaudateCorpus1/sarif-sdk
src/Sarif/Writers/ResultLogJsonWriter.cs
16,435
C#
using System; using System.Collections.Generic; using Hl7.Fhir.Introspection; using Hl7.Fhir.Validation; using System.Linq; using System.Runtime.Serialization; using Hl7.Fhir.Utility; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma warning disable 1591 // suppress XML summary warnings // // Generated for FHIR v3.0.2 // namespace Hl7.Fhir.Model { /// <summary> /// Roles/organizations the practitioner is associated with /// </summary> [FhirType("PractitionerRole", IsResource=true)] [DataContract] public partial class PractitionerRole : Hl7.Fhir.Model.DomainResource, System.ComponentModel.INotifyPropertyChanged { [NotMapped] public override ResourceType ResourceType { get { return ResourceType.PractitionerRole; } } [NotMapped] public override string TypeName { get { return "PractitionerRole"; } } [FhirType("AvailableTimeComponent")] [DataContract] public partial class AvailableTimeComponent : Hl7.Fhir.Model.BackboneElement, System.ComponentModel.INotifyPropertyChanged, IBackboneElement { [NotMapped] public override string TypeName { get { return "AvailableTimeComponent"; } } /// <summary> /// mon | tue | wed | thu | fri | sat | sun /// </summary> [FhirElement("daysOfWeek", Order=40)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Code<Hl7.Fhir.Model.DaysOfWeek>> DaysOfWeekElement { get { if(_DaysOfWeekElement==null) _DaysOfWeekElement = new List<Hl7.Fhir.Model.Code<Hl7.Fhir.Model.DaysOfWeek>>(); return _DaysOfWeekElement; } set { _DaysOfWeekElement = value; OnPropertyChanged("DaysOfWeekElement"); } } private List<Code<Hl7.Fhir.Model.DaysOfWeek>> _DaysOfWeekElement; /// <summary> /// mon | tue | wed | thu | fri | sat | sun /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public IEnumerable<Hl7.Fhir.Model.DaysOfWeek?> DaysOfWeek { get { return DaysOfWeekElement != null ? DaysOfWeekElement.Select(elem => elem.Value) : null; } set { if (value == null) DaysOfWeekElement = null; else DaysOfWeekElement = new List<Hl7.Fhir.Model.Code<Hl7.Fhir.Model.DaysOfWeek>>(value.Select(elem=>new Hl7.Fhir.Model.Code<Hl7.Fhir.Model.DaysOfWeek>(elem))); OnPropertyChanged("DaysOfWeek"); } } /// <summary> /// Always available? e.g. 24 hour service /// </summary> [FhirElement("allDay", Order=50)] [DataMember] public Hl7.Fhir.Model.FhirBoolean AllDayElement { get { return _AllDayElement; } set { _AllDayElement = value; OnPropertyChanged("AllDayElement"); } } private Hl7.Fhir.Model.FhirBoolean _AllDayElement; /// <summary> /// Always available? e.g. 24 hour service /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public bool? AllDay { get { return AllDayElement != null ? AllDayElement.Value : null; } set { if (!value.HasValue) AllDayElement = null; else AllDayElement = new Hl7.Fhir.Model.FhirBoolean(value); OnPropertyChanged("AllDay"); } } /// <summary> /// Opening time of day (ignored if allDay = true) /// </summary> [FhirElement("availableStartTime", Order=60)] [DataMember] public Hl7.Fhir.Model.Time AvailableStartTimeElement { get { return _AvailableStartTimeElement; } set { _AvailableStartTimeElement = value; OnPropertyChanged("AvailableStartTimeElement"); } } private Hl7.Fhir.Model.Time _AvailableStartTimeElement; /// <summary> /// Opening time of day (ignored if allDay = true) /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string AvailableStartTime { get { return AvailableStartTimeElement != null ? AvailableStartTimeElement.Value : null; } set { if (value == null) AvailableStartTimeElement = null; else AvailableStartTimeElement = new Hl7.Fhir.Model.Time(value); OnPropertyChanged("AvailableStartTime"); } } /// <summary> /// Closing time of day (ignored if allDay = true) /// </summary> [FhirElement("availableEndTime", Order=70)] [DataMember] public Hl7.Fhir.Model.Time AvailableEndTimeElement { get { return _AvailableEndTimeElement; } set { _AvailableEndTimeElement = value; OnPropertyChanged("AvailableEndTimeElement"); } } private Hl7.Fhir.Model.Time _AvailableEndTimeElement; /// <summary> /// Closing time of day (ignored if allDay = true) /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string AvailableEndTime { get { return AvailableEndTimeElement != null ? AvailableEndTimeElement.Value : null; } set { if (value == null) AvailableEndTimeElement = null; else AvailableEndTimeElement = new Hl7.Fhir.Model.Time(value); OnPropertyChanged("AvailableEndTime"); } } public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as AvailableTimeComponent; if (dest != null) { base.CopyTo(dest); if(DaysOfWeekElement != null) dest.DaysOfWeekElement = new List<Code<Hl7.Fhir.Model.DaysOfWeek>>(DaysOfWeekElement.DeepCopy()); if(AllDayElement != null) dest.AllDayElement = (Hl7.Fhir.Model.FhirBoolean)AllDayElement.DeepCopy(); if(AvailableStartTimeElement != null) dest.AvailableStartTimeElement = (Hl7.Fhir.Model.Time)AvailableStartTimeElement.DeepCopy(); if(AvailableEndTimeElement != null) dest.AvailableEndTimeElement = (Hl7.Fhir.Model.Time)AvailableEndTimeElement.DeepCopy(); return dest; } else throw new ArgumentException("Can only copy to an object of the same type", "other"); } public override IDeepCopyable DeepCopy() { return CopyTo(new AvailableTimeComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as AvailableTimeComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(DaysOfWeekElement, otherT.DaysOfWeekElement)) return false; if( !DeepComparable.Matches(AllDayElement, otherT.AllDayElement)) return false; if( !DeepComparable.Matches(AvailableStartTimeElement, otherT.AvailableStartTimeElement)) return false; if( !DeepComparable.Matches(AvailableEndTimeElement, otherT.AvailableEndTimeElement)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as AvailableTimeComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(DaysOfWeekElement, otherT.DaysOfWeekElement)) return false; if( !DeepComparable.IsExactly(AllDayElement, otherT.AllDayElement)) return false; if( !DeepComparable.IsExactly(AvailableStartTimeElement, otherT.AvailableStartTimeElement)) return false; if( !DeepComparable.IsExactly(AvailableEndTimeElement, otherT.AvailableEndTimeElement)) return false; return true; } [NotMapped] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; foreach (var elem in DaysOfWeekElement) { if (elem != null) yield return elem; } if (AllDayElement != null) yield return AllDayElement; if (AvailableStartTimeElement != null) yield return AvailableStartTimeElement; if (AvailableEndTimeElement != null) yield return AvailableEndTimeElement; } } [NotMapped] public override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; foreach (var elem in DaysOfWeekElement) { if (elem != null) yield return new ElementValue("daysOfWeek", elem); } if (AllDayElement != null) yield return new ElementValue("allDay", AllDayElement); if (AvailableStartTimeElement != null) yield return new ElementValue("availableStartTime", AvailableStartTimeElement); if (AvailableEndTimeElement != null) yield return new ElementValue("availableEndTime", AvailableEndTimeElement); } } } [FhirType("NotAvailableComponent")] [DataContract] public partial class NotAvailableComponent : Hl7.Fhir.Model.BackboneElement, System.ComponentModel.INotifyPropertyChanged, IBackboneElement { [NotMapped] public override string TypeName { get { return "NotAvailableComponent"; } } /// <summary> /// Reason presented to the user explaining why time not available /// </summary> [FhirElement("description", Order=40)] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.FhirString DescriptionElement { get { return _DescriptionElement; } set { _DescriptionElement = value; OnPropertyChanged("DescriptionElement"); } } private Hl7.Fhir.Model.FhirString _DescriptionElement; /// <summary> /// Reason presented to the user explaining why time not available /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string Description { get { return DescriptionElement != null ? DescriptionElement.Value : null; } set { if (value == null) DescriptionElement = null; else DescriptionElement = new Hl7.Fhir.Model.FhirString(value); OnPropertyChanged("Description"); } } /// <summary> /// Service not availablefrom this date /// </summary> [FhirElement("during", Order=50)] [DataMember] public Hl7.Fhir.Model.Period During { get { return _During; } set { _During = value; OnPropertyChanged("During"); } } private Hl7.Fhir.Model.Period _During; public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as NotAvailableComponent; if (dest != null) { base.CopyTo(dest); if(DescriptionElement != null) dest.DescriptionElement = (Hl7.Fhir.Model.FhirString)DescriptionElement.DeepCopy(); if(During != null) dest.During = (Hl7.Fhir.Model.Period)During.DeepCopy(); return dest; } else throw new ArgumentException("Can only copy to an object of the same type", "other"); } public override IDeepCopyable DeepCopy() { return CopyTo(new NotAvailableComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as NotAvailableComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(DescriptionElement, otherT.DescriptionElement)) return false; if( !DeepComparable.Matches(During, otherT.During)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as NotAvailableComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(DescriptionElement, otherT.DescriptionElement)) return false; if( !DeepComparable.IsExactly(During, otherT.During)) return false; return true; } [NotMapped] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (DescriptionElement != null) yield return DescriptionElement; if (During != null) yield return During; } } [NotMapped] public override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (DescriptionElement != null) yield return new ElementValue("description", DescriptionElement); if (During != null) yield return new ElementValue("during", During); } } } /// <summary> /// Business Identifiers that are specific to a role/location /// </summary> [FhirElement("identifier", InSummary=true, Order=90)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.Identifier> Identifier { get { if(_Identifier==null) _Identifier = new List<Hl7.Fhir.Model.Identifier>(); return _Identifier; } set { _Identifier = value; OnPropertyChanged("Identifier"); } } private List<Hl7.Fhir.Model.Identifier> _Identifier; /// <summary> /// Whether this practitioner's record is in active use /// </summary> [FhirElement("active", InSummary=true, Order=100)] [DataMember] public Hl7.Fhir.Model.FhirBoolean ActiveElement { get { return _ActiveElement; } set { _ActiveElement = value; OnPropertyChanged("ActiveElement"); } } private Hl7.Fhir.Model.FhirBoolean _ActiveElement; /// <summary> /// Whether this practitioner's record is in active use /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public bool? Active { get { return ActiveElement != null ? ActiveElement.Value : null; } set { if (!value.HasValue) ActiveElement = null; else ActiveElement = new Hl7.Fhir.Model.FhirBoolean(value); OnPropertyChanged("Active"); } } /// <summary> /// The period during which the practitioner is authorized to perform in these role(s) /// </summary> [FhirElement("period", InSummary=true, Order=110)] [DataMember] public Hl7.Fhir.Model.Period Period { get { return _Period; } set { _Period = value; OnPropertyChanged("Period"); } } private Hl7.Fhir.Model.Period _Period; /// <summary> /// Practitioner that is able to provide the defined services for the organation /// </summary> [FhirElement("practitioner", InSummary=true, Order=120)] [CLSCompliant(false)] [References("Practitioner")] [DataMember] public Hl7.Fhir.Model.ResourceReference Practitioner { get { return _Practitioner; } set { _Practitioner = value; OnPropertyChanged("Practitioner"); } } private Hl7.Fhir.Model.ResourceReference _Practitioner; /// <summary> /// Organization where the roles are available /// </summary> [FhirElement("organization", InSummary=true, Order=130)] [CLSCompliant(false)] [References("Organization")] [DataMember] public Hl7.Fhir.Model.ResourceReference Organization { get { return _Organization; } set { _Organization = value; OnPropertyChanged("Organization"); } } private Hl7.Fhir.Model.ResourceReference _Organization; /// <summary> /// Roles which this practitioner may perform /// </summary> [FhirElement("code", InSummary=true, Order=140)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.CodeableConcept> Code { get { if(_Code==null) _Code = new List<Hl7.Fhir.Model.CodeableConcept>(); return _Code; } set { _Code = value; OnPropertyChanged("Code"); } } private List<Hl7.Fhir.Model.CodeableConcept> _Code; /// <summary> /// Specific specialty of the practitioner /// </summary> [FhirElement("specialty", InSummary=true, Order=150)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.CodeableConcept> Specialty { get { if(_Specialty==null) _Specialty = new List<Hl7.Fhir.Model.CodeableConcept>(); return _Specialty; } set { _Specialty = value; OnPropertyChanged("Specialty"); } } private List<Hl7.Fhir.Model.CodeableConcept> _Specialty; /// <summary> /// The location(s) at which this practitioner provides care /// </summary> [FhirElement("location", InSummary=true, Order=160)] [CLSCompliant(false)] [References("Location")] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.ResourceReference> Location { get { if(_Location==null) _Location = new List<Hl7.Fhir.Model.ResourceReference>(); return _Location; } set { _Location = value; OnPropertyChanged("Location"); } } private List<Hl7.Fhir.Model.ResourceReference> _Location; /// <summary> /// The list of healthcare services that this worker provides for this role's Organization/Location(s) /// </summary> [FhirElement("healthcareService", Order=170)] [CLSCompliant(false)] [References("HealthcareService")] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.ResourceReference> HealthcareService { get { if(_HealthcareService==null) _HealthcareService = new List<Hl7.Fhir.Model.ResourceReference>(); return _HealthcareService; } set { _HealthcareService = value; OnPropertyChanged("HealthcareService"); } } private List<Hl7.Fhir.Model.ResourceReference> _HealthcareService; /// <summary> /// Contact details that are specific to the role/location/service /// </summary> [FhirElement("telecom", InSummary=true, Order=180)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.ContactPoint> Telecom { get { if(_Telecom==null) _Telecom = new List<Hl7.Fhir.Model.ContactPoint>(); return _Telecom; } set { _Telecom = value; OnPropertyChanged("Telecom"); } } private List<Hl7.Fhir.Model.ContactPoint> _Telecom; /// <summary> /// Times the Service Site is available /// </summary> [FhirElement("availableTime", Order=190)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.PractitionerRole.AvailableTimeComponent> AvailableTime { get { if(_AvailableTime==null) _AvailableTime = new List<Hl7.Fhir.Model.PractitionerRole.AvailableTimeComponent>(); return _AvailableTime; } set { _AvailableTime = value; OnPropertyChanged("AvailableTime"); } } private List<Hl7.Fhir.Model.PractitionerRole.AvailableTimeComponent> _AvailableTime; /// <summary> /// Not available during this time due to provided reason /// </summary> [FhirElement("notAvailable", Order=200)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.PractitionerRole.NotAvailableComponent> NotAvailable { get { if(_NotAvailable==null) _NotAvailable = new List<Hl7.Fhir.Model.PractitionerRole.NotAvailableComponent>(); return _NotAvailable; } set { _NotAvailable = value; OnPropertyChanged("NotAvailable"); } } private List<Hl7.Fhir.Model.PractitionerRole.NotAvailableComponent> _NotAvailable; /// <summary> /// Description of availability exceptions /// </summary> [FhirElement("availabilityExceptions", Order=210)] [DataMember] public Hl7.Fhir.Model.FhirString AvailabilityExceptionsElement { get { return _AvailabilityExceptionsElement; } set { _AvailabilityExceptionsElement = value; OnPropertyChanged("AvailabilityExceptionsElement"); } } private Hl7.Fhir.Model.FhirString _AvailabilityExceptionsElement; /// <summary> /// Description of availability exceptions /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string AvailabilityExceptions { get { return AvailabilityExceptionsElement != null ? AvailabilityExceptionsElement.Value : null; } set { if (value == null) AvailabilityExceptionsElement = null; else AvailabilityExceptionsElement = new Hl7.Fhir.Model.FhirString(value); OnPropertyChanged("AvailabilityExceptions"); } } /// <summary> /// Technical endpoints providing access to services operated for the practitioner with this role /// </summary> [FhirElement("endpoint", Order=220)] [CLSCompliant(false)] [References("Endpoint")] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.ResourceReference> Endpoint { get { if(_Endpoint==null) _Endpoint = new List<Hl7.Fhir.Model.ResourceReference>(); return _Endpoint; } set { _Endpoint = value; OnPropertyChanged("Endpoint"); } } private List<Hl7.Fhir.Model.ResourceReference> _Endpoint; public override void AddDefaultConstraints() { base.AddDefaultConstraints(); } public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as PractitionerRole; if (dest != null) { base.CopyTo(dest); if(Identifier != null) dest.Identifier = new List<Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy()); if(ActiveElement != null) dest.ActiveElement = (Hl7.Fhir.Model.FhirBoolean)ActiveElement.DeepCopy(); if(Period != null) dest.Period = (Hl7.Fhir.Model.Period)Period.DeepCopy(); if(Practitioner != null) dest.Practitioner = (Hl7.Fhir.Model.ResourceReference)Practitioner.DeepCopy(); if(Organization != null) dest.Organization = (Hl7.Fhir.Model.ResourceReference)Organization.DeepCopy(); if(Code != null) dest.Code = new List<Hl7.Fhir.Model.CodeableConcept>(Code.DeepCopy()); if(Specialty != null) dest.Specialty = new List<Hl7.Fhir.Model.CodeableConcept>(Specialty.DeepCopy()); if(Location != null) dest.Location = new List<Hl7.Fhir.Model.ResourceReference>(Location.DeepCopy()); if(HealthcareService != null) dest.HealthcareService = new List<Hl7.Fhir.Model.ResourceReference>(HealthcareService.DeepCopy()); if(Telecom != null) dest.Telecom = new List<Hl7.Fhir.Model.ContactPoint>(Telecom.DeepCopy()); if(AvailableTime != null) dest.AvailableTime = new List<Hl7.Fhir.Model.PractitionerRole.AvailableTimeComponent>(AvailableTime.DeepCopy()); if(NotAvailable != null) dest.NotAvailable = new List<Hl7.Fhir.Model.PractitionerRole.NotAvailableComponent>(NotAvailable.DeepCopy()); if(AvailabilityExceptionsElement != null) dest.AvailabilityExceptionsElement = (Hl7.Fhir.Model.FhirString)AvailabilityExceptionsElement.DeepCopy(); if(Endpoint != null) dest.Endpoint = new List<Hl7.Fhir.Model.ResourceReference>(Endpoint.DeepCopy()); return dest; } else throw new ArgumentException("Can only copy to an object of the same type", "other"); } public override IDeepCopyable DeepCopy() { return CopyTo(new PractitionerRole()); } public override bool Matches(IDeepComparable other) { var otherT = other as PractitionerRole; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(Identifier, otherT.Identifier)) return false; if( !DeepComparable.Matches(ActiveElement, otherT.ActiveElement)) return false; if( !DeepComparable.Matches(Period, otherT.Period)) return false; if( !DeepComparable.Matches(Practitioner, otherT.Practitioner)) return false; if( !DeepComparable.Matches(Organization, otherT.Organization)) return false; if( !DeepComparable.Matches(Code, otherT.Code)) return false; if( !DeepComparable.Matches(Specialty, otherT.Specialty)) return false; if( !DeepComparable.Matches(Location, otherT.Location)) return false; if( !DeepComparable.Matches(HealthcareService, otherT.HealthcareService)) return false; if( !DeepComparable.Matches(Telecom, otherT.Telecom)) return false; if( !DeepComparable.Matches(AvailableTime, otherT.AvailableTime)) return false; if( !DeepComparable.Matches(NotAvailable, otherT.NotAvailable)) return false; if( !DeepComparable.Matches(AvailabilityExceptionsElement, otherT.AvailabilityExceptionsElement)) return false; if( !DeepComparable.Matches(Endpoint, otherT.Endpoint)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as PractitionerRole; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(Identifier, otherT.Identifier)) return false; if( !DeepComparable.IsExactly(ActiveElement, otherT.ActiveElement)) return false; if( !DeepComparable.IsExactly(Period, otherT.Period)) return false; if( !DeepComparable.IsExactly(Practitioner, otherT.Practitioner)) return false; if( !DeepComparable.IsExactly(Organization, otherT.Organization)) return false; if( !DeepComparable.IsExactly(Code, otherT.Code)) return false; if( !DeepComparable.IsExactly(Specialty, otherT.Specialty)) return false; if( !DeepComparable.IsExactly(Location, otherT.Location)) return false; if( !DeepComparable.IsExactly(HealthcareService, otherT.HealthcareService)) return false; if( !DeepComparable.IsExactly(Telecom, otherT.Telecom)) return false; if( !DeepComparable.IsExactly(AvailableTime, otherT.AvailableTime)) return false; if( !DeepComparable.IsExactly(NotAvailable, otherT.NotAvailable)) return false; if( !DeepComparable.IsExactly(AvailabilityExceptionsElement, otherT.AvailabilityExceptionsElement)) return false; if( !DeepComparable.IsExactly(Endpoint, otherT.Endpoint)) return false; return true; } [NotMapped] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; foreach (var elem in Identifier) { if (elem != null) yield return elem; } if (ActiveElement != null) yield return ActiveElement; if (Period != null) yield return Period; if (Practitioner != null) yield return Practitioner; if (Organization != null) yield return Organization; foreach (var elem in Code) { if (elem != null) yield return elem; } foreach (var elem in Specialty) { if (elem != null) yield return elem; } foreach (var elem in Location) { if (elem != null) yield return elem; } foreach (var elem in HealthcareService) { if (elem != null) yield return elem; } foreach (var elem in Telecom) { if (elem != null) yield return elem; } foreach (var elem in AvailableTime) { if (elem != null) yield return elem; } foreach (var elem in NotAvailable) { if (elem != null) yield return elem; } if (AvailabilityExceptionsElement != null) yield return AvailabilityExceptionsElement; foreach (var elem in Endpoint) { if (elem != null) yield return elem; } } } [NotMapped] public override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; foreach (var elem in Identifier) { if (elem != null) yield return new ElementValue("identifier", elem); } if (ActiveElement != null) yield return new ElementValue("active", ActiveElement); if (Period != null) yield return new ElementValue("period", Period); if (Practitioner != null) yield return new ElementValue("practitioner", Practitioner); if (Organization != null) yield return new ElementValue("organization", Organization); foreach (var elem in Code) { if (elem != null) yield return new ElementValue("code", elem); } foreach (var elem in Specialty) { if (elem != null) yield return new ElementValue("specialty", elem); } foreach (var elem in Location) { if (elem != null) yield return new ElementValue("location", elem); } foreach (var elem in HealthcareService) { if (elem != null) yield return new ElementValue("healthcareService", elem); } foreach (var elem in Telecom) { if (elem != null) yield return new ElementValue("telecom", elem); } foreach (var elem in AvailableTime) { if (elem != null) yield return new ElementValue("availableTime", elem); } foreach (var elem in NotAvailable) { if (elem != null) yield return new ElementValue("notAvailable", elem); } if (AvailabilityExceptionsElement != null) yield return new ElementValue("availabilityExceptions", AvailabilityExceptionsElement); foreach (var elem in Endpoint) { if (elem != null) yield return new ElementValue("endpoint", elem); } } } } }
45.73385
179
0.586813
[ "BSD-3-Clause" ]
GinoCanessa/fhir-net-api
src/Hl7.Fhir.Core/Model/Generated/PractitionerRole.cs
35,400
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Project1_1 { public partial class frmStopWatch : Form { public frmStopWatch() { InitializeComponent(); } DateTime startTime; DateTime endTime; TimeSpan elapsedTime; private void btnStart_Click(object sender, EventArgs e) { //establish and print starting time startTime = DateTime.Now; txtStart.Text = startTime.ToLongTimeString(); txtEnd.Text = ""; txtElapsed.Text = ""; } private void btnEnd_Click(object sender, EventArgs e) { //find ending time, compute the elapsed time //Put both values in text boxes endTime = DateTime.Now; elapsedTime = endTime - startTime; txtEnd.Text = endTime.ToLongTimeString(); txtElapsed.Text = elapsedTime.Seconds.ToString(); } private void btnExit_Click(object sender, EventArgs e) { this.Close(); } } }
25.94
66
0.579029
[ "MIT" ]
Craftycoolgamer/Programs
Stopwatch/Project1-1/Form1.cs
1,299
C#
using System; using System.Collections.Generic; namespace _1._Reverse_Strings { class Program { static void Main(string[] args) { string input = Console.ReadLine(); Stack<char> reversed = new Stack<char>(); for (int i = 0; i < input.Length; i++) { reversed.Push(input[i]); } while (reversed.Count > 0) { Console.Write(reversed.Pop()); } Console.WriteLine(); } } }
20.923077
53
0.46875
[ "MIT" ]
MDeyanov/SoftUni
C#Advanced/Stacks and Queues - Lab/1. Reverse Strings/Program.cs
546
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 route53resolver-2018-04-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Route53Resolver.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Route53Resolver.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ResourceNotFoundException Object /// </summary> public class ResourceNotFoundExceptionUnmarshaller : IErrorResponseUnmarshaller<ResourceNotFoundException, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public ResourceNotFoundException Unmarshall(JsonUnmarshallerContext context) { return this.Unmarshall(context, new Amazon.Runtime.Internal.ErrorResponse()); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <param name="errorResponse"></param> /// <returns></returns> public ResourceNotFoundException Unmarshall(JsonUnmarshallerContext context, Amazon.Runtime.Internal.ErrorResponse errorResponse) { context.Read(); ResourceNotFoundException unmarshalledObject = new ResourceNotFoundException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("ResourceType", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ResourceType = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static ResourceNotFoundExceptionUnmarshaller _instance = new ResourceNotFoundExceptionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ResourceNotFoundExceptionUnmarshaller Instance { get { return _instance; } } } }
36.626374
141
0.663366
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/Route53Resolver/Generated/Model/Internal/MarshallTransformations/ResourceNotFoundExceptionUnmarshaller.cs
3,333
C#
using Application.Common.Interfaces; using Application.Common.Models; using MediatR; namespace Application.Features.UrlItems; public class DeleteUrlItemCommand : IRequest<CQRSResponse> { public string Id { get; set; } } public class DeleteUrlItemCommandHandler : IRequestHandler<DeleteUrlItemCommand, CQRSResponse> { private readonly IAppDbContext _context; public DeleteUrlItemCommandHandler(IAppDbContext context) { _context = context; } public async Task<CQRSResponse> Handle(DeleteUrlItemCommand request, CancellationToken cancellationToken) { var id = Guid.Parse(request.Id); var item = await _context.UrlItems.FindAsync(new object[] {id}, cancellationToken); if (item == null) return CQRSResponse.NotFound<string>($"Item with Id: {request.Id} has not been found."); _context.UrlItems.Remove(item); await _context.SaveChangesAsync(cancellationToken); return CQRSResponse.Success<string>("Item has been deleted successfully."); } }
30.705882
109
0.727011
[ "Apache-2.0" ]
andrewtomas/url-shortener
backend/Application/Features/UrlItems/DeleteUrlItem.cs
1,046
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 securityhub-2018-10-26.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.SecurityHub.Model { /// <summary> /// This is the response object from the GetInsights operation. /// </summary> public partial class GetInsightsResponse : AmazonWebServiceResponse { private List<Insight> _insights = new List<Insight>(); private string _nextToken; /// <summary> /// Gets and sets the property Insights. /// <para> /// The insights returned by the operation. /// </para> /// </summary> public List<Insight> Insights { get { return this._insights; } set { this._insights = value; } } // Check to see if Insights property is set internal bool IsSetInsights() { return this._insights != null && this._insights.Count > 0; } /// <summary> /// Gets and sets the property NextToken. /// <para> /// The token that is required for pagination. /// </para> /// </summary> public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } } }
29.426667
109
0.618487
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/SecurityHub/Generated/Model/GetInsightsResponse.cs
2,207
C#
/* Copyright 2006-2012 Stefano Chizzolini. http://www.pdfclown.org Contributors: * Stefano Chizzolini (original code developer, http://www.stefanochizzolini.it) This file should be part of the source code distribution of "PDF Clown library" (the Program): see the accompanying README files for more info. This Program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This Program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, either expressed or implied; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more details. You should have received a copy of the GNU Lesser General Public License along with this Program (see README files); if not, go to the GNU website (http://www.gnu.org/licenses/). Redistribution and use, with or without modification, are permitted provided that such redistributions retain the above copyright notice, license and disclaimer, along with this list of conditions. */ using tokens = org.pdfclown.tokens; using org.pdfclown.util.parsers; using System; using System.Globalization; using System.Text; namespace org.pdfclown.objects { /** <summary>PDF date object [PDF:1.6:3.8.3].</summary> */ public sealed class PdfDate : PdfString { #region static #region fields private const string FormatString = "yyyyMMddHHmmsszzz"; #endregion #region interface #region public /** <summary>Gets the object equivalent to the given value.</summary> */ public static PdfDate Get( DateTime? value ) {return value.HasValue ? new PdfDate(value.Value) : null;} /** <summary>Converts a PDF date literal into its corresponding date.</summary> <exception cref="org.pdfclown.util.parsers.ParseException">Thrown when date literal parsing fails.</exception> */ public static DateTime ToDate( string value ) { // 1. Normalization. StringBuilder dateBuilder = new StringBuilder(); try { int length = value.Length; // Year (YYYY). dateBuilder.Append(value.Substring(2, 4)); // NOTE: Skips the "D:" prefix; Year is mandatory. // Month (MM). dateBuilder.Append(length < 8 ? "01" : value.Substring(6, 2)); // Day (DD). dateBuilder.Append(length < 10 ? "01" : value.Substring(8, 2)); // Hour (HH). dateBuilder.Append(length < 12 ? "00" : value.Substring(10, 2)); // Minute (mm). dateBuilder.Append(length < 14 ? "00" : value.Substring(12, 2)); // Second (SS). dateBuilder.Append(length < 16 ? "00" : value.Substring(14, 2)); // Local time / Universal Time relationship (O). dateBuilder.Append(length < 17 || value.Substring(16, 1).Equals("Z") ? "+" : value.Substring(16, 1)); // UT Hour offset (HH'). dateBuilder.Append(length < 19 ? "00" : value.Substring(17, 2)); // UT Minute offset (mm'). dateBuilder.Append(":").Append(length < 22 ? "00" : value.Substring(20, 2)); } catch(Exception exception) {throw new ParseException("Failed to normalize the date string.", exception);} // 2. Parsing. try { return DateTime.ParseExact( dateBuilder.ToString(), FormatString, new CultureInfo("en-US") ); } catch(Exception exception) {throw new ParseException("Failed to parse the date string.", exception);} } #endregion #region private private static string Format( DateTime value ) {return ("D:" + value.ToString(FormatString).Replace(':','\'') + "'");} #endregion #endregion #endregion #region dynamic #region constructors public PdfDate( DateTime value ) {Value = value;} #endregion #region interface #region public public override PdfObject Accept( IVisitor visitor, object data ) {return visitor.Visit(this, data);} public override SerializationModeEnum SerializationMode { get {return base.SerializationMode;} set {/* NOOP: Serialization MUST be kept literal. */} } public override object Value { get // FIXME: proper call to base.StringValue could NOT be done due to an unexpected Mono runtime SIGSEGV (TOO BAD). // {return ToDate(base.StringValue);} {return ToDate((string)base.Value);} protected set {RawValue = tokens::Encoding.Pdf.Encode(Format((DateTime)value));} } #endregion #endregion #endregion } }
31.986755
118
0.648033
[ "Apache-2.0" ]
XoriantOpenSource/PDFClown
dotNET/pdfclown.lib/src/org/pdfclown/objects/PdfDate.cs
4,830
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Insights.V20180901.Outputs { [OutputType] public sealed class VoiceReceiverResponse { /// <summary> /// The country code of the voice receiver. /// </summary> public readonly string CountryCode; /// <summary> /// The name of the voice receiver. Names must be unique across all receivers within an action group. /// </summary> public readonly string Name; /// <summary> /// The phone number of the voice receiver. /// </summary> public readonly string PhoneNumber; [OutputConstructor] private VoiceReceiverResponse( string countryCode, string name, string phoneNumber) { CountryCode = countryCode; Name = name; PhoneNumber = phoneNumber; } } }
27.697674
109
0.617128
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Insights/V20180901/Outputs/VoiceReceiverResponse.cs
1,191
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.RemoveRedundantEquality { internal abstract class AbstractRemoveRedundantEqualityDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { private readonly ISyntaxFacts _syntaxFacts; protected AbstractRemoveRedundantEqualityDiagnosticAnalyzer(ISyntaxFacts syntaxFacts) : base(IDEDiagnosticIds.RemoveRedundantEqualityDiagnosticId, option: null, new LocalizableResourceString(nameof(AnalyzersResources.Remove_redundant_equality), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { _syntaxFacts = syntaxFacts; } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterOperationAction(AnalyzeBinaryOperator, OperationKind.BinaryOperator); private void AnalyzeBinaryOperator(OperationAnalysisContext context) { var operation = (IBinaryOperation)context.Operation; if (operation.OperatorMethod is not null) { // We shouldn't report diagnostic on overloaded operator as the behavior can change. return; } if (operation.OperatorKind is not (BinaryOperatorKind.Equals or BinaryOperatorKind.NotEquals)) { return; } if (!_syntaxFacts.IsBinaryExpression(operation.Syntax)) { return; } var rightOperand = operation.RightOperand; var leftOperand = operation.LeftOperand; if (rightOperand.Type.SpecialType != SpecialType.System_Boolean || leftOperand.Type.SpecialType != SpecialType.System_Boolean) { return; } var isOperatorEquals = operation.OperatorKind == BinaryOperatorKind.Equals; _syntaxFacts.GetPartsOfBinaryExpression(operation.Syntax, out _, out var operatorToken, out _); var properties = ImmutableDictionary.CreateBuilder<string, string>(); if (TryGetLiteralValue(rightOperand) == isOperatorEquals) { properties.Add(RedundantEqualityConstants.RedundantSide, RedundantEqualityConstants.Right); } else if (TryGetLiteralValue(leftOperand) == isOperatorEquals) { properties.Add(RedundantEqualityConstants.RedundantSide, RedundantEqualityConstants.Left); } if (properties.Count == 1) { context.ReportDiagnostic(Diagnostic.Create(Descriptor, operatorToken.GetLocation(), additionalLocations: new[] { operation.Syntax.GetLocation() }, properties: properties.ToImmutable())); } return; static bool? TryGetLiteralValue(IOperation operand) { // Make sure we only simplify literals to avoid changing // something like the following example: // const bool Activated = true; ... if (state == Activated) if (operand.ConstantValue.HasValue && operand.Kind == OperationKind.Literal && operand.ConstantValue.Value is bool constValue) { return constValue; } return null; } } } }
40.908163
167
0.64006
[ "MIT" ]
BrianFreemanAtlanta/roslyn
src/Analyzers/Core/Analyzers/RemoveRedundantEquality/AbstractRemoveRedundantEqualityDiagnosticAnalyzer.cs
4,011
C#
// This file was automatically generated and may be regenerated at any // time. To ensure any changes are retained, modify the tool with any segment/component/group/field name // or type changes. namespace Machete.HL7Schema.V26 { using HL7; /// <summary> /// NMR_N01_CLOCK_AND_STATS_WITH_NOTES_ALT (Group) - /// </summary> public interface NMR_N01_CLOCK_AND_STATS_WITH_NOTES_ALT : HL7V26Layout { /// <summary> /// NCK /// </summary> Segment<NCK> NCK { get; } /// <summary> /// NTE /// </summary> SegmentList<NTE> NTE { get; } /// <summary> /// NST /// </summary> Segment<NST> NST { get; } /// <summary> /// NTE2 /// </summary> SegmentList<NTE> NTE2 { get; } /// <summary> /// NSC /// </summary> Segment<NSC> NSC { get; } /// <summary> /// NTE3 /// </summary> SegmentList<NTE> NTE3 { get; } } }
23.363636
104
0.5107
[ "Apache-2.0" ]
ahives/Machete
src/Machete.HL7Schema/V26/Groups/NMR_N01_CLOCK_AND_STATS_WITH_NOTES_ALT.cs
1,028
C#
using ShellSampleApp.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ShellSampleApp.Services { public class MockDataStore : IDataStore<Item> { readonly List<Item> items; public MockDataStore() { items = new List<Item>() { new Item { Id = Guid.NewGuid().ToString(), Text = "First item", Description="This is an item description." }, new Item { Id = Guid.NewGuid().ToString(), Text = "Second item", Description="This is an item description." }, new Item { Id = Guid.NewGuid().ToString(), Text = "Third item", Description="This is an item description." }, new Item { Id = Guid.NewGuid().ToString(), Text = "Fourth item", Description="This is an item description." }, new Item { Id = Guid.NewGuid().ToString(), Text = "Fifth item", Description="This is an item description." }, new Item { Id = Guid.NewGuid().ToString(), Text = "Sixth item", Description="This is an item description." } }; } public async Task<bool> AddItemAsync(Item item) { items.Add(item); return await Task.FromResult(true); } public async Task<bool> UpdateItemAsync(Item item) { var oldItem = items.Where((Item arg) => arg.Id == item.Id).FirstOrDefault(); items.Remove(oldItem); items.Add(item); return await Task.FromResult(true); } public async Task<bool> DeleteItemAsync(string id) { var oldItem = items.Where((Item arg) => arg.Id == id).FirstOrDefault(); items.Remove(oldItem); return await Task.FromResult(true); } public async Task<Item> GetItemAsync(string id) { return await Task.FromResult(items.FirstOrDefault(s => s.Id == id)); } public async Task<IEnumerable<Item>> GetItemsAsync(bool forceRefresh = false) { return await Task.FromResult(items); } } }
35.6
126
0.578184
[ "MIT" ]
runceel/Xamarin.Forms-Shell-Android-BackButtonBehavior
src/ShellSampleApp/ShellSampleApp/ShellSampleApp/Services/MockDataStore.cs
2,138
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Book_of_Spells.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.483871
151
0.582788
[ "MIT" ]
sprtn/ProjectCerberus
Book of Spells/Properties/Settings.Designer.cs
1,071
C#
using System.Collections.Generic; using RayTracingLearning.RayTracer.Math; namespace RayTracingLearning.RayTracer.Materials { public class Lambertian : Material { #region constructors public Lambertian(Color albedo) : base(albedo, 0) { } #endregion #region methods public override bool TryGetScatteredRay(Ray rayIn, HitInfo hitInfo, out Ray rayOut) { /*vec3 target = rec.p + rec.normal + random_in_unit_sphere(); scattered = ray(rec.p, target-rec.p); attenuation = albedo; return true;*/ //Vector3 target = hitInfo.HitPoint + hitInfo.Normal + RandomUtility.RandomInSphere(1f); //Ray scatteredRay = new Ray(hitInfo.HitPoint, target - hitInfo.HitPoint); rayOut = new Ray(hitInfo.HitPoint, hitInfo.Normal + RandomUtility.RandomInSphere(1f)); // combine above two line code return true; } public override Color GetAttenuation(Ray rayIn, HitInfo hitInfo) { return albedo; } #endregion } }
32
129
0.615179
[ "MIT" ]
windsmoon/RayTracingLearning
RayTracingLearning/Assets/RayTracingLearning/Scripts/RayTracer/Materials/Lambertian.cs
1,120
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using AdaptiveExpressions; using Antlr4.Runtime; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Tree; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.Bot.Builder.LanguageGeneration { /// <summary> /// LG template expander. /// </summary> public class Expander : LGTemplateParserBaseVisitor<List<object>> { public const string LGType = "lgType"; public static readonly string RegexString = @"(?<!\\)\${(('(\\('|\\)|[^'])*?')|(""(\\(""|\\)|[^""])*?"")|(`(\\(`|\\)|[^`])*?`)|([^\r\n{}'""`])|({\s*}))+}?"; public static readonly Regex ExpressionRecognizeRegex = new Regex(RegexString, RegexOptions.Compiled); private readonly Stack<EvaluationTarget> evaluationTargetStack = new Stack<EvaluationTarget>(); private readonly EvaluationOptions lgOptions; /// <summary> /// Initializes a new instance of the <see cref="Expander"/> class. /// </summary> /// <param name="templates">Template list.</param> /// <param name="expressionParser">Given expression parser.</param> /// <param name="opt">Options for LG. including strictMode, replaceNull and lineBreakStyle.</param> public Expander(List<Template> templates, ExpressionParser expressionParser, EvaluationOptions opt = null) { Templates = templates; TemplateMap = templates.ToDictionary(x => x.Name); this.lgOptions = opt; // generate a new customized expression parser by injecting the template as functions ExpanderExpressionParser = new ExpressionParser(CustomizedEvaluatorLookup(expressionParser.EvaluatorLookup, true)); EvaluatorExpressionParser = new ExpressionParser(CustomizedEvaluatorLookup(expressionParser.EvaluatorLookup, false)); } /// <summary> /// Gets templates. /// </summary> /// <value> /// Templates. /// </value> public List<Template> Templates { get; } /// <summary> /// Gets expander expression parser. /// </summary> /// <value> /// Expression parser. /// </value> public ExpressionParser ExpanderExpressionParser { get; } /// <summary> /// Gets evaluator expression parser. /// </summary> /// <value> /// Expression parser. /// </value> public ExpressionParser EvaluatorExpressionParser { get; } /// <summary> /// Gets templateMap. /// </summary> /// <value> /// TemplateMap. /// </value> public Dictionary<string, Template> TemplateMap { get; } /// <summary> /// Expand the results of a template with given name and scope. /// </summary> /// <param name="templateName">Given template name.</param> /// <param name="scope">Given scope.</param> /// <returns>All possiable results.</returns> public List<object> ExpandTemplate(string templateName, object scope) { if (!(scope is CustomizedMemory)) { scope = new CustomizedMemory(scope); } if (!TemplateMap.ContainsKey(templateName)) { throw new Exception(TemplateErrors.TemplateNotExist(templateName)); } if (evaluationTargetStack.Any(e => e.TemplateName == templateName)) { throw new Exception($"{TemplateErrors.LoopDetected} {string.Join(" => ", evaluationTargetStack.Reverse().Select(e => e.TemplateName))} => {templateName}"); } // Using a stack to track the evaluation trace evaluationTargetStack.Push(new EvaluationTarget(templateName, scope)); var expanderResult = Visit(TemplateMap[templateName].TemplateBodyParseTree); evaluationTargetStack.Pop(); var result = new List<object>(); expanderResult.ForEach(u => { result.Add(u); }); return result; } public override List<object> VisitNormalBody([NotNull] LGTemplateParser.NormalBodyContext context) => Visit(context.normalTemplateBody()); public override List<object> VisitNormalTemplateBody([NotNull] LGTemplateParser.NormalTemplateBodyContext context) { var normalTemplateStrs = context.templateString(); var result = new List<object>(); foreach (var normalTemplateStr in normalTemplateStrs) { result.AddRange(Visit(normalTemplateStr.normalTemplateString())); } return result; } public override List<object> VisitIfElseBody([NotNull] LGTemplateParser.IfElseBodyContext context) { var ifRules = context.ifElseTemplateBody().ifConditionRule(); foreach (var ifRule in ifRules) { if (EvalCondition(ifRule.ifCondition()) && ifRule.normalTemplateBody() != null) { return Visit(ifRule.normalTemplateBody()); } } return null; } public override List<object> VisitSwitchCaseBody([NotNull] LGTemplateParser.SwitchCaseBodyContext context) { var switchCaseNodes = context.switchCaseTemplateBody().switchCaseRule(); var length = switchCaseNodes.Length; var switchExprs = switchCaseNodes[0].switchCaseStat().EXPRESSION(); var switchErrorPrefix = "Switch '" + switchExprs[0].GetText() + "': "; var switchExprResult = EvalExpression(switchExprs[0].GetText(), switchCaseNodes[0].switchCaseStat(), switchErrorPrefix); var idx = 0; foreach (var switchCaseNode in switchCaseNodes) { if (idx == 0) { idx++; continue; // skip the first node, which is switch statement } if (idx == length - 1 && switchCaseNode.switchCaseStat().DEFAULT() != null) { var defaultBody = switchCaseNode.normalTemplateBody(); if (defaultBody != null) { return Visit(defaultBody); } else { return null; } } var caseExprs = switchCaseNode.switchCaseStat().EXPRESSION(); var caseErrorPrefix = "Case '" + caseExprs[0].GetText() + "': "; var caseExprResult = EvalExpression(caseExprs[0].GetText(), switchCaseNode.switchCaseStat(), caseErrorPrefix); if (switchExprResult[0] == caseExprResult[0]) { return Visit(switchCaseNode.normalTemplateBody()); } idx++; } return null; } public override List<object> VisitStructuredBody([NotNull] LGTemplateParser.StructuredBodyContext context) { var templateRefValues = new Dictionary<string, List<object>>(); var stb = context.structuredTemplateBody(); var result = new JObject(); var typeName = stb.structuredBodyNameLine().STRUCTURE_NAME().GetText(); result[Evaluator.LGType] = typeName; var expandedResult = new List<JObject> { result }; var bodys = stb.structuredBodyContentLine(); foreach (var body in bodys) { var isKVPairBody = body.keyValueStructureLine() != null; if (isKVPairBody) { var property = body.keyValueStructureLine().STRUCTURE_IDENTIFIER().GetText().ToLower(); var value = VisitStructureValue(body.keyValueStructureLine()); if (value.Count > 1) { var valueList = new JArray(); foreach (var item in value) { var id = Guid.NewGuid().ToString(); valueList.Add(id); templateRefValues.Add(id, item); } expandedResult.ForEach(x => x[property] = valueList); } else { var id = Guid.NewGuid().ToString(); expandedResult.ForEach(x => x[property] = id); templateRefValues.Add(id, value[0]); } } else { var propertyObjects = EvalExpression(body.objectStructureLine().GetText(), body.objectStructureLine()).Select(x => JObject.Parse(x)).ToList(); var tempResult = new List<JObject>(); foreach (var res in expandedResult) { foreach (var propertyObject in propertyObjects) { var tempRes = JObject.FromObject(res); // Full reference to another structured template is limited to the structured template with same type if (propertyObject[Evaluator.LGType] != null && propertyObject[Evaluator.LGType].ToString() == typeName) { foreach (var item in propertyObject) { if (tempRes.Property(item.Key) == null) { tempRes[item.Key] = item.Value; } } } tempResult.Add(tempRes); } } expandedResult = tempResult; } } var exps = expandedResult; var finalResult = new List<object>(exps); foreach (var templateRefValue in templateRefValues) { var tempRes = new List<object>(); foreach (var res in finalResult) { foreach (var refValue in templateRefValue.Value) { tempRes.Add(res.ToString().Replace(templateRefValue.Key, refValue.ToString().Replace("\"", "\\\""))); } } finalResult = tempRes; } return finalResult; } public override List<object> VisitNormalTemplateString([NotNull] LGTemplateParser.NormalTemplateStringContext context) { var prefixErrorMsg = context.GetPrefixErrorMessage(); var result = new List<string>() { string.Empty }; foreach (ITerminalNode node in context.children) { switch (node.Symbol.Type) { case LGTemplateParser.DASH: case LGTemplateParser.MULTILINE_PREFIX: case LGTemplateParser.MULTILINE_SUFFIX: break; case LGTemplateParser.ESCAPE_CHARACTER: result = StringListConcat(result, new List<string>() { node.GetText().Escape() }); break; case LGTemplateParser.EXPRESSION: result = StringListConcat(result, EvalExpression(node.GetText(), context, prefixErrorMsg)); break; default: result = StringListConcat(result, new List<string>() { node.GetText() }); break; } } return result.Select(x => x as object).ToList(); } public object ConstructScope(string templateName, List<object> args) { var parameters = TemplateMap[templateName].Parameters; if (args.Count == 0) { // no args to construct, inherit from current scope return CurrentTarget().Scope; } var newScope = parameters.Zip(args, (k, v) => new { k, v }) .ToDictionary(x => x.k, x => x.v); return newScope; } private bool EvalCondition(LGTemplateParser.IfConditionContext condition) { var expression = condition.EXPRESSION(0); if (expression == null || // no expression means it's else EvalExpressionInCondition(expression.GetText(), condition, "Condition '" + expression.GetText() + "':")) { return true; } return false; } private List<List<object>> VisitStructureValue(LGTemplateParser.KeyValueStructureLineContext context) { var values = context.keyValueStructureValue(); var result = new List<List<string>>(); foreach (var item in values) { if (item.IsPureExpression(out var text)) { result.Add(EvalExpression(text, context)); } else { var itemStringResult = new List<string>() { string.Empty }; foreach (ITerminalNode node in item.children) { switch (node.Symbol.Type) { case LGTemplateParser.ESCAPE_CHARACTER_IN_STRUCTURE_BODY: itemStringResult = StringListConcat(itemStringResult, new List<string>() { node.GetText().Replace(@"\|", "|").Escape() }); break; case LGTemplateParser.EXPRESSION_IN_STRUCTURE_BODY: var errorPrefix = "Property '" + context.STRUCTURE_IDENTIFIER().GetText() + "':"; itemStringResult = StringListConcat(itemStringResult, EvalExpression(node.GetText(), item, errorPrefix)); break; default: itemStringResult = StringListConcat(itemStringResult, new List<string>() { node.GetText() }); break; } } result.Add(itemStringResult); } } return result.Select(x => x.Select(y => y as object).ToList()).ToList(); } private bool EvalExpressionInCondition(string exp, ParserRuleContext context = null, string errorPrefix = "") { exp = exp.TrimExpression(); var (result, error) = EvalByAdaptiveExpression(exp, CurrentTarget().Scope); if (lgOptions.StrictMode == true && (error != null || result == null)) { var templateName = CurrentTarget().TemplateName; if (evaluationTargetStack.Count > 0) { evaluationTargetStack.Pop(); } Evaluator.CheckExpressionResult(exp, error, result, templateName, context, errorPrefix); } else if (error != null || result == null || (result is bool r1 && r1 == false) || (result is int r2 && r2 == 0)) { return false; } return true; } private List<string> EvalExpression(string exp, ParserRuleContext context = null, string errorPrefix = "") { exp = exp.TrimExpression(); var (result, error) = EvalByAdaptiveExpression(exp, CurrentTarget().Scope); if (error != null || (result == null && lgOptions.StrictMode == true)) { var templateName = CurrentTarget().TemplateName; if (evaluationTargetStack.Count > 0) { evaluationTargetStack.Pop(); } Evaluator.CheckExpressionResult(exp, error, result, templateName, context, errorPrefix); } else if (result == null && lgOptions.StrictMode == false) { result = "null"; } if (result is IList && result.GetType().IsGenericType && result.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(List<>))) { var listRes = result as List<object>; return listRes.Select(x => x.ToString()).ToList(); } return new List<string>() { result.ToString() }; } // just don't want to write evaluationTargetStack.Peek() everywhere private EvaluationTarget CurrentTarget() => evaluationTargetStack.Peek(); private (object value, string error) EvalByAdaptiveExpression(string exp, object scope) { var expanderExpression = this.ExpanderExpressionParser.Parse(exp); var evaluatorExpression = this.EvaluatorExpressionParser.Parse(exp); var parse = ReconstructExpression(expanderExpression, evaluatorExpression); string error; object value; (value, error) = parse.TryEvaluate(scope); return (value, error); } private List<string> StringListConcat(List<string> list1, List<string> list2) { var result = new List<string>(); foreach (var item1 in list1) { foreach (var item2 in list2) { result.Add(item1 + item2); } } return result; } // Generate a new lookup function based on one lookup function private EvaluatorLookup CustomizedEvaluatorLookup(EvaluatorLookup baseLookup, bool isExpander) => (string name) => { var standardFunction = baseLookup(name); if (standardFunction != null) { return standardFunction; } if (name.StartsWith("lg.")) { name = name.Substring(3); } if (this.TemplateMap.ContainsKey(name)) { if (isExpander) { return new ExpressionEvaluator(name, ExpressionFunctions.Apply(this.TemplateExpander(name)), ReturnType.Object, this.ValidTemplateReference); } else { return new ExpressionEvaluator(name, ExpressionFunctions.Apply(this.TemplateEvaluator(name)), ReturnType.Object, this.ValidTemplateReference); } } const string template = "template"; if (name.Equals(template)) { return new ExpressionEvaluator(template, ExpressionFunctions.Apply(this.TemplateFunction()), ReturnType.Object, this.ValidateTemplateFunction); } const string fromFile = "fromFile"; if (name.Equals(fromFile)) { return new ExpressionEvaluator(fromFile, ExpressionFunctions.Apply(this.FromFile()), ReturnType.String, ExpressionFunctions.ValidateUnaryString); } const string activityAttachment = "ActivityAttachment"; if (name.Equals(activityAttachment)) { return new ExpressionEvaluator( activityAttachment, ExpressionFunctions.Apply(this.ActivityAttachment()), ReturnType.Object, (expr) => ExpressionFunctions.ValidateOrder(expr, null, ReturnType.Object, ReturnType.String)); } const string isTemplate = "isTemplate"; if (name.Equals(isTemplate)) { return new ExpressionEvaluator(isTemplate, ExpressionFunctions.Apply(this.IsTemplate()), ReturnType.Boolean, ExpressionFunctions.ValidateUnaryString); } return null; }; private Func<IReadOnlyList<object>, object> TemplateExpander(string templateName) => (IReadOnlyList<object> args) => { var newScope = this.ConstructScope(templateName, args.ToList()); return this.ExpandTemplate(templateName, newScope); }; private Func<IReadOnlyList<object>, object> TemplateEvaluator(string templateName) => (IReadOnlyList<object> args) => { var newScope = this.ConstructScope(templateName, args.ToList()); var value = this.ExpandTemplate(templateName, newScope); var rd = new Random(); return value[rd.Next(value.Count)]; }; // Evaluator for template(templateName, ...args) // normal case we can just use templateName(...args), but template function is particularly useful when the template name is not pre-known private Func<IReadOnlyList<object>, object> TemplateFunction() => (IReadOnlyList<object> args) => { var templateName = args[0].ToString(); var newScope = this.ConstructScope(templateName, args.Skip(1).ToList()); return this.ExpandTemplate(templateName, newScope); }; // Validator for template(...) private void ValidateTemplateFunction(Expression expression) { ExpressionFunctions.ValidateAtLeastOne(expression); var children0 = expression.Children[0]; if ((children0.ReturnType & ReturnType.Object) == 0 && (children0.ReturnType & ReturnType.String) == 0) { throw new Exception(TemplateErrors.InvalidTemplateName); } // Validate more if the name is string constant if (children0.Type == ExpressionType.Constant) { var templateName = (children0 as Constant).Value.ToString(); CheckTemplateReference(templateName, expression.Children.Skip(1)); } } private void ValidTemplateReference(Expression expression) { var templateName = expression.Type; if (!this.TemplateMap.ContainsKey(templateName)) { throw new Exception(TemplateErrors.TemplateNotExist(templateName)); } var expectedArgsCount = this.TemplateMap[templateName].Parameters.Count(); var actualArgsCount = expression.Children.Length; if (expectedArgsCount != actualArgsCount) { throw new Exception(TemplateErrors.ArgumentMismatch(templateName, expectedArgsCount, actualArgsCount)); } } private Expression ReconstructExpression(Expression expanderExpression, Expression evaluatorExpression, bool foundPrebuiltFunction = false) { if (this.TemplateMap.ContainsKey(expanderExpression.Type)) { if (foundPrebuiltFunction) { return evaluatorExpression; } } else { foundPrebuiltFunction = true; } for (var i = 0; i < expanderExpression.Children.Count(); i++) { expanderExpression.Children[i] = ReconstructExpression(expanderExpression.Children[i], evaluatorExpression.Children[i], foundPrebuiltFunction); } return expanderExpression; } private void CheckTemplateReference(string templateName, IEnumerable<Expression> children) { if (!this.TemplateMap.ContainsKey(templateName)) { throw new Exception(TemplateErrors.TemplateNotExist(templateName)); } var expectedArgsCount = this.TemplateMap[templateName].Parameters.Count(); var actualArgsCount = children.Count(); if (actualArgsCount != 0 && expectedArgsCount != actualArgsCount) { throw new Exception(TemplateErrors.ArgumentMismatch(templateName, expectedArgsCount, actualArgsCount)); } } private Func<IReadOnlyList<object>, object> ActivityAttachment() => (IReadOnlyList<object> args) => { return new JObject { [LGType] = "attachment", ["contenttype"] = args[1].ToString(), ["content"] = args[0] as JObject }; }; private Func<IReadOnlyList<object>, object> FromFile() => (IReadOnlyList<object> args) => { var filePath = args[0].ToString().NormalizePath(); var resourcePath = GetResourcePath(filePath); var stringContent = File.ReadAllText(resourcePath); var evaluator = new MatchEvaluator(m => EvalExpression(m.Value).ToString()); var result = ExpressionRecognizeRegex.Replace(stringContent, evaluator); return result.Escape(); }; private string GetResourcePath(string filePath) { string resourcePath; if (Path.IsPathRooted(filePath)) { resourcePath = filePath; } else { var template = TemplateMap[CurrentTarget().TemplateName]; var sourcePath = template.SourceRange.Source.NormalizePath(); var baseFolder = Environment.CurrentDirectory; if (Path.IsPathRooted(sourcePath)) { baseFolder = Path.GetDirectoryName(sourcePath); } resourcePath = Path.GetFullPath(Path.Combine(baseFolder, filePath)); } return resourcePath; } private Func<IReadOnlyList<object>, object> IsTemplate() => (IReadOnlyList<object> args) => { var templateName = args[0].ToString(); return TemplateMap.ContainsKey(templateName); }; } }
39.328402
171
0.538291
[ "MIT" ]
ZachT1711/botbuilder-dotnet
libraries/Microsoft.Bot.Builder.LanguageGeneration/Expander.cs
26,588
C#
using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Text.RegularExpressions; namespace N_m3u8DL_CLI { class Parser { struct Audio { public string Name; public string Language; public string Uri; public string Channels; public override string ToString() { return $"[{Name}] [{Language}] [{(string.IsNullOrEmpty(Channels) ? "" : $"{Channels}ch")}]".Replace("[]", ""); } } struct Subtitle { public string Name; public string Language; public string Uri; public override string ToString() { return $"[{Name}] [{Language}]"; } } //存储上一行key的信息,如果一样,就跳过下载key这一步 private string lastKeyLine = string.Empty; //METHOD, KEY, IV string[] m3u8CurrentKey = new string[] { "NONE", "", "" }; private string m3u8SavePath = string.Empty; private string jsonSavePath = string.Empty; private long bestBandwidth = 0; private string bestUrl = string.Empty; private string bestUrlAudio = string.Empty; private string bestUrlSub = string.Empty; Dictionary<string, List<Audio>> MEDIA_AUDIO_GROUP = new Dictionary<string, List<Audio>>(); //外挂音频所有分组信息 private string audioUrl = string.Empty; //音轨地址 Dictionary<string, List<Subtitle>> MEDIA_SUB_GROUP = new Dictionary<string, List<Subtitle>>(); //外挂字幕所有分组信息 private string subUrl = string.Empty; //字幕地址 //存放多轨道的信息 private ArrayList extLists = new ArrayList(); //标记是否已清除优酷广告分片 private static bool hasAd = false; public string BaseUrl { get; set; } = string.Empty; public string M3u8Url { get; set; } = string.Empty; public string DownDir { get; set; } = string.Empty; public string DownName { get; set; } = string.Empty; public string Headers { get; set; } = string.Empty; //存放Range信息,允许用户只下载部分视频 public static int RangeStart { get; set; } = 0; public static int RangeEnd { get; set; } = -1; //是否自动清除优酷广告分片 public static bool DelAd { get; set; } = true; //存放Range信息,允许用户只下载部分视频 public static string DurStart { get; set; } = ""; public static string DurEnd { get; set; } = ""; public string KeyFile { get; set; } = string.Empty; public string KeyBase64 { get; set; } = string.Empty; public bool LiveStream { get; set; } = false; public string KeyIV { get; set; } = string.Empty; public void Parse() { FFmpeg.REC_TIME = ""; m3u8SavePath = Path.Combine(DownDir, "raw.m3u8"); jsonSavePath = Path.Combine(DownDir, "meta.json"); if (!Directory.Exists(DownDir))//若文件夹不存在则新建文件夹 Directory.CreateDirectory(DownDir); //新建文件夹 //存放分部的所有信息(#EXT-X-DISCONTINUITY) JArray parts = new JArray(); //存放分片的所有信息 JArray segments = new JArray(); JObject segInfo = new JObject(); extLists.Clear(); MEDIA_AUDIO_GROUP.Clear(); MEDIA_SUB_GROUP.Clear(); string m3u8Content = string.Empty; string m3u8Method = string.Empty; string[] extMAP = { "", "" }; string[] extList = new string[10]; long segIndex = 0; long startIndex = 0; int targetDuration = 0; double totalDuration = 0; bool expectSegment = false, expectPlaylist = false, isIFramesOnly = false, isIndependentSegments = false, isEndlist = false, isAd = false, isM3u = false; //获取m3u8内容 //if (!LiveStream) // LOGGER.PrintLine(strings.downloadingM3u8, LOGGER.Warning); //if (M3u8Url.Contains(".cntv.")) //{ // M3u8Url = M3u8Url.Replace("/h5e/", "/"); //} if (M3u8Url.StartsWith("http")) { if (M3u8Url.Contains("nfmovies.com/hls")) m3u8Content = DecodeNfmovies.DecryptM3u8(Global.HttpDownloadFileToBytes(M3u8Url, Headers)); else if (M3u8Url.Contains("hls.ddyunp.com/ddyun") || M3u8Url.Contains("hls.90mm.me/ddyun")) m3u8Content = DecodeDdyun.DecryptM3u8(Global.HttpDownloadFileToBytes(DecodeDdyun.GetVaildM3u8Url(M3u8Url), Headers)); else m3u8Content = Global.GetWebSource(M3u8Url, Headers); } else if (M3u8Url.StartsWith("file:")) { Uri t = new Uri(M3u8Url); m3u8Content = File.ReadAllText(t.LocalPath); } else if (File.Exists(M3u8Url)) { m3u8Content = File.ReadAllText(M3u8Url); if (!M3u8Url.Contains("\\")) M3u8Url = Path.Combine(Environment.CurrentDirectory, M3u8Url); Uri t = new Uri(M3u8Url); M3u8Url = t.ToString(); } if (m3u8Content == "") return; if (M3u8Url.Contains("tlivecloud-playback-cdn.ysp.cctv.cn") && M3u8Url.Contains("endtime=")) isEndlist = true; if (M3u8Url.Contains("imooc.com/")) { m3u8Content = DecodeImooc.DecodeM3u8(m3u8Content); } if (m3u8Content.Contains("</MPD>") && m3u8Content.Contains("<MPD")) { //LOGGER.PrintLine(strings.startParsingMpd, LOGGER.Warning); //LOGGER.WriteLine(strings.startParsingMpd); var mpdSavePath = Path.Combine(DownDir, "dash.mpd"); //输出mpd文件 File.WriteAllText(mpdSavePath, m3u8Content); //分析mpd文件 M3u8Url = Global.Get302(M3u8Url, Headers); var newUri = MPDParser.Parse(DownDir, M3u8Url, m3u8Content, BaseUrl); M3u8Url = newUri; m3u8Content = File.ReadAllText(new Uri(M3u8Url).LocalPath); } if (m3u8Content.StartsWith("{\"payload\"")) { var iqJsonPath = Path.Combine(DownDir, "iq.json"); //输出mpd文件 File.WriteAllText(iqJsonPath, m3u8Content); //分析json文件 var newUri = IqJsonParser.Parse(DownDir, m3u8Content); M3u8Url = newUri; m3u8Content = File.ReadAllText(new Uri(M3u8Url).LocalPath); } //输出m3u8文件 File.WriteAllText(m3u8SavePath, m3u8Content); //针对优酷#EXT-X-VERSION:7杜比视界片源修正 if (m3u8Content.Contains("#EXT-X-DISCONTINUITY") && m3u8Content.Contains("#EXT-X-MAP") && m3u8Content.Contains("ott.cibntv.net") && m3u8Content.Contains("ccode=")) { Regex ykmap = new Regex("#EXT-X-DISCONTINUITY\\s+#EXT-X-MAP:URI=\\\"(.*?)\\\",BYTERANGE=\\\"(.*?)\\\""); foreach (Match m in ykmap.Matches(m3u8Content)) { m3u8Content = m3u8Content.Replace(m.Value, $"#EXTINF:0.000000,\n#EXT-X-BYTERANGE:{m.Groups[2].Value}\n{m.Groups[1].Value}"); } } //针对Disney+修正 if (m3u8Content.Contains("#EXT-X-DISCONTINUITY") && m3u8Content.Contains("#EXT-X-MAP") && M3u8Url.Contains("media.dssott.com/")) { Regex ykmap = new Regex("#EXT-X-MAP:URI=\\\".*?BUMPER/[\\s\\S]+?#EXT-X-DISCONTINUITY"); if (ykmap.IsMatch(m3u8Content)) { m3u8Content = m3u8Content.Replace(ykmap.Match(m3u8Content).Value, "#XXX"); } } //针对AppleTv修正 if (m3u8Content.Contains("#EXT-X-DISCONTINUITY") && m3u8Content.Contains("#EXT-X-MAP") && (M3u8Url.Contains(".apple.com/") || Regex.IsMatch(m3u8Content, "#EXT-X-MAP.*\\.apple\\.com/"))) { //只取加密部分即可 Regex ykmap = new Regex("(#EXT-X-KEY:[\\s\\S]*?)(#EXT-X-DISCONTINUITY|#EXT-X-ENDLIST)"); if (ykmap.IsMatch(m3u8Content)) { m3u8Content = "#EXTM3U\r\n" + ykmap.Match(m3u8Content).Groups[1].Value + "\r\n#EXT-X-ENDLIST"; } } //修复#EXT-X-KEY与#EXTINF出现次序异常问题 if (Regex.IsMatch(m3u8Content, "(#EXTINF.*)(\\s+)(#EXT-X-KEY.*)")) { m3u8Content = Regex.Replace(m3u8Content, "(#EXTINF.*)(\\s+)(#EXT-X-KEY.*)", "$3$2$1"); } //如果BaseUrl为空则截取字符串充当 if (BaseUrl == "") { if (new Regex("#YUMING\\|(.*)").IsMatch(m3u8Content)) BaseUrl = new Regex("#YUMING\\|(.*)").Match(m3u8Content).Groups[1].Value; else BaseUrl = GetBaseUrl(M3u8Url, Headers); } //if (!LiveStream) //{ // LOGGER.WriteLine(strings.parsingM3u8); // LOGGER.PrintLine(strings.parsingM3u8); //} if (!string.IsNullOrEmpty(KeyBase64)) { string line = ""; if (string.IsNullOrEmpty(KeyIV)) line = $"#EXT-X-KEY:METHOD=AES-128,URI=\"base64:{KeyBase64}\""; else line = $"#EXT-X-KEY:METHOD=AES-128,URI=\"base64:{KeyBase64}\",IV=0x{KeyIV.Replace("0x", "")}"; m3u8CurrentKey = ParseKey(line); } if (!string.IsNullOrEmpty(KeyFile)) { string line = ""; Uri u = new Uri(KeyFile); if (string.IsNullOrEmpty(KeyIV)) line = $"#EXT-X-KEY:METHOD=AES-128,URI=\"{u.ToString()}\""; else line = $"#EXT-X-KEY:METHOD=AES-128,URI=\"{u.ToString()}\",IV=0x{KeyIV.Replace("0x", "")}"; m3u8CurrentKey = ParseKey(line); } //逐行分析 using (StringReader sr = new StringReader(m3u8Content)) { string line; double segDuration = 0; string segUrl = string.Empty; //#EXT-X-BYTERANGE:<n>[@<o>] long expectByte = -1; //parm n long startByte = 0; //parm o while ((line = sr.ReadLine()) != null) { if (string.IsNullOrEmpty(line)) continue; if (line.StartsWith(HLSTags.ext_m3u)) isM3u = true; //只下载部分字节 else if (line.StartsWith(HLSTags.ext_x_byterange)) { string[] t = line.Replace(HLSTags.ext_x_byterange + ":", "").Split('@'); if (t.Length > 0) { if (t.Length == 1) { expectByte = Convert.ToInt64(t[0]); segInfo.Add("expectByte", expectByte); } if (t.Length == 2) { expectByte = Convert.ToInt64(t[0]); startByte = Convert.ToInt64(t[1]); segInfo.Add("expectByte", expectByte); segInfo.Add("startByte", startByte); } } expectSegment = true; } //国家地理去广告 else if (line.StartsWith("#UPLYNK-SEGMENT")) { if (line.Contains(",ad")) isAd = true; else if (line.Contains(",segment")) isAd = false; } //国家地理去广告 else if (isAd) { continue; } //解析定义的分段长度 else if (line.StartsWith(HLSTags.ext_x_targetduration)) { targetDuration = Convert.ToInt32(Convert.ToDouble(line.Replace(HLSTags.ext_x_targetduration + ":", "").Trim())); } //解析起始编号 else if (line.StartsWith(HLSTags.ext_x_media_sequence)) { segIndex = Convert.ToInt64(line.Replace(HLSTags.ext_x_media_sequence + ":", "").Trim()); startIndex = segIndex; } else if (line.StartsWith(HLSTags.ext_x_discontinuity_sequence)) ; else if (line.StartsWith(HLSTags.ext_x_program_date_time)) { if (string.IsNullOrEmpty(FFmpeg.REC_TIME)) { FFmpeg.REC_TIME = line.Replace(HLSTags.ext_x_program_date_time + ":", "").Trim(); } } //解析不连续标记,需要单独合并(timestamp不同) else if (line.StartsWith(HLSTags.ext_x_discontinuity)) { //修复优酷去除广告后的遗留问题 if (hasAd && parts.Count > 0) { segments = (JArray)parts[parts.Count - 1]; parts.RemoveAt(parts.Count - 1); hasAd = false; continue; } //常规情况的#EXT-X-DISCONTINUITY标记,新建part if (!hasAd && segments.Count > 1) { parts.Add(segments); segments = new JArray(); } } else if (line.StartsWith(HLSTags.ext_x_cue_out)) ; else if (line.StartsWith(HLSTags.ext_x_cue_out_start)) ; else if (line.StartsWith(HLSTags.ext_x_cue_span)) ; else if (line.StartsWith(HLSTags.ext_x_version)) ; else if (line.StartsWith(HLSTags.ext_x_allow_cache)) ; //解析KEY else if (line.StartsWith(HLSTags.ext_x_key)) { //自定义KEY情况 判断是否需要读取IV if (!string.IsNullOrEmpty(KeyFile) || !string.IsNullOrEmpty(KeyBase64)) { if (m3u8CurrentKey[2] == "" && line.Contains("IV=0x")) { var temp = Global.GetTagAttribute(line.Replace(HLSTags.ext_x_key + ":", ""), "IV"); m3u8CurrentKey[2] = temp; //使用m3u8中的IV } } else { m3u8CurrentKey = ParseKey(line); //存储为上一行的key信息 lastKeyLine = line; } } //解析分片时长(暂时不考虑标题属性) else if (line.StartsWith(HLSTags.extinf)) { string[] tmp = line.Replace(HLSTags.extinf + ":", "").Split(','); segDuration = Convert.ToDouble(tmp[0]); segInfo.Add("index", segIndex); segInfo.Add("method", m3u8CurrentKey[0]); //是否有加密,有的话写入KEY和IV if (m3u8CurrentKey[0] != "NONE") { segInfo.Add("key", m3u8CurrentKey[1]); //没有读取到IV,自己生成 if (m3u8CurrentKey[2] == "") segInfo.Add("iv", "0x" + Convert.ToString(segIndex, 16).PadLeft(32, '0')); else segInfo.Add("iv", m3u8CurrentKey[2]); } totalDuration += segDuration; segInfo.Add("duration", segDuration); expectSegment = true; segIndex++; } //解析STREAM属性 else if (line.StartsWith(HLSTags.ext_x_stream_inf)) { expectPlaylist = true; string bandwidth = Global.GetTagAttribute(line, "BANDWIDTH"); string average_bandwidth = Global.GetTagAttribute(line, "AVERAGE-BANDWIDTH"); string codecs = Global.GetTagAttribute(line, "CODECS"); string resolution = Global.GetTagAttribute(line, "RESOLUTION"); string frame_rate = Global.GetTagAttribute(line, "FRAME-RATE"); string hdcp_level = Global.GetTagAttribute(line, "HDCP-LEVEL"); string audio = Global.GetTagAttribute(line, "AUDIO"); string video = Global.GetTagAttribute(line, "VIDEO"); string subtitles = Global.GetTagAttribute(line, "SUBTITLES"); string closed_captions = Global.GetTagAttribute(line, "CLOSED-CAPTIONS"); extList = new string[] { bandwidth, average_bandwidth, codecs, resolution, frame_rate,hdcp_level,audio,video,subtitles,closed_captions }; } else if (line.StartsWith(HLSTags.ext_x_i_frame_stream_inf)) ; else if (line.StartsWith(HLSTags.ext_x_media)) { var groupId = Global.GetTagAttribute(line, "GROUP-ID"); if (Global.GetTagAttribute(line, "TYPE") == "AUDIO") { var audio = new Audio(); audio.Channels = Global.GetTagAttribute(line, "CHANNELS"); audio.Language = Global.GetTagAttribute(line, "LANGUAGE"); audio.Name = Global.GetTagAttribute(line, "NAME"); audio.Uri = CombineURL(BaseUrl, Global.GetTagAttribute(line, "URI")); if (!MEDIA_AUDIO_GROUP.ContainsKey(groupId)) { MEDIA_AUDIO_GROUP.Add(groupId, new List<Audio>() { audio }); } else { MEDIA_AUDIO_GROUP[groupId].Add(audio); } } else if (Global.GetTagAttribute(line, "TYPE") == "SUBTITLES") { var sub = new Subtitle(); sub.Language = Global.GetTagAttribute(line, "LANGUAGE"); sub.Name = Global.GetTagAttribute(line, "NAME"); sub.Uri = CombineURL(BaseUrl, Global.GetTagAttribute(line, "URI")); if (!MEDIA_SUB_GROUP.ContainsKey(groupId)) { MEDIA_SUB_GROUP.Add(groupId, new List<Subtitle>() { sub }); } else { MEDIA_SUB_GROUP[groupId].Add(sub); } } } else if (line.StartsWith(HLSTags.ext_x_playlist_type)) ; else if (line.StartsWith(HLSTags.ext_i_frames_only)) { isIFramesOnly = true; } else if (line.StartsWith(HLSTags.ext_is_independent_segments)) { isIndependentSegments = true; } //m3u8主体结束 else if (line.StartsWith(HLSTags.ext_x_endlist)) { if (segments.Count > 0) parts.Add(segments); segments = new JArray(); isEndlist = true; } //#EXT-X-MAP else if (line.StartsWith(HLSTags.ext_x_map)) { if (extMAP[0] == "") { extMAP[0] = Global.GetTagAttribute(line, "URI"); if (line.Contains("BYTERANGE")) extMAP[1] = Global.GetTagAttribute(line, "BYTERANGE"); if (!extMAP[0].StartsWith("http")) extMAP[0] = CombineURL(BaseUrl, extMAP[0]); } //遇到了其他的map,说明已经不是一个视频了,全部丢弃即可 else { if (segments.Count > 0) parts.Add(segments); segments = new JArray(); isEndlist = true; break; } } else if (line.StartsWith(HLSTags.ext_x_start)) ; //评论行不解析 else if (line.StartsWith("#")) continue; //空白行不解析 else if (line.StartsWith("\r\n")) continue; //解析分片的地址 else if (expectSegment) { segUrl = CombineURL(BaseUrl, line); if (M3u8Url.Contains("?__gda__")) { segUrl += new Regex("\\?__gda__.*").Match(M3u8Url).Value; } if (M3u8Url.Contains("//dlsc.hcs.cmvideo.cn") && (segUrl.EndsWith(".ts") || segUrl.EndsWith(".mp4"))) { segUrl += new Regex("\\?.*").Match(M3u8Url).Value; } segInfo.Add("segUri", segUrl); segments.Add(segInfo); segInfo = new JObject(); //优酷的广告分段则清除此分片 //需要注意,遇到广告说明程序对上文的#EXT-X-DISCONTINUITY做出的动作是不必要的, //其实上下文是同一种编码,需要恢复到原先的part上 if (DelAd && segUrl.Contains("ccode=") && segUrl.Contains("/ad/") && segUrl.Contains("duration=")) { segments.RemoveAt(segments.Count - 1); segIndex--; hasAd = true; } //优酷广告(4K分辨率测试) if (DelAd && segUrl.Contains("ccode=0902") && segUrl.Contains("duration=")) { segments.RemoveAt(segments.Count - 1); segIndex--; hasAd = true; } expectSegment = false; } //解析STREAM属性的URI else if (expectPlaylist) { string listUrl; listUrl = CombineURL(BaseUrl, line); if (M3u8Url.Contains("?__gda__")) { listUrl += new Regex("\\?__gda__.*").Match(M3u8Url).Value; } StringBuilder sb = new StringBuilder(); sb.Append("{"); sb.Append("\"URL\":\"" + listUrl + "\","); for (int i = 0; i < 10; i++) { if (extList[i] != "") { switch (i) { case 0: sb.Append("\"BANDWIDTH\":\"" + extList[i] + "\","); break; case 1: sb.Append("\"AVERAGE-BANDWIDTH\":\"" + extList[i] + "\","); break; case 2: sb.Append("\"CODECS\":\"" + extList[i] + "\","); break; case 3: sb.Append("\"RESOLUTION\":\"" + extList[i] + "\","); break; case 4: sb.Append("\"FRAME-RATE\":\"" + extList[i] + "\","); break; case 5: sb.Append("\"HDCP-LEVEL\":\"" + extList[i] + "\","); break; case 6: sb.Append("\"AUDIO\":\"" + extList[i] + "\","); break; case 7: sb.Append("\"VIDEO\":\"" + extList[i] + "\","); break; case 8: sb.Append("\"SUBTITLES\":\"" + extList[i] + "\","); break; case 9: sb.Append("\"CLOSED-CAPTIONS\":\"" + extList[i] + "\","); break; } } } sb.Append("}"); extLists.Add(sb.ToString().Replace(",}", "}")); if (Convert.ToInt64(extList[0]) >= bestBandwidth) { bestBandwidth = Convert.ToInt64(extList[0]); bestUrl = listUrl; bestUrlAudio = extList[6]; bestUrlSub = extList[8]; } extList = new string[8]; expectPlaylist = false; } } } if (isM3u == false) { LOGGER.WriteLineError(strings.invalidM3u8); LOGGER.PrintLine(strings.invalidM3u8, LOGGER.Error); return; } //直播的情况,无法遇到m3u8结束标记,需要手动将segments加入parts if (parts.HasValues == false) parts.Add(segments); //处理外挂音轨的AudioOnly逻辑 if (audioUrl != "" && Global.VIDEO_TYPE == "IGNORE") { LOGGER.WriteLine(strings.startParsing + audioUrl); LOGGER.WriteLine(strings.downloadingExternalAudioTrack); LOGGER.PrintLine(strings.downloadingExternalAudioTrack, LOGGER.Warning); try { DirectoryInfo directoryInfo = new DirectoryInfo(DownDir); directoryInfo.Delete(true); } catch (Exception) { } M3u8Url = audioUrl; BaseUrl = ""; audioUrl = ""; bestUrlAudio = ""; Parse(); return; } //构造JSON文件 JObject jsonResult = new JObject(); jsonResult.Add("m3u8", M3u8Url); jsonResult.Add("m3u8BaseUri", BaseUrl); jsonResult.Add("updateTime", DateTime.Now.ToString("o")); JObject jsonM3u8Info = new JObject(); jsonM3u8Info.Add("originalCount", segIndex - startIndex); jsonM3u8Info.Add("count", segIndex - startIndex); jsonM3u8Info.Add("vod", isEndlist); jsonM3u8Info.Add("targetDuration", targetDuration); jsonM3u8Info.Add("totalDuration", totalDuration); if (bestUrlAudio != "" && MEDIA_AUDIO_GROUP.ContainsKey(bestUrlAudio)) { if (MEDIA_AUDIO_GROUP[bestUrlAudio].Count == 1) { audioUrl = MEDIA_AUDIO_GROUP[bestUrlAudio][0].Uri; } //多种音频语言 让用户选择 else { var startCursorIndex = Console.CursorTop; var cursorIndex = startCursorIndex; LOGGER.PrintLine("Found Multiple Language Audio Tracks.", LOGGER.Warning); for (int i = 0; i < MEDIA_AUDIO_GROUP[bestUrlAudio].Count; i++) { Console.WriteLine("".PadRight(13) + $"[{i.ToString().PadLeft(2)}]. {bestUrlAudio} => {MEDIA_AUDIO_GROUP[bestUrlAudio][i]}"); cursorIndex++; } LOGGER.PrintLine("Please Select What You Want.(Up To 1 Track)"); Console.Write("".PadRight(13) + "Enter Number: "); var input = Console.ReadLine(); cursorIndex += 2; for (int i = startCursorIndex; i < cursorIndex; i++) { Console.SetCursorPosition(0, i); Console.Write("".PadRight(300)); } Console.SetCursorPosition(0, startCursorIndex); audioUrl = MEDIA_AUDIO_GROUP[bestUrlAudio][int.Parse(input)].Uri; } } if (bestUrlSub != "" && MEDIA_SUB_GROUP.ContainsKey(bestUrlSub)) { if (MEDIA_SUB_GROUP[bestUrlSub].Count == 1) { subUrl = MEDIA_SUB_GROUP[bestUrlSub][0].Uri; } //多种字幕语言 让用户选择 else { var startCursorIndex = Console.CursorTop; var cursorIndex = startCursorIndex; LOGGER.PrintLine("Found Multiple Language Subtitle Tracks.", LOGGER.Warning); for (int i = 0; i < MEDIA_SUB_GROUP[bestUrlSub].Count; i++) { Console.WriteLine("".PadRight(13) + $"[{i.ToString().PadLeft(2)}]. {bestUrlSub} => {MEDIA_SUB_GROUP[bestUrlSub][i]}"); cursorIndex++; } LOGGER.PrintLine("Please Select What You Want.(Up To 1 Track)"); Console.Write("".PadRight(13) + "Enter Number: "); var input = Console.ReadLine(); cursorIndex += 2; for (int i = startCursorIndex; i < cursorIndex; i++) { Console.SetCursorPosition(0, i); Console.Write("".PadRight(300)); } Console.SetCursorPosition(0, startCursorIndex); subUrl = MEDIA_SUB_GROUP[bestUrlSub][int.Parse(input)].Uri; } } if (audioUrl != "") jsonM3u8Info.Add("audio", audioUrl); if (subUrl != "") jsonM3u8Info.Add("sub", subUrl); if (extMAP[0] != "") { DownloadManager.HasExtMap = true; if (extMAP[1] == "") jsonM3u8Info.Add("extMAP", extMAP[0]); else jsonM3u8Info.Add("extMAP", extMAP[0] + "|" + extMAP[1]); } else { DownloadManager.HasExtMap = false; } //根据DurRange来生成分片Range if (DurStart != "" || DurEnd != "") { double secStart = 0; double secEnd = -1; if (DurEnd == "") { secEnd = totalDuration; } //时间码 Regex reg2 = new Regex(@"(\d+):(\d+):(\d+)"); if (reg2.IsMatch(DurStart)) { int HH = Convert.ToInt32(reg2.Match(DurStart).Groups[1].Value); int MM = Convert.ToInt32(reg2.Match(DurStart).Groups[2].Value); int SS = Convert.ToInt32(reg2.Match(DurStart).Groups[3].Value); secStart = SS + MM * 60 + HH * 60 * 60; } if (reg2.IsMatch(DurEnd)) { int HH = Convert.ToInt32(reg2.Match(DurEnd).Groups[1].Value); int MM = Convert.ToInt32(reg2.Match(DurEnd).Groups[2].Value); int SS = Convert.ToInt32(reg2.Match(DurEnd).Groups[3].Value); secEnd = SS + MM * 60 + HH * 60 * 60; } bool flag1 = false; bool flag2 = false; if (secEnd - secStart > 0) { double dur = 0; //当前时间 foreach (JArray part in parts) { foreach (var seg in part) { dur += Convert.ToDouble(seg["duration"].ToString()); if (flag1 == false && dur > secStart) { RangeStart = seg["index"].Value<int>(); flag1 = true; } if (flag2 == false && dur >= secEnd) { RangeEnd = seg["index"].Value<int>(); flag2 = true; } } } } } //根据Range来清除部分分片 if (RangeStart != 0 || RangeEnd != -1) { if (RangeEnd == -1) RangeEnd = (int)(segIndex - startIndex - 1); int newCount = 0; double newTotalDuration = 0; JArray newParts = new JArray(); foreach (JArray part in parts) { JArray newPart = new JArray(); foreach (var seg in part) { if (RangeStart <= seg["index"].Value<int>() && seg["index"].Value<int>() <= RangeEnd) { newPart.Add(seg); newCount++; newTotalDuration += Convert.ToDouble(seg["duration"].ToString()); } } if (newPart.Count != 0) newParts.Add(newPart); } parts = newParts; jsonM3u8Info["count"] = newCount; jsonM3u8Info["totalDuration"] = newTotalDuration; } //添加 jsonM3u8Info.Add("segments", parts); jsonResult.Add("m3u8Info", jsonM3u8Info); //输出JSON文件 if (!LiveStream) { LOGGER.WriteLine(strings.wrtingMeta); LOGGER.PrintLine(strings.wrtingMeta); } File.WriteAllText(jsonSavePath, jsonResult.ToString()); //检测是否为master list MasterListCheck(); } bool downloadingM3u8KeyTip = false; public string[] ParseKey(string line) { if (!downloadingM3u8KeyTip) { LOGGER.PrintLine(strings.downloadingM3u8Key, LOGGER.Warning); downloadingM3u8KeyTip = true; } string[] tmp = line.Replace(HLSTags.ext_x_key + ":", "").Split(','); string[] key = new string[] { "NONE", "", "" }; string u_l = Global.GetTagAttribute(lastKeyLine.Replace(HLSTags.ext_x_key + ":", ""), "URI"); string m = Global.GetTagAttribute(line.Replace(HLSTags.ext_x_key + ":", ""), "METHOD"); string u = Global.GetTagAttribute(line.Replace(HLSTags.ext_x_key + ":", ""), "URI"); string i = Global.GetTagAttribute(line.Replace(HLSTags.ext_x_key + ":", ""), "IV"); //存在加密 if (m != "") { if (m != "AES-128") { LOGGER.PrintLine(string.Format(strings.notSupportMethod, m), LOGGER.Error); DownloadManager.BinaryMerge = true; return new string[] { $"{m}(NOTSUPPORTED)", "", "" }; } //METHOD key[0] = m; //URI key[1] = u; if (u_l == u) { key[1] = m3u8CurrentKey[1]; } else { LOGGER.WriteLine(strings.downloadingM3u8Key + " " + key[1]); if (key[1].StartsWith("http")) { string keyUrl = key[1]; if (key[1].Contains("imooc.com/")) { key[1] = DecodeImooc.DecodeKey(Global.GetWebSource(key[1], Headers)); } else if (key[1] == "https://hls.ventunotech.com/m3u8/pc_videosecurevtnkey.key") { string temp = Global.GetWebSource(keyUrl, Headers); LOGGER.PrintLine(temp); byte[] tempKey = new byte[16]; for (int d = 0; d < 16; d++) { tempKey[d] = Convert.ToByte(temp.Substring(2 * d, 2), 16); } key[1] = Convert.ToBase64String(tempKey); } else if (key[1].Contains("elearning.cdeledu.com/hls/service/getKeyForHls")) { var keyBytes = Global.HttpDownloadFileToBytes(keyUrl, Headers); if (keyBytes.Length != 16) { key[1] = DecodeCdeledu.DecodeKey(Encoding.UTF8.GetString(keyBytes)); } else { key[1] = Convert.ToBase64String(keyBytes); } } else if (key[1].Contains("drm.vod2.myqcloud.com/getlicense")) { var temp = Global.HttpDownloadFileToBytes(keyUrl, Headers); key[1] = DecodeHuke88Key.DecodeKey(key[1], temp); } else { if (keyUrl.Contains("https://keydeliver.linetv.tw/jurassicPark")) //linetv keyUrl = keyUrl + "?time=" + Global.GetTimeStamp(false); key[1] = Convert.ToBase64String(Global.HttpDownloadFileToBytes(keyUrl, Headers)); } } //DMM网站 else if (key[1].StartsWith("base64:")) { key[1] = key[1].Replace("base64:", ""); } else { string keyUrl = CombineURL(BaseUrl, key[1]); if (keyUrl.Contains("edu.51cto.com")) //51cto { string lessonId = Global.GetQueryString("lesson_id", keyUrl); keyUrl = keyUrl + "&sign=" + Decode51CtoKey.GetSign(lessonId); var encodeKey = Encoding.UTF8.GetString(Global.HttpDownloadFileToBytes(keyUrl, Headers)); key[1] = Decode51CtoKey.GetDecodeKey(encodeKey, lessonId); } else { key[1] = Convert.ToBase64String(Global.HttpDownloadFileToBytes(keyUrl, Headers)); } } } //IV key[2] = i; } return key; } public void MasterListCheck() { //若存在多个清晰度条目,输出另一个json文件存放 if (extLists.Count != 0) { File.Copy(m3u8SavePath, Path.GetDirectoryName(m3u8SavePath) + "\\master.m3u8", true); LOGGER.WriteLine("Master List Found"); LOGGER.PrintLine(strings.masterListFound, LOGGER.Warning); var json = new JObject(); json.Add("masterUri", M3u8Url); json.Add("updateTime", DateTime.Now.ToString("o")); json.Add("playLists", JArray.Parse("[" + string.Join(",", extLists.ToArray()) + "]")); if (MEDIA_AUDIO_GROUP.Keys.Count > 0) { var audioGroup = JObject.FromObject(MEDIA_AUDIO_GROUP); json.Add("audioTracks", audioGroup); } if (MEDIA_SUB_GROUP.Keys.Count > 0) { var subGroup = JObject.FromObject(MEDIA_SUB_GROUP); json.Add("subtitleTracks", subGroup); } //输出json文件 LOGGER.WriteLine(strings.wrtingMasterMeta); LOGGER.PrintLine(strings.wrtingMasterMeta); File.WriteAllText(Path.GetDirectoryName(jsonSavePath) + "\\playLists.json", json.ToString()); LOGGER.WriteLine(strings.selectPlaylist + ": " + bestUrl); LOGGER.PrintLine(strings.selectPlaylist); LOGGER.WriteLine(strings.startReParsing); LOGGER.PrintLine(strings.startReParsing, LOGGER.Warning); //重置Baseurl并重新解析 M3u8Url = bestUrl; BaseUrl = ""; Parse(); } } //解决低版本.Net框架的一个BUG(XP上百分之百复现) //https://stackoverflow.com/questions/781205/getting-a-url-with-an-url-encoded-slash# private void ForceCanonicalPathAndQuery(Uri uri) { string paq = uri.PathAndQuery; // need to access PathAndQuery FieldInfo flagsFieldInfo = typeof(Uri).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic); ulong flags = (ulong)flagsFieldInfo.GetValue(uri); flags &= ~((ulong)0x30); // Flags.PathNotCanonical|Flags.QueryNotCanonical flagsFieldInfo.SetValue(uri, flags); } /// <summary> /// 拼接Baseurl和RelativeUrl /// </summary> /// <param name="baseurl">Baseurl</param> /// <param name="url">RelativeUrl</param> /// <returns></returns> public string CombineURL(string baseurl, string url) { /* //本地文件形式 if (File.Exists(Path.Combine(baseurl, url))) { return Path.Combine(baseurl, url); }*/ Uri uri1 = new Uri(baseurl); //这里直接传完整的URL即可 Uri uri2 = new Uri(uri1, url); ForceCanonicalPathAndQuery(uri2); //兼容XP的低版本.Net url = uri2.ToString(); /* if (!url.StartsWith("http")) { if (url.StartsWith("/")) { if (!url.Contains(":")) // => /livelvy:livelvy/lvy1/WysAABmKyDctEW8V-13959.ts?n=vdn-gdzh-tel-1-6 url = baseurl.Substring(0, baseurl.Length - 1) + url; else url = baseurl.Substring(0, baseurl.Length - 1) + url.Substring(url.IndexOf(':')); } else url = baseurl + url; }*/ return url; } /// <summary> /// 从url中截取字符串充当baseurl /// </summary> /// <param name="m3u8url"></param> /// <returns></returns> public static string GetBaseUrl(string m3u8url, string headers) { string url = Global.Get302(m3u8url, headers); if (url.Contains("?")) url = url.Remove(url.LastIndexOf('?')); url = url.Substring(0, url.LastIndexOf('/') + 1); return url; } } }
44.775225
198
0.426774
[ "MIT" ]
FusselTeddy/N_m3u8DL-CLI
N_m3u8DL-CLI/Parser.cs
46,186
C#
using System; using System.Threading; using System.Threading.Tasks; namespace Fluxor.Extensions { public static class SpinLockExtensions { public static void ExecuteLocked(this SpinLock spinLock, Action callback) { if (callback == null) throw new ArgumentNullException(nameof(callback)); bool lockTaken = false; try { do { spinLock.Enter(ref lockTaken); } while (!lockTaken); callback(); } finally { if (lockTaken) spinLock.Exit(); } } public static async Task ExecuteLockedAsync(this SpinLock spinLock, Func<Task> callback) { if (callback == null) throw new ArgumentNullException(nameof(callback)); bool lockTaken = false; try { while (!lockTaken) spinLock.Enter(ref lockTaken); await callback().ConfigureAwait(false); } finally { if (lockTaken) spinLock.Exit(); } } } }
18
90
0.655556
[ "MIT" ]
DarthKurt/Fluxor
Source/Fluxor/Extensions/SpinLockExtensions.cs
902
C#
using MassTransit; using MassTransit.Azure.ServiceBus.Core; using MassTransit.ConsumeConfigurators; using System; namespace Kros.MassTransit.AzureServiceBus.Endpoints { /// <summary> /// Class representing Azure service bus endpoint. /// </summary> public abstract class Endpoint { /// <summary> /// Endpoint name. /// </summary> protected string _name; /// <summary> /// Adds new consumer to endpoint. /// </summary> /// <typeparam name="TMessage">Type of message processed by consumer.</typeparam> /// <param name="handler">Delegate to process message.</param> public abstract void AddConsumer<TMessage>(MessageHandler<TMessage> handler) where TMessage : class; /// <summary> /// Adds new consumer to endpoint. /// </summary> /// <typeparam name="TConsumer">Type of message consumer.</typeparam> /// <param name="configure">Delegate to configure consumer.</param> public abstract void AddConsumer<TConsumer>(Action<IConsumerConfigurator<TConsumer>> configure = null) where TConsumer : class, IConsumer; /// <summary> /// Adds new consumer with dependencies to endpoint. /// </summary> /// <typeparam name="TConsumer">Type of message consumer.</typeparam> /// <param name="provider">Service provider (DI container).</param> /// <param name="configure">Delegate to configure consumer.</param> public abstract void AddConsumer<TConsumer>( IServiceProvider provider, Action<IConsumerConfigurator<TConsumer>> configure = null) where TConsumer : class, IConsumer; /// <summary> /// Sets endpoint and its consumers during service bus initialization. /// </summary> /// <param name="busCfg">Service bus configuration.</param> /// <param name="host">Service bus host.</param> public abstract void SetEndpoint(IServiceBusBusFactoryConfigurator busCfg, IServiceBusHost host); } }
40.568627
110
0.645723
[ "Unlicense" ]
kubinko/AzureServiceBusDemo
Kros.MassTransit.AzureServiceBus/Endpoints/Endpoint.cs
2,071
C#
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace JoyOI.OnlineJudge.Models { /// <summary> /// Sub judge status. /// </summary> public class SubJudgeStatus { /// <summary> /// Gets or sets the status identifier. /// </summary> /// <value>The status identifier.</value> [ForeignKey("Status")] public Guid StatusId { get; set; } /// <summary> /// Gets or sets the status. /// </summary> /// <value>The status.</value> [JsonIgnore] public virtual JudgeStatus Status { get; set; } /// <summary> /// Gets or sets the sub id /// </summary> /// <value>The sub id</value> public int SubId { get; set; } /// <summary> /// Gets or sets the result. /// </summary> /// <value>The result.</value> [MaxLength(32)] [JsonConverter(typeof(StringEnumConverter))] public JudgeResult Result { get; set; } /// <summary> /// Gets or sets the test case identifier. /// </summary> /// <value>The test case identifier.</value> [ForeignKey("TestCase")] public Guid? TestCaseId { get; set; } /// <summary> /// Gets or sets the test case. /// </summary> /// <value>The test case.</value> public virtual TestCase TestCase { get; set; } /// <summary> /// Gets or sets the input blob id /// </summary> public Guid InputBlobId { get; set; } /// <summary> /// Gets or sets the output blob id in management service /// </summary> /// <value>The output blob id</value> public Guid OutputBlobId { get; set; } /// <summary> /// Gets or sets the hint /// </summary> /// <value>The hint</value> public string Hint { get; set; } /// <summary> /// Gets or sets the memory used (byte) /// </summary> /// <value>The memory used in byte</value> public int MemoryUsedInByte { get; set; } /// <summary> /// Gets or sets the time used (ms) /// </summary> /// <value>The time used in ms</value> public int TimeUsedInMs { get; set; } } }
28.529412
65
0.530309
[ "MIT" ]
JoyOI/OnlineJudge
src/JoyOI.OnlineJudge.Models/SubJudgeStatus.cs
2,427
C#
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using Storage.Net.Blobs; using Xunit; namespace Storage.Net.Tests.Integration.Blobs { public class AzureBlobStorageFixture : BlobFixture { public AzureBlobStorageFixture() : base("testcontainer/") { } protected override IBlobStorage CreateStorage(ITestSettings settings) { return StorageFactory.Blobs.AzureBlobStorage(settings.AzureStorageName, settings.AzureStorageKey); } } public class AzureBlobStorageTest : BlobTest, IClassFixture<AzureBlobStorageFixture> { public AzureBlobStorageTest(AzureBlobStorageFixture fixture) : base(fixture) { } } public class AzureFilesFixture : BlobFixture { public AzureFilesFixture() : base("testshare") { } protected override IBlobStorage CreateStorage(ITestSettings settings) { return StorageFactory.Blobs.AzureFiles(settings.AzureStorageName, settings.AzureStorageKey); } } public class AzureFilesTest : BlobTest, IClassFixture<AzureFilesFixture> { public AzureFilesTest(AzureFilesFixture fixture) : base(fixture) { } } public class AdlsGen1Fixture : BlobFixture { protected override IBlobStorage CreateStorage(ITestSettings settings) { return StorageFactory.Blobs.AzureDataLakeGen1StoreByClientSecret( settings.AzureDataLakeStoreAccountName, settings.AzureDataLakeTenantId, settings.AzureDataLakePrincipalId, settings.AzureDataLakePrincipalSecret); } } public class AdlsGen1Test : BlobTest, IClassFixture<AdlsGen1Fixture> { public AdlsGen1Test(AdlsGen1Fixture fixture) : base(fixture) { } } public class AdlsGen2Fixture : BlobFixture { public AdlsGen2Fixture() : base("integration") { } protected override IBlobStorage CreateStorage(ITestSettings settings) { return StorageFactory.Blobs.AzureDataLakeGen2StoreBySharedAccessKey(settings.AzureDataLakeGen2Name, settings.AzureDataLakeGen2Key); } } public class AdlsGen2Test : BlobTest, IClassFixture<AdlsGen2Fixture> { public AdlsGen2Test(AdlsGen2Fixture fixture) : base(fixture) { } } public class DiskDirectoryStorageFixture : BlobFixture { protected override IBlobStorage CreateStorage(ITestSettings settings) { return StorageFactory.Blobs.DirectoryFiles(TestDir); } } public class DiskDirectoryTest : BlobTest, IClassFixture<DiskDirectoryStorageFixture> { public DiskDirectoryTest(DiskDirectoryStorageFixture fixture) : base(fixture) { } } public class ZipFileFixture : BlobFixture { protected override IBlobStorage CreateStorage(ITestSettings settings) { return StorageFactory.Blobs.ZipFile(Path.Combine(TestDir, "test.zip")); } } public class ZipFileTest : BlobTest, IClassFixture<ZipFileFixture> { public ZipFileTest(ZipFileFixture fixture) : base(fixture) { } } public class AwsS3Fixture : BlobFixture { protected override IBlobStorage CreateStorage(ITestSettings settings) { return StorageFactory.Blobs.AmazonS3BlobStorage( settings.AwsAccessKeyId, settings.AwsSecretAccessKey, settings.AwsTestBucketName); } } public class AwsS3Test : BlobTest, IClassFixture<AwsS3Fixture> { public AwsS3Test(AwsS3Fixture fixture) : base(fixture) { } } public class InMemoryFixture : BlobFixture { protected override IBlobStorage CreateStorage(ITestSettings settings) { return StorageFactory.Blobs.InMemory(); } } public class InMemoryTest : BlobTest, IClassFixture<InMemoryFixture> { public InMemoryTest(InMemoryFixture fixture) : base(fixture) { } } public class AzureKeyVaultFixture : BlobFixture { protected override IBlobStorage CreateStorage(ITestSettings settings) { return StorageFactory.Blobs.AzureKeyVault( settings.KeyVaultUri, settings.KeyVaultCreds); } } public class AzureKeyVaultTest : BlobTest, IClassFixture<AzureKeyVaultFixture> { public AzureKeyVaultTest(AzureKeyVaultFixture fixture) : base(fixture) { } } public class FtpFixture : BlobFixture { protected override IBlobStorage CreateStorage(ITestSettings settings) { return StorageFactory.Blobs.Ftp( settings.FtpHostName, new NetworkCredential(settings.FtpUsername, settings.FtpPassword)); } } /* i don't have an ftp server anymore public class FtpTest : BlobTest, IClassFixture<FtpFixture> { public FtpTest(FtpFixture fixture) : base(fixture) { } }*/ public class AzdbfsFixture : BlobFixture { protected override IBlobStorage CreateStorage(ITestSettings settings) { return StorageFactory.Blobs.AzureDatabricksDbfs(settings.DatabricksBaseUri, settings.DatabricksToken, true); } } #if DEBUG public class AzdbfsTest : BlobTest, IClassFixture<AzdbfsFixture> { public AzdbfsTest(AzdbfsFixture fixture) : base(fixture) { } } #endif public class GcpFixture : BlobFixture { protected override IBlobStorage CreateStorage(ITestSettings settings) { return StorageFactory.Blobs.GoogleCloudStorageFromJson( settings.GcpStorageBucketName, settings.GcpStorageJsonCreds, true); } } public class GcpTest : BlobTest, IClassFixture<GcpFixture> { public GcpTest(GcpFixture fixture) : base(fixture) { } } }
26.257778
140
0.67671
[ "MIT" ]
MoimHossain/storage
test/Storage.Net.Tests.Integration/Trio/BlobTest.Variations.cs
5,910
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 comprehendmedical-2018-10-30.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.Runtime; using Amazon.ComprehendMedical.Model; namespace Amazon.ComprehendMedical { /// <summary> /// Interface for accessing ComprehendMedical /// /// Amazon Comprehend Medical extracts structured information from unstructured clinical /// text. Use these actions to gain insight in your documents. /// </summary> public partial interface IAmazonComprehendMedical : IAmazonService, IDisposable { #region DescribeEntitiesDetectionV2Job /// <summary> /// Gets the properties associated with a medical entities detection job. Use this operation /// to get the status of a detection job. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeEntitiesDetectionV2Job service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeEntitiesDetectionV2Job service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ResourceNotFoundException"> /// The resource identified by the specified Amazon Resource Name (ARN) was not found. /// Check the ARN and try your request again. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TooManyRequestsException"> /// You have made too many requests within a short period of time. Wait for a short time /// and then try your request again. Contact customer support for more information about /// a service limit increase. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/DescribeEntitiesDetectionV2Job">REST API Reference for DescribeEntitiesDetectionV2Job Operation</seealso> Task<DescribeEntitiesDetectionV2JobResponse> DescribeEntitiesDetectionV2JobAsync(DescribeEntitiesDetectionV2JobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeICD10CMInferenceJob /// <summary> /// Gets the properties associated with an InferICD10CM job. Use this operation to get /// the status of an inference job. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeICD10CMInferenceJob service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeICD10CMInferenceJob service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ResourceNotFoundException"> /// The resource identified by the specified Amazon Resource Name (ARN) was not found. /// Check the ARN and try your request again. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TooManyRequestsException"> /// You have made too many requests within a short period of time. Wait for a short time /// and then try your request again. Contact customer support for more information about /// a service limit increase. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/DescribeICD10CMInferenceJob">REST API Reference for DescribeICD10CMInferenceJob Operation</seealso> Task<DescribeICD10CMInferenceJobResponse> DescribeICD10CMInferenceJobAsync(DescribeICD10CMInferenceJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribePHIDetectionJob /// <summary> /// Gets the properties associated with a protected health information (PHI) detection /// job. Use this operation to get the status of a detection job. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribePHIDetectionJob service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribePHIDetectionJob service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ResourceNotFoundException"> /// The resource identified by the specified Amazon Resource Name (ARN) was not found. /// Check the ARN and try your request again. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TooManyRequestsException"> /// You have made too many requests within a short period of time. Wait for a short time /// and then try your request again. Contact customer support for more information about /// a service limit increase. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/DescribePHIDetectionJob">REST API Reference for DescribePHIDetectionJob Operation</seealso> Task<DescribePHIDetectionJobResponse> DescribePHIDetectionJobAsync(DescribePHIDetectionJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeRxNormInferenceJob /// <summary> /// Gets the properties associated with an InferRxNorm job. Use this operation to get /// the status of an inference job. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeRxNormInferenceJob service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeRxNormInferenceJob service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ResourceNotFoundException"> /// The resource identified by the specified Amazon Resource Name (ARN) was not found. /// Check the ARN and try your request again. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TooManyRequestsException"> /// You have made too many requests within a short period of time. Wait for a short time /// and then try your request again. Contact customer support for more information about /// a service limit increase. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/DescribeRxNormInferenceJob">REST API Reference for DescribeRxNormInferenceJob Operation</seealso> Task<DescribeRxNormInferenceJobResponse> DescribeRxNormInferenceJobAsync(DescribeRxNormInferenceJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DetectEntities /// <summary> /// The <code>DetectEntities</code> operation is deprecated. You should use the <a>DetectEntitiesV2</a> /// operation instead. /// /// /// <para> /// Inspects the clinical text for a variety of medical entities and returns specific /// information about them such as entity category, location, and confidence score on /// that information . /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DetectEntities service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DetectEntities service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidEncodingException"> /// The input text was not in valid UTF-8 character encoding. Check your text then retry /// your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ServiceUnavailableException"> /// The Amazon Comprehend Medical service is temporarily unavailable. Please wait and /// then retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TextSizeLimitExceededException"> /// The size of the text you submitted exceeds the size limit. Reduce the size of the /// text or use a smaller document and then retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TooManyRequestsException"> /// You have made too many requests within a short period of time. Wait for a short time /// and then try your request again. Contact customer support for more information about /// a service limit increase. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/DetectEntities">REST API Reference for DetectEntities Operation</seealso> [Obsolete("This operation is deprecated, use DetectEntitiesV2 instead.")] Task<DetectEntitiesResponse> DetectEntitiesAsync(DetectEntitiesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DetectEntitiesV2 /// <summary> /// Inspects the clinical text for a variety of medical entities and returns specific /// information about them such as entity category, location, and confidence score on /// that information. Amazon Comprehend Medical only detects medical entities in English /// language texts. /// /// /// <para> /// The <code>DetectEntitiesV2</code> operation replaces the <a>DetectEntities</a> operation. /// This new action uses a different model for determining the entities in your medical /// text and changes the way that some entities are returned in the output. You should /// use the <code>DetectEntitiesV2</code> operation in all new applications. /// </para> /// /// <para> /// The <code>DetectEntitiesV2</code> operation returns the <code>Acuity</code> and <code>Direction</code> /// entities as attributes instead of types. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DetectEntitiesV2 service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DetectEntitiesV2 service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidEncodingException"> /// The input text was not in valid UTF-8 character encoding. Check your text then retry /// your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ServiceUnavailableException"> /// The Amazon Comprehend Medical service is temporarily unavailable. Please wait and /// then retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TextSizeLimitExceededException"> /// The size of the text you submitted exceeds the size limit. Reduce the size of the /// text or use a smaller document and then retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TooManyRequestsException"> /// You have made too many requests within a short period of time. Wait for a short time /// and then try your request again. Contact customer support for more information about /// a service limit increase. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/DetectEntitiesV2">REST API Reference for DetectEntitiesV2 Operation</seealso> Task<DetectEntitiesV2Response> DetectEntitiesV2Async(DetectEntitiesV2Request request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DetectPHI /// <summary> /// Inspects the clinical text for protected health information (PHI) entities and returns /// the entity category, location, and confidence score for each entity. Amazon Comprehend /// Medical only detects entities in English language texts. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DetectPHI service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DetectPHI service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidEncodingException"> /// The input text was not in valid UTF-8 character encoding. Check your text then retry /// your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ServiceUnavailableException"> /// The Amazon Comprehend Medical service is temporarily unavailable. Please wait and /// then retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TextSizeLimitExceededException"> /// The size of the text you submitted exceeds the size limit. Reduce the size of the /// text or use a smaller document and then retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TooManyRequestsException"> /// You have made too many requests within a short period of time. Wait for a short time /// and then try your request again. Contact customer support for more information about /// a service limit increase. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/DetectPHI">REST API Reference for DetectPHI Operation</seealso> Task<DetectPHIResponse> DetectPHIAsync(DetectPHIRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region InferICD10CM /// <summary> /// InferICD10CM detects medical conditions as entities listed in a patient record and /// links those entities to normalized concept identifiers in the ICD-10-CM knowledge /// base from the Centers for Disease Control. Amazon Comprehend Medical only detects /// medical entities in English language texts. /// </summary> /// <param name="request">Container for the necessary parameters to execute the InferICD10CM service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the InferICD10CM service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidEncodingException"> /// The input text was not in valid UTF-8 character encoding. Check your text then retry /// your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ServiceUnavailableException"> /// The Amazon Comprehend Medical service is temporarily unavailable. Please wait and /// then retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TextSizeLimitExceededException"> /// The size of the text you submitted exceeds the size limit. Reduce the size of the /// text or use a smaller document and then retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TooManyRequestsException"> /// You have made too many requests within a short period of time. Wait for a short time /// and then try your request again. Contact customer support for more information about /// a service limit increase. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/InferICD10CM">REST API Reference for InferICD10CM Operation</seealso> Task<InferICD10CMResponse> InferICD10CMAsync(InferICD10CMRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region InferRxNorm /// <summary> /// InferRxNorm detects medications as entities listed in a patient record and links to /// the normalized concept identifiers in the RxNorm database from the National Library /// of Medicine. Amazon Comprehend Medical only detects medical entities in English language /// texts. /// </summary> /// <param name="request">Container for the necessary parameters to execute the InferRxNorm service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the InferRxNorm service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidEncodingException"> /// The input text was not in valid UTF-8 character encoding. Check your text then retry /// your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ServiceUnavailableException"> /// The Amazon Comprehend Medical service is temporarily unavailable. Please wait and /// then retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TextSizeLimitExceededException"> /// The size of the text you submitted exceeds the size limit. Reduce the size of the /// text or use a smaller document and then retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TooManyRequestsException"> /// You have made too many requests within a short period of time. Wait for a short time /// and then try your request again. Contact customer support for more information about /// a service limit increase. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/InferRxNorm">REST API Reference for InferRxNorm Operation</seealso> Task<InferRxNormResponse> InferRxNormAsync(InferRxNormRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListEntitiesDetectionV2Jobs /// <summary> /// Gets a list of medical entity detection jobs that you have submitted. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListEntitiesDetectionV2Jobs service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListEntitiesDetectionV2Jobs service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TooManyRequestsException"> /// You have made too many requests within a short period of time. Wait for a short time /// and then try your request again. Contact customer support for more information about /// a service limit increase. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ValidationException"> /// The filter that you specified for the operation is invalid. Check the filter values /// that you entered and try your request again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/ListEntitiesDetectionV2Jobs">REST API Reference for ListEntitiesDetectionV2Jobs Operation</seealso> Task<ListEntitiesDetectionV2JobsResponse> ListEntitiesDetectionV2JobsAsync(ListEntitiesDetectionV2JobsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListICD10CMInferenceJobs /// <summary> /// Gets a list of InferICD10CM jobs that you have submitted. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListICD10CMInferenceJobs service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListICD10CMInferenceJobs service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TooManyRequestsException"> /// You have made too many requests within a short period of time. Wait for a short time /// and then try your request again. Contact customer support for more information about /// a service limit increase. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ValidationException"> /// The filter that you specified for the operation is invalid. Check the filter values /// that you entered and try your request again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/ListICD10CMInferenceJobs">REST API Reference for ListICD10CMInferenceJobs Operation</seealso> Task<ListICD10CMInferenceJobsResponse> ListICD10CMInferenceJobsAsync(ListICD10CMInferenceJobsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListPHIDetectionJobs /// <summary> /// Gets a list of protected health information (PHI) detection jobs that you have submitted. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListPHIDetectionJobs service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListPHIDetectionJobs service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TooManyRequestsException"> /// You have made too many requests within a short period of time. Wait for a short time /// and then try your request again. Contact customer support for more information about /// a service limit increase. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ValidationException"> /// The filter that you specified for the operation is invalid. Check the filter values /// that you entered and try your request again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/ListPHIDetectionJobs">REST API Reference for ListPHIDetectionJobs Operation</seealso> Task<ListPHIDetectionJobsResponse> ListPHIDetectionJobsAsync(ListPHIDetectionJobsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListRxNormInferenceJobs /// <summary> /// Gets a list of InferRxNorm jobs that you have submitted. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListRxNormInferenceJobs service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListRxNormInferenceJobs service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TooManyRequestsException"> /// You have made too many requests within a short period of time. Wait for a short time /// and then try your request again. Contact customer support for more information about /// a service limit increase. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ValidationException"> /// The filter that you specified for the operation is invalid. Check the filter values /// that you entered and try your request again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/ListRxNormInferenceJobs">REST API Reference for ListRxNormInferenceJobs Operation</seealso> Task<ListRxNormInferenceJobsResponse> ListRxNormInferenceJobsAsync(ListRxNormInferenceJobsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region StartEntitiesDetectionV2Job /// <summary> /// Starts an asynchronous medical entity detection job for a collection of documents. /// Use the <code>DescribeEntitiesDetectionV2Job</code> operation to track the status /// of a job. /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartEntitiesDetectionV2Job service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the StartEntitiesDetectionV2Job service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ResourceNotFoundException"> /// The resource identified by the specified Amazon Resource Name (ARN) was not found. /// Check the ARN and try your request again. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TooManyRequestsException"> /// You have made too many requests within a short period of time. Wait for a short time /// and then try your request again. Contact customer support for more information about /// a service limit increase. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/StartEntitiesDetectionV2Job">REST API Reference for StartEntitiesDetectionV2Job Operation</seealso> Task<StartEntitiesDetectionV2JobResponse> StartEntitiesDetectionV2JobAsync(StartEntitiesDetectionV2JobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region StartICD10CMInferenceJob /// <summary> /// Starts an asynchronous job to detect medical conditions and link them to the ICD-10-CM /// ontology. Use the <code>DescribeICD10CMInferenceJob</code> operation to track the /// status of a job. /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartICD10CMInferenceJob service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the StartICD10CMInferenceJob service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ResourceNotFoundException"> /// The resource identified by the specified Amazon Resource Name (ARN) was not found. /// Check the ARN and try your request again. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TooManyRequestsException"> /// You have made too many requests within a short period of time. Wait for a short time /// and then try your request again. Contact customer support for more information about /// a service limit increase. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/StartICD10CMInferenceJob">REST API Reference for StartICD10CMInferenceJob Operation</seealso> Task<StartICD10CMInferenceJobResponse> StartICD10CMInferenceJobAsync(StartICD10CMInferenceJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region StartPHIDetectionJob /// <summary> /// Starts an asynchronous job to detect protected health information (PHI). Use the <code>DescribePHIDetectionJob</code> /// operation to track the status of a job. /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartPHIDetectionJob service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the StartPHIDetectionJob service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ResourceNotFoundException"> /// The resource identified by the specified Amazon Resource Name (ARN) was not found. /// Check the ARN and try your request again. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TooManyRequestsException"> /// You have made too many requests within a short period of time. Wait for a short time /// and then try your request again. Contact customer support for more information about /// a service limit increase. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/StartPHIDetectionJob">REST API Reference for StartPHIDetectionJob Operation</seealso> Task<StartPHIDetectionJobResponse> StartPHIDetectionJobAsync(StartPHIDetectionJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region StartRxNormInferenceJob /// <summary> /// Starts an asynchronous job to detect medication entities and link them to the RxNorm /// ontology. Use the <code>DescribeRxNormInferenceJob</code> operation to track the status /// of a job. /// </summary> /// <param name="request">Container for the necessary parameters to execute the StartRxNormInferenceJob service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the StartRxNormInferenceJob service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ResourceNotFoundException"> /// The resource identified by the specified Amazon Resource Name (ARN) was not found. /// Check the ARN and try your request again. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.TooManyRequestsException"> /// You have made too many requests within a short period of time. Wait for a short time /// and then try your request again. Contact customer support for more information about /// a service limit increase. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/StartRxNormInferenceJob">REST API Reference for StartRxNormInferenceJob Operation</seealso> Task<StartRxNormInferenceJobResponse> StartRxNormInferenceJobAsync(StartRxNormInferenceJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region StopEntitiesDetectionV2Job /// <summary> /// Stops a medical entities detection job in progress. /// </summary> /// <param name="request">Container for the necessary parameters to execute the StopEntitiesDetectionV2Job service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the StopEntitiesDetectionV2Job service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ResourceNotFoundException"> /// The resource identified by the specified Amazon Resource Name (ARN) was not found. /// Check the ARN and try your request again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/StopEntitiesDetectionV2Job">REST API Reference for StopEntitiesDetectionV2Job Operation</seealso> Task<StopEntitiesDetectionV2JobResponse> StopEntitiesDetectionV2JobAsync(StopEntitiesDetectionV2JobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region StopICD10CMInferenceJob /// <summary> /// Stops an InferICD10CM inference job in progress. /// </summary> /// <param name="request">Container for the necessary parameters to execute the StopICD10CMInferenceJob service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the StopICD10CMInferenceJob service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ResourceNotFoundException"> /// The resource identified by the specified Amazon Resource Name (ARN) was not found. /// Check the ARN and try your request again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/StopICD10CMInferenceJob">REST API Reference for StopICD10CMInferenceJob Operation</seealso> Task<StopICD10CMInferenceJobResponse> StopICD10CMInferenceJobAsync(StopICD10CMInferenceJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region StopPHIDetectionJob /// <summary> /// Stops a protected health information (PHI) detection job in progress. /// </summary> /// <param name="request">Container for the necessary parameters to execute the StopPHIDetectionJob service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the StopPHIDetectionJob service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ResourceNotFoundException"> /// The resource identified by the specified Amazon Resource Name (ARN) was not found. /// Check the ARN and try your request again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/StopPHIDetectionJob">REST API Reference for StopPHIDetectionJob Operation</seealso> Task<StopPHIDetectionJobResponse> StopPHIDetectionJobAsync(StopPHIDetectionJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region StopRxNormInferenceJob /// <summary> /// Stops an InferRxNorm inference job in progress. /// </summary> /// <param name="request">Container for the necessary parameters to execute the StopRxNormInferenceJob service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the StopRxNormInferenceJob service method, as returned by ComprehendMedical.</returns> /// <exception cref="Amazon.ComprehendMedical.Model.InternalServerException"> /// An internal server error occurred. Retry your request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.InvalidRequestException"> /// The request that you made is invalid. Check your request to determine why it's invalid /// and then retry the request. /// </exception> /// <exception cref="Amazon.ComprehendMedical.Model.ResourceNotFoundException"> /// The resource identified by the specified Amazon Resource Name (ARN) was not found. /// Check the ARN and try your request again. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/comprehendmedical-2018-10-30/StopRxNormInferenceJob">REST API Reference for StopRxNormInferenceJob Operation</seealso> Task<StopRxNormInferenceJobResponse> StopRxNormInferenceJobAsync(StopRxNormInferenceJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion } }
59.383394
219
0.684425
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/ComprehendMedical/Generated/_netstandard/IAmazonComprehendMedical.cs
48,635
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.Data.SqlClient; using System.Linq; using Microsoft.EntityFrameworkCore.TestUtilities; using Microsoft.EntityFrameworkCore.TestUtilities.Xunit; using Xunit; using Xunit.Abstractions; // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore.Query { public class DbFunctionsSqlServerTest : DbFunctionsTestBase<NorthwindQuerySqlServerFixture<NoopModelCustomizer>> { public DbFunctionsSqlServerTest( NorthwindQuerySqlServerFixture<NoopModelCustomizer> fixture, ITestOutputHelper testOutputHelper) : base(fixture) { Fixture.TestSqlLoggerFactory.Clear(); //Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper); } public override void Like_literal() { base.Like_literal(); AssertSql( @"SELECT COUNT(*) FROM [Customers] AS [c] WHERE [c].[ContactName] LIKE N'%M%'"); } public override void Like_identity() { base.Like_identity(); AssertSql( @"SELECT COUNT(*) FROM [Customers] AS [c] WHERE [c].[ContactName] LIKE [c].[ContactName]"); } public override void Like_literal_with_escape() { base.Like_literal_with_escape(); AssertSql( @"SELECT COUNT(*) FROM [Customers] AS [c] WHERE [c].[ContactName] LIKE N'!%' ESCAPE N'!'"); } [ConditionalFact] [SqlServerCondition(SqlServerCondition.SupportsFullTextSearch)] public async void FreeText_literal() { using (var context = CreateContext()) { var result = await context.Employees .Where(c => EF.Functions.FreeText(c.Title, "Representative")) .ToListAsync(); Assert.Equal(result.First().EmployeeID, 1u); AssertSql( @"SELECT [c].[EmployeeID], [c].[City], [c].[Country], [c].[FirstName], [c].[ReportsTo], [c].[Title] FROM [Employees] AS [c] WHERE FREETEXT([c].[Title], N'Representative')"); } } [ConditionalFact] public void FreeText_client_eval_throws() { Assert.Throws<InvalidOperationException>(() => EF.Functions.FreeText("teststring", "teststring")); Assert.Throws<InvalidOperationException>(() => EF.Functions.FreeText("teststring", "teststring", 1033)); } [ConditionalFact] [SqlServerCondition(SqlServerCondition.SupportsFullTextSearch)] public void FreeText_multiple_words() { using (var context = CreateContext()) { var result = context.Employees .Where(c => EF.Functions.FreeText(c.Title, "Representative Sales")) .Count(); Assert.Equal(result, 9); AssertSql( @"SELECT COUNT(*) FROM [Employees] AS [c] WHERE FREETEXT([c].[Title], N'Representative Sales')"); } } [ConditionalFact] [SqlServerCondition(SqlServerCondition.SupportsFullTextSearch)] public void FreeText_with_language_term() { using (var context = CreateContext()) { var result = context.Employees.SingleOrDefault(c => EF.Functions.FreeText(c.Title, "President", 1033)); Assert.Equal(result.EmployeeID, 2u); AssertSql( @"SELECT TOP(2) [c].[EmployeeID], [c].[City], [c].[Country], [c].[FirstName], [c].[ReportsTo], [c].[Title] FROM [Employees] AS [c] WHERE FREETEXT([c].[Title], N'President', LANGUAGE 1033)"); } } [ConditionalFact] [SqlServerCondition(SqlServerCondition.SupportsFullTextSearch)] public void FreeText_with_multiple_words_and_language_term() { using (var context = CreateContext()) { var result = context.Employees .Where(c => EF.Functions.FreeText(c.Title, "Representative President", 1033)) .ToList(); Assert.Equal(result.First().EmployeeID, 1u); AssertSql( @"SELECT [c].[EmployeeID], [c].[City], [c].[Country], [c].[FirstName], [c].[ReportsTo], [c].[Title] FROM [Employees] AS [c] WHERE FREETEXT([c].[Title], N'Representative President', LANGUAGE 1033)"); } } [ConditionalFact] [SqlServerCondition(SqlServerCondition.SupportsFullTextSearch)] public void FreeText_multiple_predicates() { using (var context = CreateContext()) { var result = context.Employees .Where( c => EF.Functions.FreeText(c.City, "London") && EF.Functions.FreeText(c.Title, "Manager", 1033)) .FirstOrDefault(); Assert.Equal(result.EmployeeID, 5u); AssertSql( @"SELECT TOP(1) [c].[EmployeeID], [c].[City], [c].[Country], [c].[FirstName], [c].[ReportsTo], [c].[Title] FROM [Employees] AS [c] WHERE (FREETEXT([c].[City], N'London')) AND (FREETEXT([c].[Title], N'Manager', LANGUAGE 1033))"); } } [ConditionalFact] [SqlServerCondition(SqlServerCondition.SupportsFullTextSearch)] public void FreeText_throws_for_no_FullText_index() { using (var context = CreateContext()) { Assert.Throws<SqlException>( () => context.Employees.Where(c => EF.Functions.FreeText(c.FirstName, "Fred")).ToArray()); } } [ConditionalFact] [SqlServerCondition(SqlServerCondition.SupportsFullTextSearch)] public void FreeText_through_navigation() { using (var context = CreateContext()) { var result = context.Employees .Where( c => EF.Functions.FreeText(c.Manager.Title, "President") && EF.Functions.FreeText(c.Title, "Inside") && c.FirstName.Contains("Lau")) .LastOrDefault(); Assert.Equal(result.EmployeeID, 8u); AssertSql( @"SELECT [c].[EmployeeID], [c].[City], [c].[Country], [c].[FirstName], [c].[ReportsTo], [c].[Title] FROM [Employees] AS [c] LEFT JOIN [Employees] AS [c.Manager] ON [c].[ReportsTo] = [c.Manager].[EmployeeID] WHERE ((FREETEXT([c.Manager].[Title], N'President')) AND (FREETEXT([c].[Title], N'Inside'))) AND (CHARINDEX(N'Lau', [c].[FirstName]) > 0)"); } } [ConditionalFact] [SqlServerCondition(SqlServerCondition.SupportsFullTextSearch)] public void FreeText_through_navigation_with_language_terms() { using (var context = CreateContext()) { var result = context.Employees .Where( c => EF.Functions.FreeText(c.Manager.Title, "President", 1033) && EF.Functions.FreeText(c.Title, "Inside", 1031) && c.FirstName.Contains("Lau")) .LastOrDefault(); Assert.Equal(result.EmployeeID, 8u); AssertSql( @"SELECT [c].[EmployeeID], [c].[City], [c].[Country], [c].[FirstName], [c].[ReportsTo], [c].[Title] FROM [Employees] AS [c] LEFT JOIN [Employees] AS [c.Manager] ON [c].[ReportsTo] = [c.Manager].[EmployeeID] WHERE ((FREETEXT([c.Manager].[Title], N'President', LANGUAGE 1033)) AND (FREETEXT([c].[Title], N'Inside', LANGUAGE 1031))) AND (CHARINDEX(N'Lau', [c].[FirstName]) > 0)"); } } [ConditionalFact] [SqlServerCondition(SqlServerCondition.SupportsFullTextSearch)] public async void FreeText_throws_when_using_non_parameter_or_constant_for_freetext_string() { using (var context = CreateContext()) { await Assert.ThrowsAsync<SqlException>( async () => await context.Employees.FirstOrDefaultAsync( e => EF.Functions.FreeText(e.City, e.FirstName))); await Assert.ThrowsAsync<SqlException>( async () => await context.Employees.FirstOrDefaultAsync( e => EF.Functions.FreeText(e.City, ""))); await Assert.ThrowsAsync<SqlException>( async () => await context.Employees.FirstOrDefaultAsync( e => EF.Functions.FreeText(e.City, e.FirstName.ToUpper()))); } } [ConditionalFact] [SqlServerCondition(SqlServerCondition.SupportsFullTextSearch)] public async void FreeText_throws_when_using_non_column_for_proeprty_reference() { using (var context = CreateContext()) { await Assert.ThrowsAsync<InvalidOperationException>( async () => await context.Employees.FirstOrDefaultAsync( e => EF.Functions.FreeText(e.City + "1", "President"))); await Assert.ThrowsAsync<InvalidOperationException>( async () => await context.Employees.FirstOrDefaultAsync( e => EF.Functions.FreeText(e.City.ToLower(), "President"))); await Assert.ThrowsAsync<InvalidOperationException>( async () => await (from e1 in context.Employees join m1 in context.Employees.OrderBy(e => e.EmployeeID).Skip(0) on e1.ReportsTo equals m1.EmployeeID where EF.Functions.FreeText(m1.Title, "President") select e1).LastOrDefaultAsync()); } } [ConditionalFact] public virtual void DateDiff_Year() { using (var context = CreateContext()) { var count = context.Orders .Count(c => EF.Functions.DateDiffYear(c.OrderDate, DateTime.Now) == 0); Assert.Equal(0, count); AssertSql( @"SELECT COUNT(*) FROM [Orders] AS [c] WHERE DATEDIFF(YEAR, [c].[OrderDate], GETDATE()) = 0"); } } [ConditionalFact] public virtual void DateDiff_Month() { using (var context = CreateContext()) { var count = context.Orders .Count(c => EF.Functions.DateDiffMonth(c.OrderDate, DateTime.Now) == 0); Assert.Equal(0, count); AssertSql( @"SELECT COUNT(*) FROM [Orders] AS [c] WHERE DATEDIFF(MONTH, [c].[OrderDate], GETDATE()) = 0"); } } [ConditionalFact] public virtual void DateDiff_Day() { using (var context = CreateContext()) { var count = context.Orders .Count(c => EF.Functions.DateDiffDay(c.OrderDate, DateTime.Now) == 0); Assert.Equal(0, count); AssertSql( @"SELECT COUNT(*) FROM [Orders] AS [c] WHERE DATEDIFF(DAY, [c].[OrderDate], GETDATE()) = 0"); } } [ConditionalFact] public virtual void DateDiff_Hour() { using (var context = CreateContext()) { var count = context.Orders .Count(c => EF.Functions.DateDiffHour(c.OrderDate, DateTime.Now) == 0); Assert.Equal(0, count); AssertSql( @"SELECT COUNT(*) FROM [Orders] AS [c] WHERE DATEDIFF(HOUR, [c].[OrderDate], GETDATE()) = 0"); } } [ConditionalFact] public virtual void DateDiff_Minute() { using (var context = CreateContext()) { var count = context.Orders .Count(c => EF.Functions.DateDiffMinute(c.OrderDate, DateTime.Now) == 0); Assert.Equal(0, count); AssertSql( @"SELECT COUNT(*) FROM [Orders] AS [c] WHERE DATEDIFF(MINUTE, [c].[OrderDate], GETDATE()) = 0"); } } [ConditionalFact] public virtual void DateDiff_Second() { using (var context = CreateContext()) { var count = context.Orders .Count(c => EF.Functions.DateDiffSecond(c.OrderDate, DateTime.Now) == 0); Assert.Equal(0, count); AssertSql( @"SELECT COUNT(*) FROM [Orders] AS [c] WHERE DATEDIFF(SECOND, [c].[OrderDate], GETDATE()) = 0"); } } [ConditionalFact] public virtual void DateDiff_Millisecond() { using (var context = CreateContext()) { var count = context.Orders .Count(c => EF.Functions.DateDiffMillisecond(DateTime.Now, DateTime.Now.AddDays(1)) == 0); Assert.Equal(0, count); AssertSql( @"SELECT COUNT(*) FROM [Orders] AS [c] WHERE DATEDIFF(MILLISECOND, GETDATE(), DATEADD(day, 1.0E0, GETDATE())) = 0"); } } [ConditionalFact] public virtual void DateDiff_Microsecond() { using (var context = CreateContext()) { var count = context.Orders .Count(c => EF.Functions.DateDiffMicrosecond(DateTime.Now, DateTime.Now.AddSeconds(1)) == 0); Assert.Equal(0, count); AssertSql( @"SELECT COUNT(*) FROM [Orders] AS [c] WHERE DATEDIFF(MICROSECOND, GETDATE(), DATEADD(second, 1.0E0, GETDATE())) = 0"); } } [ConditionalFact] public virtual void DateDiff_Nanosecond() { using (var context = CreateContext()) { var count = context.Orders .Count(c => EF.Functions.DateDiffNanosecond(DateTime.Now, DateTime.Now.AddSeconds(1)) == 0); Assert.Equal(0, count); AssertSql( @"SELECT COUNT(*) FROM [Orders] AS [c] WHERE DATEDIFF(NANOSECOND, GETDATE(), DATEADD(second, 1.0E0, GETDATE())) = 0"); } } private void AssertSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected); } }
36.600985
170
0.538291
[ "Apache-2.0" ]
austindrenski/EntityFrameworkCore
test/EFCore.SqlServer.FunctionalTests/Query/DbFunctionsSqlServerTest.cs
14,860
C#
using PostSharp.Aspects; using PostSharp.Aspects.Advices; using System; using System.Linq; using System.Reflection; using System.Windows.Forms; using FP.PostSharpSamples.BL; namespace FP.PostSharpSamples.UI.Controls { [Serializable] public class IncludeAdditionalControlAspectPS4 : InstanceLevelAspect { public override bool CompileTimeValidate(Type type) { return !type.IsAbstract && typeof(Form).IsAssignableFrom(type); } [OnInstanceConstructedAdvice] public void OnInstanceConstructed() { var tabControlMember = Instance.GetType() .GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance) .FirstOrDefault(x => x.FieldType == typeof(TabControl)); if (tabControlMember == null) return; var tabControl = tabControlMember.GetValue(Instance) as TabControl; if (tabControl == null) return; var formControllerMember = Instance.GetType() .GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance) .FirstOrDefault(x => x.FieldType.IsSubclassOf(typeof(BaseController))); if (formControllerMember == null) return; var formController = formControllerMember.GetValue(Instance) as BaseController; if (formController == null) return; var tabPage = new TabPage {Text = "Documents"}; DocumentControl documentControl = new DocumentControl(); tabPage.Controls.Add(documentControl); documentControl.Dock = DockStyle.Fill; tabControl.TabPages.Add(tabPage); formController.DataSourceInitialized += (sender, eventArgs) => documentControl.Controller.InitDataSource(); } } }
38.703704
119
0.579904
[ "MIT" ]
fpommerening/PostSharpSamples
UiManipulation/FP.PostSharpSamples.UI.Controls/IncludeAdditionalControlAspectPS4.cs
2,092
C#
namespace WindowsFormsApp1 { 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.btnRight = new System.Windows.Forms.Button(); this.btnLeft = new System.Windows.Forms.Button(); this.SuspendLayout(); // // btnLeft // this.btnLeft.BackColor = System.Drawing.Color.Transparent; this.btnLeft.FlatAppearance.BorderSize = 0; this.btnLeft.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(20)))), ((int)(((byte)(20)))), ((int)(((byte)(20))))); this.btnLeft.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnLeft.Image = global::Mano.Properties.Resources.left_hand; this.btnLeft.Location = new System.Drawing.Point(40, 40); this.btnLeft.Name = "btnLeft"; this.btnLeft.Size = new System.Drawing.Size(200, 200); this.btnLeft.TabIndex = 0; this.btnLeft.UseVisualStyleBackColor = false; this.btnLeft.MouseDown += new System.Windows.Forms.MouseEventHandler(this.btnLeft_MouseDown); // // btnRight // this.btnRight.BackColor = System.Drawing.Color.Transparent; this.btnRight.FlatAppearance.BorderSize = 0; this.btnRight.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(20)))), ((int)(((byte)(20)))), ((int)(((byte)(20))))); this.btnRight.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnRight.Image = global::Mano.Properties.Resources.right_hand; this.btnRight.Location = new System.Drawing.Point(280, 40); this.btnRight.Name = "btnRight"; this.btnRight.Size = new System.Drawing.Size(200, 200); this.btnRight.TabIndex = 1; this.btnRight.UseVisualStyleBackColor = false; this.btnRight.MouseDown += new System.Windows.Forms.MouseEventHandler(this.btnRight_MouseDown); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.Black; this.ClientSize = new System.Drawing.Size(520, 280); this.Controls.Add(this.btnRight); this.Controls.Add(this.btnLeft); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Name = "Form1"; this.Opacity = 0.85D; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Form1"; this.TopMost = true; this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnLeft; private System.Windows.Forms.Button btnRight; } }
42.606742
161
0.591245
[ "MIT" ]
albertocc/Mano
Mano/Form.Designer.cs
3,794
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 Apache.Ignite.Core.Client.Services { /// <summary> /// Ignite distributed services client. /// </summary> public interface IServicesClient { /// <summary> /// Gets the cluster group for this <see cref="IServicesClient"/> instance. /// </summary> IClientClusterGroup ClusterGroup { get; } /// <summary> /// Gets a proxy for the service with the specified name. /// <para /> /// Note: service proxies are not "sticky" - there is no guarantee that all calls will be made to the same /// remote service instance. /// </summary> /// <typeparam name="T">Service type.</typeparam> /// <param name="serviceName">Service name.</param> /// <returns>Proxy object that forwards all member calls to a remote Ignite service.</returns> T GetServiceProxy<T>(string serviceName) where T : class; /// <summary> /// Returns an instance with binary mode enabled. /// Service method results will be kept in binary form. /// </summary> /// <returns>Instance with binary mode enabled.</returns> IServicesClient WithKeepBinary(); /// <summary> /// Returns an instance with server-side binary mode enabled. /// Service method arguments will be kept in binary form. /// </summary> /// <returns>Instance with server-side binary mode enabled.</returns> IServicesClient WithServerKeepBinary(); } }
41.392857
114
0.661777
[ "CC0-1.0" ]
10088/ignite
modules/platforms/dotnet/Apache.Ignite.Core/Client/Services/IServicesClient.cs
2,318
C#
using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using ICSharpCode.Decompiler.Metadata; namespace ICSharpCode.Decompiler.Tests { sealed class TestAssemblyResolver : UniversalAssemblyResolver { readonly HashSet<string> localAssemblies = new HashSet<string>(); public TestAssemblyResolver(string mainAssemblyFileName, string baseDir, string targetFramework) : base(mainAssemblyFileName, false, targetFramework, PEStreamOptions.PrefetchMetadata, MetadataReaderOptions.ApplyWindowsRuntimeProjections) { var assemblyNames = new DirectoryInfo(baseDir).EnumerateFiles("*.dll").Select(f => Path.GetFileNameWithoutExtension(f.Name)); foreach (var name in assemblyNames) { localAssemblies.Add(name); } } public override bool IsGacAssembly(IAssemblyReference reference) { return reference != null && !localAssemblies.Contains(reference.Name); } } }
31.645161
143
0.792049
[ "MIT" ]
LingxueFreeLab/ILSpy
ICSharpCode.Decompiler.Tests/TestAssemblyResolver.cs
983
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GenerateOthersBackground : MonoBehaviour { public int range = 4; public GameObject background1; public GameObject background2; public GameObject background3; public GameObject background4; void start (){ Instantiate (background1, transform.position, transform.rotation); } void OnTriggerExit2D(Collider2D coll){ if (coll.gameObject.tag == "BackgroundCollider") { int salut = Random.Range (1, range); if (salut == 1) Instantiate (background1, new Vector3(0, 25, 3), transform.rotation); if (salut == 2) Instantiate (background2, new Vector3(0, 25, 3), transform.rotation); if (salut == 3) Instantiate (background3, new Vector3(0, 25, 3), transform.rotation); if (salut == 4) Instantiate (background4, new Vector3(0, 25, 3), transform.rotation); } } }
23.102564
73
0.712542
[ "MIT" ]
DigitaruCamera/DNL
Danmaku_No_Loli_2018/Assets/Scripts/3DBackground/GenerateOthersBackground.cs
903
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SnakeGame")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SnakeGame")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("765FFF61-D44D-4E2C-A7C4-5C7D9297F2EE")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.6
84
0.740933
[ "MIT" ]
ABGEO07/snake-game
SnakeGame/Properties/AssemblyInfo.cs
1,354
C#
using System.Threading.Tasks; using System.Collections.Generic; using Refit; namespace Appmilla.Moneyhub.Refit.Identity { public interface IPayees { /// <summary> /// Retrieve all payees created by an API client /// </summary> /// <param name="limit">The total number of records to retrieve</param> /// <param name="offset">The offset at which to start retrieving records</param> /// <param name="userId">The user ID to query payees on</param> /// <param name="hasUserId">Determine if you want to return payees with user ID of not</param> /// <returns>Successful Payee Response</returns> [Get("/payees")] [Headers()] Task<PayeesGetAllResponse> PayeesGetAllAsync([Query][AliasAs("limit")] int? limit,[Query][AliasAs("offset")] int? offset,[Query][AliasAs("userId")] string userId,[Query][AliasAs("hasUserId")] bool? hasUserId); /// <summary> /// Create a payee /// </summary> /// <returns>Successful Payee Response</returns> [Post("/payees")] [Headers()] Task<PayeesCreateResponse> PayeesCreateAsync([Body][AliasAs("body")] PayeeCreateRequest payeeCreateRequest); /// <summary> /// Retrieve one payee created by an API client /// </summary> /// <param name="payeeId">The payee Id</param> /// <returns>Successful Payee Response</returns> [Get("/payees/{payeeId}")] [Headers()] Task<PayeesGetResponse> PayeesGetAsync([AliasAs("payeeId")] System.Guid payeeId); } }
40.717949
217
0.623426
[ "MIT" ]
Appmilla/moneyhub-api-client
Moneyhub.ApiClient/Moneyhub.ApiClient/Identity/Apis/Payees.cs
1,590
C#
// <auto-generated /> using System; using BookShop.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace BookShop.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.9") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("BookShop.Data.Models.ApplicationRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<DateTime?>("DeletedOn") .HasColumnType("datetime2"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<string>("Name") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("IsDeleted"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("BookShop.Data.Models.ApplicationUser", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("Address") .IsRequired() .HasColumnType("nvarchar(1000)") .HasMaxLength(1000) .IsUnicode(true); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<DateTime?>("DeletedOn") .HasColumnType("datetime2"); b.Property<string>("Email") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<string>("FullName") .IsRequired() .HasColumnType("nvarchar(100)") .HasMaxLength(100) .IsUnicode(true); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<string>("NormalizedEmail") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("IsDeleted"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("BookShop.Data.Models.Author", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<string>("FullName") .IsRequired() .HasColumnType("nvarchar(100)") .HasMaxLength(100) .IsUnicode(true); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.HasKey("Id"); b.ToTable("Authors"); }); modelBuilder.Entity("BookShop.Data.Models.AuthorBook", b => { b.Property<int>("BookId") .HasColumnType("int"); b.Property<int>("AuthorId") .HasColumnType("int"); b.HasKey("BookId", "AuthorId"); b.HasIndex("AuthorId"); b.ToTable("AuthorBooks"); }); modelBuilder.Entity("BookShop.Data.Models.Book", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Annotation") .IsRequired() .HasColumnType("nvarchar(1000)") .HasMaxLength(1000) .IsUnicode(true); b.Property<int>("Bought") .HasColumnType("int"); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<DateTime?>("DeletedOn") .HasColumnType("datetime2"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<string>("Isbn") .IsRequired() .HasColumnType("nchar(13)") .IsFixedLength(true) .HasMaxLength(13); b.Property<int>("Language") .HasColumnType("int"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(100)") .HasMaxLength(100) .IsUnicode(true); b.Property<int>("Pages") .HasColumnType("int"); b.Property<decimal>("Price") .HasColumnType("decimal(18,2)"); b.Property<int>("PublisherId") .HasColumnType("int"); b.Property<int>("Quantity") .HasColumnType("int"); b.Property<int>("YearOfIssue") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("IsDeleted"); b.HasIndex("PublisherId"); b.ToTable("Books"); }); modelBuilder.Entity("BookShop.Data.Models.BookCategory", b => { b.Property<int>("BookId") .HasColumnType("int"); b.Property<int>("CategoryId") .HasColumnType("int"); b.HasKey("BookId", "CategoryId"); b.HasIndex("CategoryId"); b.ToTable("BookCategories"); }); modelBuilder.Entity("BookShop.Data.Models.Cart", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("BookId") .HasColumnType("int"); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<DateTime?>("DeletedOn") .HasColumnType("datetime2"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<int?>("PurchaseId") .HasColumnType("int"); b.Property<int>("Quantity") .HasColumnType("int"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("BookId"); b.HasIndex("IsDeleted"); b.HasIndex("PurchaseId"); b.HasIndex("UserId"); b.ToTable("Carts"); }); modelBuilder.Entity("BookShop.Data.Models.Category", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(100)") .HasMaxLength(100) .IsUnicode(true); b.HasKey("Id"); b.ToTable("Categories"); }); modelBuilder.Entity("BookShop.Data.Models.Comment", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("BookId") .HasColumnType("int"); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<DateTime?>("DeletedOn") .HasColumnType("datetime2"); b.Property<string>("Description") .IsRequired() .HasColumnType("nvarchar(300)") .HasMaxLength(300) .IsUnicode(true); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("BookId"); b.HasIndex("IsDeleted"); b.HasIndex("UserId"); b.ToTable("Comments"); }); modelBuilder.Entity("BookShop.Data.Models.Photo", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("BookId") .HasColumnType("int"); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<DateTime?>("DeletedOn") .HasColumnType("datetime2"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<string>("PublicId") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Url") .IsRequired() .HasColumnType("nvarchar(1000)") .HasMaxLength(1000); b.HasKey("Id"); b.HasIndex("BookId"); b.HasIndex("IsDeleted"); b.ToTable("Photos"); }); modelBuilder.Entity("BookShop.Data.Models.Publisher", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(100)") .HasMaxLength(100) .IsUnicode(true); b.HasKey("Id"); b.ToTable("Publishers"); }); modelBuilder.Entity("BookShop.Data.Models.Purchase", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("Purchases"); }); modelBuilder.Entity("BookShop.Data.Models.Setting", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<DateTime?>("DeletedOn") .HasColumnType("datetime2"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("ModifiedOn") .HasColumnType("datetime2"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("IsDeleted"); b.ToTable("Settings"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("nvarchar(450)"); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(450)"); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(450)"); b.Property<string>("Name") .HasColumnType("nvarchar(450)"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("BookShop.Data.Models.AuthorBook", b => { b.HasOne("BookShop.Data.Models.Author", "Author") .WithMany("AuthorBooks") .HasForeignKey("AuthorId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("BookShop.Data.Models.Book", "Book") .WithMany("AuthorBooks") .HasForeignKey("BookId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("BookShop.Data.Models.Book", b => { b.HasOne("BookShop.Data.Models.Publisher", "Publisher") .WithMany("Books") .HasForeignKey("PublisherId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("BookShop.Data.Models.BookCategory", b => { b.HasOne("BookShop.Data.Models.Book", "Book") .WithMany("BookCategories") .HasForeignKey("BookId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("BookShop.Data.Models.Category", "Category") .WithMany("BookCategories") .HasForeignKey("CategoryId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("BookShop.Data.Models.Cart", b => { b.HasOne("BookShop.Data.Models.Book", "Book") .WithMany("Carts") .HasForeignKey("BookId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("BookShop.Data.Models.Purchase", null) .WithMany("Cart") .HasForeignKey("PurchaseId"); b.HasOne("BookShop.Data.Models.ApplicationUser", "User") .WithMany("Cart") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("BookShop.Data.Models.Comment", b => { b.HasOne("BookShop.Data.Models.Book", "Book") .WithMany("Comments") .HasForeignKey("BookId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("BookShop.Data.Models.ApplicationUser", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("BookShop.Data.Models.Photo", b => { b.HasOne("BookShop.Data.Models.Book", "Book") .WithMany("Photos") .HasForeignKey("BookId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("BookShop.Data.Models.Purchase", b => { b.HasOne("BookShop.Data.Models.ApplicationUser", "User") .WithMany("Purchases") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("BookShop.Data.Models.ApplicationRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("BookShop.Data.Models.ApplicationUser", null) .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("BookShop.Data.Models.ApplicationUser", null) .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("BookShop.Data.Models.ApplicationRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("BookShop.Data.Models.ApplicationUser", null) .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("BookShop.Data.Models.ApplicationUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); #pragma warning restore 612, 618 } } }
36.654762
125
0.437949
[ "MIT" ]
SvetoslavIT/BookShop
Data/BookShop.Data/Migrations/ApplicationDbContextModelSnapshot.cs
27,713
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 application-insights-2018-11-25.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.ApplicationInsights { /// <summary> /// Configuration for accessing Amazon ApplicationInsights service /// </summary> public partial class AmazonApplicationInsightsConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.3.101.35"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonApplicationInsightsConfig() { this.AuthenticationServiceName = "applicationinsights"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "applicationinsights"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2018-11-25"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
27.1
118
0.601476
[ "Apache-2.0" ]
tap4fun/aws-sdk-net
sdk/src/Services/ApplicationInsights/Generated/AmazonApplicationInsightsConfig.cs
2,168
C#
using App.Domain.Entidades; using App.Domain.ObjetosDeValor; using App.Forms.Enum; using App.Forms.Forms.Dialog; using App.Forms.Forms.Pesquisa; using App.Infra; using App.Infra.Repositorios; using System; using System.Windows.Forms; namespace App.Forms.Forms.Cadastro { public partial class FormCadastroVeiculo : App.Forms.Forms.Base.Add.FormBaseCadastro { static UnitOfWork unitOfWork = new UnitOfWork(); RepositorioVeiculo repositorio = new RepositorioVeiculo(unitOfWork); RepositorioCidade repositorioCidade = new RepositorioCidade(unitOfWork); RepositorioPessoa repositorioPessoa = new RepositorioPessoa(unitOfWork); RepositorioMarca repositorioMarca = new RepositorioMarca(unitOfWork); Veiculo entidade = new Veiculo(); Marca marca = new Marca(); Pessoa pessoa = new Pessoa(); Cidade cidade = new Cidade(); public FormCadastroVeiculo(AcaoForm acaoForm, int id = 0) { this.acaoForm = acaoForm; this.id = id; InitializeComponent(); txtEspecie.DataSource = System.Enum.GetValues(typeof(VeiculoEspecie)); txtCategoria.DataSource = System.Enum.GetValues(typeof(VeiculoCategoria)); txtLicenciamento.DataSource = System.Enum.GetValues(typeof(VecimentoLicenciamento)); } private void FormCadastroVeiculo_Load(object sender, EventArgs e) { if (acaoForm == AcaoForm.Add) { this.Text = "Incluindo novo Veiculo"; SolicitarPlaca(); } if (acaoForm == AcaoForm.Update) this.Text = "Editando Veiculo [ " + id + " ]"; } void SolicitarPlaca() { this.Visible = false; this.Update(); FormInput input = new FormInput("ENTRE COM A PLACA", "Digite a Placa para o novo cadastro"); input.ShowDialog(); if(input.result == DialogResult.OK) { VerificarExistencia(input.Value); txtPlaca.Text = input.Value; this.Visible = true; } else { PerguntarParaSair = false; this.Close(); } } void VerificarExistencia(string placa) { if (repositorio.IsExist(p => p.Placa.Valor == placa && p.Ativo == true)) { DialogResult result = MessageBox.Show("Já Existe um veiculo com esta placa ativo no sistema, desativa-lo e atualizar dados ?", "Erro", MessageBoxButtons.YesNo, MessageBoxIcon.Error); if (result == DialogResult.Yes) { Veiculo v = repositorio.GetOne(p => p.Placa.Valor == placa && p.Ativo == true); if (v != null) { entidade = v; marca = v.Marca; cidade = v.Endereco.Cidade; PreencherForm(); v.Ativo = false; repositorio.Update(v); repositorio.Save(); entidade.NomeProprietarioAnterior = v.Pessoa.Nome; entidade.CpfCnpjProprietarioAnterior = v.Pessoa.CpfCnpj; txtNomePropAnterior.Text = v.Pessoa.Nome; txtCpfCnpjPropAnterior.Text = v.Pessoa.CpfCnpj; txtValorCompra.Clear(); txtNumeroNotaCompra.Clear(); txtDataCompra.Clear(); txtEnderecoLogradouro.Clear(); txtEnderecoBairro.Clear(); txtEnderecoCaixaPostal.Clear(); txtEnderecoComplemento.Clear(); txtEnderecoNumero.Clear(); } } } } public override bool add() { if (entidade.IsInvalid()) { Erros = false; ShowErros(entidade.Notifications); return false; } //essa parte do código tem que ser no repositório e não no form else if (repositorio.IsExist(p => p.Placa.Valor == entidade.Placa.Valor && p.Ativo == true)) { MessageBox.Show("Já Existe um veiculo com esta placa ativo no sistema", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); Erros = false; return false; } else return repositorio.Add(entidade); } public override bool update() { repositorio.ClearNotifications(); if (entidade == null) return false; if (entidade.IsInvalid()) { Erros = false; ShowErros(entidade.Notifications); return false; } bool retorno = repositorio.Update(entidade); if (repositorio.IsInvalid()) { Erros = false; ShowErros(repositorio.Notifications); return false; } else { Erros = true; return retorno; } } public override bool CarregarEntidadeDoBanco() { entidade = repositorio.GetOne(p => p.VeiculoId == id); cidade = entidade.Endereco.Cidade; pessoa = entidade.Pessoa; marca = entidade.Marca; if (entidade == null) return false; else { PreencherForm(); return true; } } public override void Save() { repositorio.Save(); } public override void CarregarEntidadeDoForm() { entidade.ClearNotifications(); entidade.Endereco.ClearNotifications(); cidade.SetValidations(); pessoa.SetValidations(); marca.SetValidations(); Placa placa = new Placa(txtPlaca.Text, TipoPlaca.Comum); Endereco endereco = new Endereco(txtEnderecoLogradouro.Text.ToUpper().Trim(), txtEnderecoNumero.Text.ToUpper().Trim(), cidade, txtEnderecoBairro.Text.ToUpper().Trim(), txtEnderecoComplemento.Text.ToUpper().Trim(), txtEnderecoCEP.Text.ToUpper().Trim(), txtEnderecoCaixaPostal.Text.ToUpper().Trim()); VeiculoCategoria categoria = (VeiculoCategoria)txtCategoria.SelectedItem; VeiculoEspecie especie = (VeiculoEspecie)txtEspecie.SelectedItem; VecimentoLicenciamento licenciamento = (VecimentoLicenciamento)txtLicenciamento.SelectedItem; entidade.SetValues(placa, txtRenavam.Text.ToUpper().Trim(), txtChassi.Text.ToUpper().Trim(), txtMotor.Text.ToUpper().Trim(), txtAnoFab.Text.ToUpper().Trim(), txtAnoMod.Text.ToUpper().Trim(), txtDescricaoModelo.Text.ToUpper().Trim(), txtEspelho.Text.ToUpper().Trim(), txtCombustivel.Text.ToUpper().Trim(), txtCor.Text.ToUpper().Trim(), categoria, especie, licenciamento, endereco, pessoa, marca, metroCheckBox1.Checked, txtNomePropAnterior.Text.Trim().ToUpper(), txtCpfCnpjPropAnterior.Text.Trim().ToUpper(), txtDataCompra.Text.Trim().ToUpper().ToUpper(), txtValorCompra.Text.Trim().ToUpper(), txtNumeroNotaCompra.Text.Trim().ToUpper()); entidade.NomeComprador = txtCompradorNome.Text.Trim().ToUpper(); entidade.CpfCnpjComprador = txtCompradorCpfCnpj.Text.Trim().ToUpper(); entidade.DataVenda = txtCompradorData.Text.Trim().ToUpper(); entidade.ValorVenda = txtCompradorValor.Text.Trim().ToUpper(); } public override void PreencherForm() { txtPlaca.Text = entidade.Placa.Valor; txtRenavam.Text = entidade.Renavam; txtChassi.Text = entidade.Renavam; txtMotor.Text = entidade.Motor; txtAnoFab.Text = entidade.AnoFab; txtAnoMod.Text = entidade.AnoModelo; txtDescricaoModelo.Text = entidade.DescricaoModelo; txtEspelho.Text = entidade.Espelho; txtCombustivel.Text = entidade.Combustivel; txtCor.Text = entidade.Cor; txtCategoria.SelectedItem = entidade.Categoria; txtEspecie.SelectedItem = entidade.Especie; txtLicenciamento.SelectedItem = entidade.Licenciamento; txtEnderecoLogradouro.Text = entidade.Endereco.Logradouro; txtEnderecoNumero.Text = entidade.Endereco.Numero; txtEnderecoBairro.Text = entidade.Endereco.Bairro; txtEnderecoComplemento.Text = entidade.Endereco.Complemento; txtEnderecoCEP.Text = entidade.Endereco.Cep; txtEnderecoCaixaPostal.Text = entidade.Endereco.CaixaPostal; metroCheckBox1.Checked = entidade.Ativo; txtNomePropAnterior.Text = entidade.NomeProprietarioAnterior; txtCpfCnpjPropAnterior.Text = entidade.CpfCnpjProprietarioAnterior; txtDataCompra.Text = entidade.DataDaCompra; txtValorCompra.Text = entidade.ValorDaCompra; txtNumeroNotaCompra.Text = entidade.NumeroDaNotaDeCompra; txtCompradorNome.Text = entidade.NomeComprador; txtCompradorValor.Text = entidade.ValorVenda; txtCompradorData.Text = entidade.DataVenda; txtCompradorCpfCnpj.Text = entidade.CpfCnpjComprador; if (cidade != null) txtEnderecoCidade.Text = cidade.Nome + "-" + cidade.Uf; if (marca != null) txtMarca.Text = marca.Nome; if (pessoa != null) { txtProprietario.Text = pessoa.Nome; txtCpfCnpj.Text = pessoa.CpfCnpj; } } private void btSelecionarCidade_Click_1(object sender, EventArgs e) { FormPesquisaCidade form = new FormPesquisaCidade(); form.ShowDialog(); if (form.Id_selecionado > 0) { repositorioCidade = new RepositorioCidade(unitOfWork); repositorioCidade.ClearNotifications(); cidade = repositorioCidade.GetOne(p => p.CidadeId == form.Id_selecionado); txtEnderecoCidade.Text = cidade.Nome + "-" + cidade.Uf; if (repositorioCidade.IsInvalid()) { Erros = true; ShowErros(repositorio.Notifications); } } else { cidade = new Cidade(); txtEnderecoCidade.Clear(); } } private void metroButton1_Click_1(object sender, EventArgs e) { FormPesquisaPessoa form = new FormPesquisaPessoa(); form.ShowDialog(); if (form.Id_selecionado > 0) { repositorioPessoa = new RepositorioPessoa(unitOfWork); repositorioPessoa.ClearNotifications(); pessoa = repositorioPessoa.GetOne(p => p.PessoaId == form.Id_selecionado); txtProprietario.Text = pessoa.Nome; txtCpfCnpj.Text = pessoa.CpfCnpj; metroButton3.Enabled = true; if (repositorioPessoa.IsInvalid()) { Erros = true; ShowErros(repositorio.Notifications); } } else { pessoa = new Pessoa(); txtProprietario.Clear(); txtCpfCnpj.Clear(); metroButton3.Enabled = false; } } private void metroButton2_Click(object sender, EventArgs e) { FormPresquisaMarca form = new FormPresquisaMarca(); form.ShowDialog(); if (form.Id_selecionado > 0) { repositorioMarca = new RepositorioMarca(unitOfWork); repositorioMarca.ClearNotifications(); marca = repositorioMarca.GetOne(p => p.MarcaId == form.Id_selecionado); txtMarca.Text = marca.Nome; if (repositorioPessoa.IsInvalid()) { Erros = true; ShowErros(repositorio.Notifications); } } else { marca = new Marca(); txtMarca.Clear(); } } private void metroPanel1_Paint(object sender, PaintEventArgs e) { } void UsarEnderecoProprietarioNoVeiculo() { if (pessoa != null) { txtEnderecoLogradouro.Text = pessoa.Endereco.Logradouro; txtEnderecoNumero.Text = pessoa.Endereco.Numero; txtEnderecoBairro.Text = pessoa.Endereco.Bairro; txtEnderecoComplemento.Text = pessoa.Endereco.Complemento; txtEnderecoCEP.Text = pessoa.Endereco.Cep; txtEnderecoCaixaPostal.Text = pessoa.Endereco.CaixaPostal; cidade = pessoa.Endereco.Cidade; if (cidade != null) txtEnderecoCidade.Text = cidade.Nome + "-" + cidade.Uf; } } private void chkEnderecoPropToVeiculo_CheckedChanged(object sender, EventArgs e) { } private void metroButton3_Click_1(object sender, EventArgs e) { UsarEnderecoProprietarioNoVeiculo(); } private void txtValorCompra_Leave(object sender, EventArgs e) { txtValorCompra.Text = txtValorCompra.Text.Replace(",", "").Replace(".", "").Replace(" ","").Replace("R$",""); if(txtValorCompra.Text.Length > 0) txtValorCompra.Text = Convert.ToDouble(txtValorCompra.Text).ToString("C"); } private void txtCpfCnpjPropAnterior_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsDigit(e.KeyChar) && e.KeyChar != (char)8 && e.KeyChar != (char)Keys.Delete) { e.Handled = true; } } private void txtValorCompra_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsDigit(e.KeyChar) && e.KeyChar != (char)8 && e.KeyChar != (char)Keys.Delete) { e.Handled = true; } } private void metroLabel18_Click(object sender, EventArgs e) { } private void txtValorCompra_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { } private void txtCompradorValor_Leave(object sender, EventArgs e) { txtCompradorValor.Text = txtCompradorValor.Text.Replace(",", "").Replace(".", "").Replace(" ", "").Replace("R$", ""); if (txtCompradorValor.Text.Length > 0) txtCompradorValor.Text = Convert.ToDouble(txtCompradorValor.Text).ToString("C"); } private void txtCompradorValor_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsDigit(e.KeyChar) && e.KeyChar != (char)8 && e.KeyChar != (char)Keys.Delete) { e.Handled = true; } } private void txtCompradorCpfCnpj_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsDigit(e.KeyChar) && e.KeyChar != (char)8 && e.KeyChar != (char)Keys.Delete) { e.Handled = true; } } private void metroTabPage1_Click(object sender, EventArgs e) { } } }
38.736077
310
0.547318
[ "MIT" ]
toandriottibertoni/despachante-veiculos
App/App.Forms/Forms/Cadastro/FormCadastroVeiculo.cs
16,005
C#
using System.Net.Http; using System.Security.Claims; using System.Web.Http; using Microsoft.Owin.Security; using Web.Constants; namespace Web.Controllers { [Authorize, Route(RoutePatterns.Token, Name = RouteNames.Token)] public sealed class TokenController : ApiController { public IHttpActionResult Get(string returnUrl) { if (string.IsNullOrEmpty(returnUrl)) { this.ModelState.AddModelError("returnUrl", Properties.Resources.Required); return this.BadRequest(this.ModelState); } var email = ((ClaimsPrincipal)User).FindFirst(ClaimTypes.Email); if (email == null) { this.ModelState.AddModelError("email", Properties.Resources.Required); return this.BadRequest(this.ModelState); } return this.IssueChallenge(new AuthenticationProperties() { RedirectUri = returnUrl }); } public IHttpActionResult Post() { return this.IssueChallenge(new AuthenticationProperties() { AllowRefresh = true }); } private IHttpActionResult IssueChallenge(AuthenticationProperties props) { this.Request.GetOwinContext().Authentication.Challenge( props, OAuth2Config.OAuthBearerOptions.AuthenticationType); return this.Unauthorized(); } } }
32.244444
99
0.620951
[ "MIT" ]
akornatskyy/oauth2-social-net
src/Web/Controllers/TokenController.cs
1,453
C#
//----------------------------------------------------------------------- // <copyright file="MemberAliasPropertyInfo.cs" company="Sirenix IVS"> // Copyright (c) 2018 Sirenix IVS // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- namespace XamExporter.Utilities { using System; using System.Globalization; using System.Reflection; /// <summary> /// Provides a methods of representing imaginary properties which are unique to serialization. /// <para /> /// We aggregate the PropertyInfo associated with this member and return a mangled form of the name. /// </summary> /// <seealso cref="System.Reflection.FieldInfo" /> public sealed class MemberAliasPropertyInfo : PropertyInfo { /// <summary> /// The default fake name separator string. /// </summary> private const string FakeNameSeparatorString = "+"; private PropertyInfo aliasedProperty; private string mangledName; /// <summary> /// Initializes a new instance of the <see cref="MemberAliasPropertyInfo"/> class. /// </summary> /// <param name="prop">The property to alias.</param> /// <param name="namePrefix">The name prefix to use.</param> public MemberAliasPropertyInfo(PropertyInfo prop, string namePrefix) { this.aliasedProperty = prop; this.mangledName = string.Concat(namePrefix, FakeNameSeparatorString, this.aliasedProperty.Name); } /// <summary> /// Initializes a new instance of the <see cref="MemberAliasPropertyInfo"/> class. /// </summary> /// <param name="prop">The property to alias.</param> /// <param name="namePrefix">The name prefix to use.</param> /// <param name="separatorString">The separator string to use.</param> public MemberAliasPropertyInfo(PropertyInfo prop, string namePrefix, string separatorString) { this.aliasedProperty = prop; this.mangledName = string.Concat(namePrefix, separatorString, this.aliasedProperty.Name); } /// <summary> /// The backing PropertyInfo that is being aliased. /// </summary> public PropertyInfo AliasedProperty { get { return this.aliasedProperty; } } /// <summary> /// Gets the module in which the type that declares the member represented by the current <see cref="T:System.Reflection.MemberInfo" /> is defined. /// </summary> public override Module Module { get { return this.aliasedProperty.Module; } } /// <summary> /// Gets a value that identifies a metadata element. /// </summary> public override int MetadataToken { get { return this.aliasedProperty.MetadataToken; } } /// <summary> /// Gets the name of the current member. /// </summary> public override string Name { get { return this.mangledName; } } /// <summary> /// Gets the class that declares this member. /// </summary> public override Type DeclaringType { get { return this.aliasedProperty.DeclaringType; } } /// <summary> /// Gets the class object that was used to obtain this instance of MemberInfo. /// </summary> public override Type ReflectedType { get { return this.aliasedProperty.ReflectedType; } } /// <summary> /// Gets the type of the property. /// </summary> /// <value> /// The type of the property. /// </value> public override Type PropertyType { get { return this.aliasedProperty.PropertyType; } } /// <summary> /// Gets the attributes. /// </summary> /// <value> /// The attributes. /// </value> public override PropertyAttributes Attributes { get { return this.aliasedProperty.Attributes; } } /// <summary> /// Gets a value indicating whether this instance can read. /// </summary> /// <value> /// <c>true</c> if this instance can read; otherwise, <c>false</c>. /// </value> public override bool CanRead { get { return this.aliasedProperty.CanRead; } } /// <summary> /// Gets a value indicating whether this instance can write. /// </summary> /// <value> /// <c>true</c> if this instance can write; otherwise, <c>false</c>. /// </value> public override bool CanWrite { get { return this.aliasedProperty.CanWrite; } } /// <summary> /// When overridden in a derived class, returns an array of all custom attributes applied to this member. /// </summary> /// <param name="inherit">True to search this member's inheritance chain to find the attributes; otherwise, false. This parameter is ignored for properties and events; see Remarks.</param> /// <returns> /// An array that contains all the custom attributes applied to this member, or an array with zero elements if no attributes are defined. /// </returns> public override object[] GetCustomAttributes(bool inherit) { return this.aliasedProperty.GetCustomAttributes(inherit); } /// <summary> /// When overridden in a derived class, returns an array of custom attributes applied to this member and identified by <see cref="T:System.Type" />. /// </summary> /// <param name="attributeType">The type of attribute to search for. Only attributes that are assignable to this type are returned.</param> /// <param name="inherit">True to search this member's inheritance chain to find the attributes; otherwise, false. This parameter is ignored for properties and events; see Remarks.</param> /// <returns> /// An array of custom attributes applied to this member, or an array with zero elements if no attributes assignable to <paramref name="attributeType" /> have been applied. /// </returns> public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return this.aliasedProperty.GetCustomAttributes(attributeType, inherit); } /// <summary> /// When overridden in a derived class, indicates whether one or more attributes of the specified type or of its derived types is applied to this member. /// </summary> /// <param name="attributeType">The type of custom attribute to search for. The search includes derived types.</param> /// <param name="inherit">True to search this member's inheritance chain to find the attributes; otherwise, false. This parameter is ignored for properties and events; see Remarks.</param> /// <returns> /// True if one or more instances of <paramref name="attributeType" /> or any of its derived types is applied to this member; otherwise, false. /// </returns> public override bool IsDefined(Type attributeType, bool inherit) { return this.aliasedProperty.IsDefined(attributeType, inherit); } /// <summary> /// Returns an array whose elements reflect the public and, if specified, non-public get, set, and other accessors of the property reflected by the current instance. /// </summary> /// <param name="nonPublic">Indicates whether non-public methods should be returned in the MethodInfo array. true if non-public methods are to be included; otherwise, false.</param> /// <returns> /// An array of <see cref="T:System.Reflection.MethodInfo" /> objects whose elements reflect the get, set, and other accessors of the property reflected by the current instance. If <paramref name="nonPublic" /> is true, this array contains public and non-public get, set, and other accessors. If <paramref name="nonPublic" /> is false, this array contains only public get, set, and other accessors. If no accessors with the specified visibility are found, this method returns an array with zero (0) elements. /// </returns> public override MethodInfo[] GetAccessors(bool nonPublic) { return this.aliasedProperty.GetAccessors(nonPublic); } /// <summary> /// When overridden in a derived class, returns the public or non-public get accessor for this property. /// </summary> /// <param name="nonPublic">Indicates whether a non-public get accessor should be returned. true if a non-public accessor is to be returned; otherwise, false.</param> /// <returns> /// A MethodInfo object representing the get accessor for this property, if <paramref name="nonPublic" /> is true. Returns null if <paramref name="nonPublic" /> is false and the get accessor is non-public, or if <paramref name="nonPublic" /> is true but no get accessors exist. /// </returns> public override MethodInfo GetGetMethod(bool nonPublic) { return this.aliasedProperty.GetGetMethod(nonPublic); } /// <summary> /// Gets the index parameters of the property. /// </summary> /// <returns>The index parameters of the property.</returns> public override ParameterInfo[] GetIndexParameters() { return this.aliasedProperty.GetIndexParameters(); } /// <summary> /// When overridden in a derived class, returns the set accessor for this property. /// </summary> /// <param name="nonPublic">Indicates whether the accessor should be returned if it is non-public. true if a non-public accessor is to be returned; otherwise, false.</param> /// <returns> /// Value Condition A <see cref="T:System.Reflection.MethodInfo" /> object representing the Set method for this property. The set accessor is public.-or- <paramref name="nonPublic" /> is true and the set accessor is non-public. null<paramref name="nonPublic" /> is true, but the property is read-only.-or- <paramref name="nonPublic" /> is false and the set accessor is non-public.-or- There is no set accessor. /// </returns> public override MethodInfo GetSetMethod(bool nonPublic) { return this.aliasedProperty.GetSetMethod(nonPublic); } /// <summary> /// Gets the value of the property on the given instance. /// </summary> /// <param name="obj">The object to invoke the getter on.</param> /// <param name="invokeAttr">The <see cref="BindingFlags"/> to invoke with.</param> /// <param name="binder">The binder to use.</param> /// <param name="index">The indices to use.</param> /// <param name="culture">The culture to use.</param> /// <returns>The value of the property on the given instance.</returns> public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) { return this.aliasedProperty.GetValue(obj, invokeAttr, binder, index, culture); } /// <summary> /// Sets the value of the property on the given instance. /// </summary> /// <param name="obj">The object to set the value on.</param> /// <param name="value">The value to set.</param> /// <param name="invokeAttr">The <see cref="BindingFlags"/> to invoke with.</param> /// <param name="binder">The binder to use.</param> /// <param name="index">The indices to use.</param> /// <param name="culture">The culture to use.</param> public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) { this.aliasedProperty.SetValue(obj, value, invokeAttr, binder, index, culture); } } }
52.472574
516
0.638308
[ "Apache-2.0" ]
johnbrandle/odin-serializer
OdinSerializer/Utilities/Misc/MemberAliasPropertyInfo.cs
12,438
C#
using System; using System.Threading.Tasks; using Baseline.Dates; using Jasper.Logging; using Microsoft.Extensions.Hosting; namespace Jasper.Tracking { public static class JasperHostMessageTrackingExtensions { internal static MessageTrackingLogger GetTrackingLogger(this IHost host) { var logger = host.Get<IMessageLogger>() as MessageTrackingLogger; if (logger == null) { throw new InvalidOperationException($"The {nameof(MessageTrackingExtension)} extension is not configured for this application"); } return logger; } /// <summary> /// Advanced usage of the 'ExecuteAndWait()' message tracking and coordination for automated testing. /// Use this configuration if you want to coordinate message tracking across multiple Jasper /// applications running in the same process /// </summary> /// <param name="host"></param> /// <returns></returns> public static TrackedSessionConfiguration TrackActivity(this IHost host) { var session = new TrackedSession(host); return new TrackedSessionConfiguration(session); } public static TrackedSessionConfiguration TrackActivity(this IHost host, TimeSpan trackingTimeout) { var session = new TrackedSession(host); session.Timeout = trackingTimeout; return new TrackedSessionConfiguration(session); } /// <summary> /// Send a message through the service bus and wait until that message /// and all cascading messages have been successfully processed /// </summary> /// <param name="host"></param> /// <param name="message"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> public static Task<ITrackedSession> SendMessageAndWait<T>(this IHost host, T message, int timeoutInMilliseconds = 5000) { return host.ExecuteAndWait(c => c.Send(message), timeoutInMilliseconds); } /// <summary> /// Invoke the given message and wait until all cascading messages /// have completed /// </summary> /// <param name="runtime"></param> /// <param name="action"></param> /// <returns></returns> public static Task<ITrackedSession> InvokeMessageAndWait(this IHost host, object message, int timeoutInMilliseconds = 5000) { return host.ExecuteAndWait(c => c.Invoke(message), timeoutInMilliseconds); } /// <summary> /// Executes an action and waits until the execution of all messages and all cascading messages /// have completed /// </summary> /// <param name="runtime"></param> /// <param name="action"></param> /// <returns></returns> public static Task<ITrackedSession> ExecuteAndWait(this IHost host, Func<Task> action, int timeoutInMilliseconds = 5000) { return host.ExecuteAndWait(c => action(), timeoutInMilliseconds); } /// <summary> /// Executes an action and waits until the execution of all messages and all cascading messages /// have completed /// </summary> /// <param name="runtime"></param> /// <param name="action"></param> /// <returns></returns> public static async Task<ITrackedSession> ExecuteAndWait(this IHost host, Func<IExecutionContext, Task> action, int timeoutInMilliseconds = 5000) { TrackedSession session = new TrackedSession(host) { Timeout = timeoutInMilliseconds.Milliseconds(), Execution = action }; await session.ExecuteAndTrack(); return session; } } }
36.981481
144
0.595643
[ "MIT" ]
JasperFx/jasper
src/Jasper/Tracking/JasperHostMessageTrackingExtensions.cs
3,994
C#
using System; using AsmResolver.DotNet.Code; using AsmResolver.DotNet.Code.Cil; using AsmResolver.PE.DotNet.Cil; using AsmResolver.PE.DotNet.Metadata.Tables; using AsmResolver.PE.DotNet.Metadata.Tables.Rows; namespace AsmResolver.DotNet.Serialized { /// <summary> /// Provides a default implementation of a <see cref="IMethodBodyReader"/>, which reads CIL method bodies using the /// <see cref="CilRawMethodBody"/> class. /// </summary> public class DefaultMethodBodyReader : IMethodBodyReader { /// <inheritdoc /> public MethodBody ReadMethodBody(ModuleReaderContext context, MethodDefinition owner, in MethodDefinitionRow row) { try { if (row.Body.CanRead) { if (owner.IsIL) { var reader = row.Body.CreateReader(); var rawBody = CilRawMethodBody.FromReader(context, ref reader); return CilMethodBody.FromRawMethodBody(context, owner, rawBody); } else { context.NotSupported($"Body of method {owner.MetadataToken} is native and unbounded which is not supported."); // TODO: handle native method bodies. } } else if (row.Body.IsBounded && row.Body.GetSegment() is CilRawMethodBody rawMethodBody) { return CilMethodBody.FromRawMethodBody(context, owner, rawMethodBody); } } catch (Exception ex) { context.RegisterException(new BadImageFormatException($"Failed to parse the method body of {owner.MetadataToken}.", ex)); } return null; } } }
37.897959
137
0.561659
[ "MIT" ]
Anonym0ose/AsmResolver
src/AsmResolver.DotNet/Serialized/DefaultMethodBodyReader.cs
1,857
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Microsoft.AppCenter.Ingestion.Models; using Newtonsoft.Json; namespace Microsoft.AppCenter.Crashes.Ingestion.Models { /// <summary> /// Abstract error log. /// </summary> public class AbstractErrorLog : Log { /// <summary> /// Initializes a new instance of the AbstractErrorLog class. /// </summary> public AbstractErrorLog() { } /// <summary> /// Initializes a new instance of the AbstractErrorLog class. /// </summary> /// <param name="id">Error identifier.</param> /// <param name="processId">Process identifier.</param> /// <param name="processName">Process name.</param> /// <param name="fatal">If true, this error report is an application /// crash. /// Corresponds to the number of milliseconds elapsed between the time /// the error occurred and the app was launched.</param> /// <param name="timestamp">Log timestamp, example: /// '2017-03-13T18:05:42Z'. /// </param> /// <param name="sid">When tracking an analytics session, logs can be /// part of the session by specifying this identifier. /// This attribute is optional, a missing value means the session /// tracking is disabled (like when using only error reporting /// feature). /// Concrete types like StartSessionLog or PageLog are always part of a /// session and always include this identifier. /// </param> /// <param name="userId">optional string used for associating logs with /// users. /// </param> /// <param name="parentProcessId">Parent's process identifier.</param> /// <param name="parentProcessName">Parent's process name.</param> /// <param name="errorThreadId">Error thread identifier.</param> /// <param name="errorThreadName">Error thread name.</param> /// <param name="appLaunchTimestamp">Timestamp when the app was /// launched, example: '2017-03-13T18:05:42Z'. /// </param> /// <param name="architecture">CPU architecture.</param> public AbstractErrorLog(Microsoft.AppCenter.Ingestion.Models.Device device, System.Guid id, int processId, string processName, bool fatal, System.DateTime? timestamp = default(System.DateTime?), System.Guid? sid = default(System.Guid?), string userId = default(string), int? parentProcessId = default(int?), string parentProcessName = default(string), long? errorThreadId = default(long?), string errorThreadName = default(string), System.DateTime? appLaunchTimestamp = default(System.DateTime?), string architecture = default(string)) : base(device, timestamp, sid, userId) { Id = id; ProcessId = processId; ProcessName = processName; ParentProcessId = parentProcessId; ParentProcessName = parentProcessName; ErrorThreadId = errorThreadId; ErrorThreadName = errorThreadName; Fatal = fatal; AppLaunchTimestamp = appLaunchTimestamp; Architecture = architecture; } /// <summary> /// Gets or sets error identifier. /// </summary> [JsonProperty(PropertyName = "id")] public System.Guid Id { get; set; } /// <summary> /// Gets or sets process identifier. /// </summary> [JsonProperty(PropertyName = "processId")] public int ProcessId { get; set; } /// <summary> /// Gets or sets process name. /// </summary> [JsonProperty(PropertyName = "processName")] public string ProcessName { get; set; } /// <summary> /// Gets or sets parent's process identifier. /// </summary> [JsonProperty(PropertyName = "parentProcessId")] public int? ParentProcessId { get; set; } /// <summary> /// Gets or sets parent's process name. /// </summary> [JsonProperty(PropertyName = "parentProcessName")] public string ParentProcessName { get; set; } /// <summary> /// Gets or sets error thread identifier. /// </summary> [JsonProperty(PropertyName = "errorThreadId")] public long? ErrorThreadId { get; set; } /// <summary> /// Gets or sets error thread name. /// </summary> [JsonProperty(PropertyName = "errorThreadName")] public string ErrorThreadName { get; set; } /// <summary> /// Gets or sets if true, this error report is an application crash. /// Corresponds to the number of milliseconds elapsed between the time /// the error occurred and the app was launched. /// </summary> [JsonProperty(PropertyName = "fatal")] public bool Fatal { get; set; } /// <summary> /// Gets or sets timestamp when the app was launched, example: /// '2017-03-13T18:05:42Z'. /// /// </summary> [JsonProperty(PropertyName = "appLaunchTimestamp")] public System.DateTime? AppLaunchTimestamp { get; set; } /// <summary> /// Gets or sets CPU architecture. /// </summary> [JsonProperty(PropertyName = "architecture")] public string Architecture { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public override void Validate() { base.Validate(); if (ProcessName == null) { throw new ValidationException(ValidationException.Rule.CannotBeNull, "ProcessName"); } } } }
39.952703
543
0.595129
[ "MIT" ]
AndreiShilkin/AppCenter-SDK-DotNet
SDK/AppCenterCrashes/Microsoft.AppCenter.Crashes.Windows.Shared/Ingestion/Models/AbstractErrorLog.cs
5,913
C#
// Needed for NET35 (ThreadLocal) #if TARGETS_NET || GREATERTHAN_NETCOREAPP11 using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Theraot.Reflection; using Theraot.Threading.Needles; namespace Theraot.Threading { [DebuggerDisplay("IsValueCreated={IsValueCreated}, Value={ValueForDebugDisplay}")] [DebuggerNonUserCode] public sealed class NoTrackingThreadLocal<T> : IThreadLocal<T>, ICacheNeedle<T>, IObserver<T> { private int _disposing; private LocalDataStoreSlot? _slot; private Func<T>? _valueFactory; public NoTrackingThreadLocal() : this(ConstructorHelper.CreateOrDefault<T>) { // Empty } public NoTrackingThreadLocal(Func<T> valueFactory) { _valueFactory = valueFactory ?? throw new ArgumentNullException(nameof(valueFactory)); _slot = Thread.AllocateDataSlot(); } bool IReadOnlyNeedle<T>.IsAlive => IsValueCreated; bool IPromise.IsCompleted => IsValueCreated; public bool IsValueCreated { get { if (Volatile.Read(ref _disposing) == 1) { throw new ObjectDisposedException(nameof(NoTrackingThreadLocal<T>)); } var slot = _slot; return slot != null && Thread.GetData(slot) is ReadOnlyStructNeedle<T>; } } public T Value { get { var valueFactory = _valueFactory; if (Volatile.Read(ref _disposing) == 1) { throw new ObjectDisposedException(nameof(NoTrackingThreadLocal<T>)); } var slot = _slot; if (slot != null) { var bundle = Thread.GetData(slot); if (bundle is INeedle<T> needle) { return needle.Value; } } else { slot = InitializeSlot(); } try { Thread.SetData(slot, ThreadLocalHelper<T>.RecursionGuardNeedle); var result = valueFactory!.Invoke(); Thread.SetData(slot, new ReadOnlyStructNeedle<T>(result)); return result; } catch (Exception exception) { if (exception != ThreadLocalHelper.RecursionGuardException) { Thread.SetData(slot, new ExceptionStructNeedle<T>(exception)); } throw; } } set { if (Volatile.Read(ref _disposing) == 1) { throw new ObjectDisposedException(nameof(NoTrackingThreadLocal<T>)); } var slot = _slot ?? InitializeSlot(); Thread.SetData(slot, new ReadOnlyStructNeedle<T>(value)); } } T IThreadLocal<T>.ValueForDebugDisplay => ValueForDebugDisplay; IList<T> IThreadLocal<T>.Values => throw new InvalidOperationException(); internal T ValueForDebugDisplay => TryGetValue(out var target) ? target : default!; [DebuggerNonUserCode] public void Dispose() { if (Interlocked.CompareExchange(ref _disposing, 1, 0) != 0) { return; } _slot = null; _valueFactory = null; } public void EraseValue() { if (Volatile.Read(ref _disposing) == 1) { throw new ObjectDisposedException(nameof(NoTrackingThreadLocal<T>)); } var slot = _slot ?? InitializeSlot(); Thread.SetData(slot, null); } void IObserver<T>.OnCompleted() { GC.KeepAlive(Value); } void IObserver<T>.OnError(Exception error) { if (Volatile.Read(ref _disposing) == 1) { throw new ObjectDisposedException(nameof(NoTrackingThreadLocal<T>)); } var slot = _slot ?? InitializeSlot(); Thread.SetData(slot, new ExceptionStructNeedle<T>(error)); } void IObserver<T>.OnNext(T value) { Value = value; } public override string ToString() { return Value?.ToString() ?? string.Empty; } public bool TryGetValue(out T value) { var slot = _slot; if (slot == null) { value = default!; return false; } var bundle = Thread.GetData(slot); if (!(bundle is INeedle<T> container)) { value = default!; return false; } value = container.Value; return true; } private LocalDataStoreSlot InitializeSlot() { var slot = Thread.AllocateDataSlot(); var found = Interlocked.CompareExchange(ref _slot, slot, null); if (found != null) { slot = found; } return slot; } } } #endif
28.378238
98
0.494614
[ "MIT" ]
Terricide/Theraot
Framework.Core/Theraot/Threading/NoTrackingThreadLocal.cs
5,479
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace Komodex.Common.SampleData { #if DEBUG public static class SampleDataHelper { private readonly static Random _random = new Random(); private readonly static string[] _words = "aenean aliquam class cras curabitur curae donec duis etiam fusce in integer lorem maecenas mauris morbi nam nulla nullam nunc pellentesque phasellus praesent proin quisque sed suspendisse ut vestibulum vivamus a ac accumsan ad adipiscing aliquam aliquet amet ante aptent arcu at auctor augue bibendum blandit commodo condimentum congue consectetuer consequat conubia convallis cubilia cursus dapibus diam dictum dictumst dignissim dis dolor egestas eget eleifend elementum elit enim erat eros est et eu euismod facilisi facilisis fames faucibus felis fermentum feugiat fringilla gravida habitant habitasse hac hendrerit himenaeos iaculis id imperdiet in inceptos interdum ipsum justo lacinia lacus laoreet lectus leo libero ligula litora lobortis lorem luctus magna magnis malesuada massa mattis mauris metus mi mollis montes morbi mus nascetur natoque nec neque netus nibh nisi nisl non nostra nulla nunc odio orci ornare parturient pede pellentesque penatibus per pharetra placerat platea porta porttitor posuere potenti pretium primis pulvinar purus quam quis rhoncus risus rutrum sagittis sapien scelerisque sed sem semper senectus sit sociis sociosqu sodales sollicitudin suscipit taciti tellus tempor tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae viverra volutpat vulputate".Split(' '); public static void FillSampleData(object obj, bool fillLists = true) { FillSampleData(obj, fillLists, 0); } private static void FillSampleData(object obj, bool fillLists, int level) { // Assign values to the object's properties var properties = obj.GetType().GetProperties(); foreach (var property in properties) { // Make sure we can set this property if (property.GetSetMethod() == null) continue; // Make sure this isn't an indexer if (property.GetIndexParameters().Length > 0) continue; // Try to get a value var sampleValue = GetSampleDataForType(property.PropertyType); if (sampleValue != null) { property.SetValue(obj, sampleValue, null); continue; } // List if (fillLists && level < 2) { Type subListItemType = GetGenericListType(property.PropertyType); if (subListItemType != null) { Type subListType = property.PropertyType; if (subListType.IsInterface()) subListType = typeof(List<>).MakeGenericType(subListItemType); object subList = Activator.CreateInstance(subListType); FillSampleData(subList, fillLists, level + 1); property.SetValue(obj, subList, null); continue; } } // SampleDataBase object if (typeof(SampleDataBase).IsAssignableFrom(property.PropertyType)) { property.SetValue(obj, Activator.CreateInstance(property.PropertyType), null); continue; } } // If this is a list, add items Type listItemType = GetGenericListType(obj.GetType()); if (listItemType != null) { var addMethod = obj.GetType().GetMethod("Add"); int listItemCount = (level < 2) ? 10 : 5; for (int i = 0; i < listItemCount; i++) { object item = GetSampleDataForType(listItemType); if (item == null && fillLists && level < 2) { Type subListItemType = GetGenericListType(listItemType); if (subListItemType != null) { Type subListType = listItemType; if (subListType.IsInterface()) subListType = typeof(List<>).MakeGenericType(subListItemType); object subList = Activator.CreateInstance(subListType); FillSampleData(subList, fillLists, level + 1); item = subList; } } if (item == null) break; addMethod.Invoke(obj, new object[] { item }); } } } private static Type GetGenericListType(Type type) { // If this is an interface, only return true if it's an IList<T> if (type.IsInterface()) { if (type.IsGenericType() && type.GetGenericTypeDefinition() == typeof(IList<>)) return type.GetGenericArguments()[0]; return null; } // Return true if the type inherits from List<T> var interfaces = type.GetInterfaces(); foreach (var interfaceType in interfaces) { Type genericType = GetGenericListType(interfaceType); if (genericType != null) return genericType; } return null; } private static object GetSampleDataForType(Type type) { // String if (type == typeof(string)) return GetRandomString(2, 5); // Int if (type == typeof(int)) return GetRandomInt(0, 100); // Bool if (type == typeof(bool)) return GetRandomBool(); // TimeSpan if (type == typeof(TimeSpan)) return TimeSpan.FromSeconds(GetRandomInt(0, 7200)); // SampleDataBase if (typeof(SampleDataBase).IsAssignableFrom(type)) return Activator.CreateInstance(type); return null; } #region Random Data Generators private static int GetRandomInt(int min, int max) { return _random.Next(min, max + 1); } private static bool GetRandomBool() { return (GetRandomInt(0, 1) == 1); } public static string GetRandomString(int minWords, int maxWords) { int words = GetRandomInt(minWords, maxWords); string result = string.Join(" ", _words.OrderBy(s => _random.Next()).Take(words)); result = char.ToUpper(result[0]) + result.Substring(1); return result; } #endregion #region Reflection Helpers private static bool IsInterface(this Type type) { return type.GetTypeInfo().IsInterface; } private static bool IsGenericType(this Type type) { return type.GetTypeInfo().IsGenericType; } #endregion } #endif }
40
1,439
0.561968
[ "MIT" ]
misenhower/WPRemote
CommonLibraries/UniversalLibraries/Komodex.Common/SampleData/SampleDataHelper.cs
7,522
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: Templates\CSharp\Requests\MethodRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The type UserWipeManagedAppRegistrationByDeviceTagRequest. /// </summary> public partial class UserWipeManagedAppRegistrationByDeviceTagRequest : BaseRequest, IUserWipeManagedAppRegistrationByDeviceTagRequest { /// <summary> /// Constructs a new UserWipeManagedAppRegistrationByDeviceTagRequest. /// </summary> public UserWipeManagedAppRegistrationByDeviceTagRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { this.ContentType = "application/json"; this.RequestBody = new UserWipeManagedAppRegistrationByDeviceTagRequestBody(); } /// <summary> /// Gets the request body. /// </summary> public UserWipeManagedAppRegistrationByDeviceTagRequestBody RequestBody { get; private set; } /// <summary> /// Issues the POST request. /// </summary> public System.Threading.Tasks.Task PostAsync() { return this.PostAsync(CancellationToken.None); } /// <summary> /// Issues the POST request. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await for async call.</returns> public System.Threading.Tasks.Task PostAsync( CancellationToken cancellationToken) { this.Method = "POST"; return this.SendAsync(this.RequestBody, cancellationToken); } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IUserWipeManagedAppRegistrationByDeviceTagRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IUserWipeManagedAppRegistrationByDeviceTagRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } } }
36.149425
153
0.59682
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/UserWipeManagedAppRegistrationByDeviceTagRequest.cs
3,145
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Navigation; // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=391641 namespace EmailValidationConverter.WinPhone { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> public sealed partial class App : Application { private TransitionCollection transitions; /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += this.OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // TODO: change this value to a cache size that is appropriate for your application rootFrame.CacheSize = 1; // Set the default language rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; Xamarin.Forms.Forms.Init(e); if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(MainPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); } /// <summary> /// Restores the content transitions after the app has launched. /// </summary> /// <param name="sender">The object where the handler is attached.</param> /// <param name="e">Details about the navigation event.</param> private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e) { var rootFrame = sender as Frame; rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() }; rootFrame.Navigated -= this.RootFrame_FirstNavigated; } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); // TODO: Save application state and stop any background activity deferral.Complete(); } } }
39.095588
126
0.611435
[ "Apache-2.0" ]
aliozgur/xamarin-forms-book-samples
Chapter23/EmailValidationConv/EmailValidationConverter/EmailValidationConverter.WinPhone/App.xaml.cs
5,317
C#
using Microsoft.AspNet.Authorization; using Microsoft.AspNet.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Kodj.Api.Controllers { [Route("status")] public class StatusController: Controller { [AllowAnonymous] [HttpGet] public string Get() { return "ok"; } } }
18.857143
45
0.643939
[ "MIT" ]
kodj/kodj
src/Kodj.Api/Controllers/StatusController.cs
398
C#
using System; using Xunit; namespace Avalonia.GameStudio.Presentation.Internal { public class TimeSpanBoxesTest { [Fact] public void MaxValueBox_should_return_MaxValue() { // Act var value = (TimeSpan)TimeSpanBoxes.MaxValueBox; // Assert Assert.Equal(TimeSpan.MaxValue, value); } [Fact] public void MaxValueBox_should_return_same_instance() { // Act var value1 = TimeSpanBoxes.MaxValueBox; var value2 = TimeSpanBoxes.MaxValueBox; // Assert Assert.Same(value1, value2); } [Fact] public void MinValueBox_should_return_MinValue() { // Act var value = (TimeSpan)TimeSpanBoxes.MinValueBox; // Assert Assert.Equal(TimeSpan.MinValue, value); } [Fact] public void MinValueBox_should_return_same_instance() { // Act var value1 = TimeSpanBoxes.MinValueBox; var value2 = TimeSpanBoxes.MinValueBox; // Assert Assert.Same(value1, value2); } [Fact] public void ZeroBox_should_return_Zero() { // Act var value = (TimeSpan)TimeSpanBoxes.ZeroBox; // Assert Assert.Equal(TimeSpan.Zero, value); } [Fact] public void ZeroBox_should_return_same_instance() { // Act var value1 = TimeSpanBoxes.ZeroBox; var value2 = TimeSpanBoxes.ZeroBox; // Assert Assert.Same(value1, value2); } } }
25.41791
61
0.531415
[ "MIT" ]
Kryptos-FR/Avalonia.GameStudio
tests/Avalonia.GameStudio.Presentation.Tests/Internal/TimeSpanBoxesTest.cs
1,705
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using BepInEx; using HarmonyLib; using SideLoader; using UnityEngine; using SharedModConfig; namespace ProtectionBubble { [BepInPlugin(GUID, NAME, VERSION)] public class ProtectionBubbleMod : BaseUnityPlugin { public const string GUID = "com.sinai.protectionbubble"; public const string NAME = "Protection Bubble"; public const string VERSION = "1.0.0"; public static ModConfig config; internal void Awake() { config = SetupConfig(); config.Register(); var harmony = new Harmony(GUID); harmony.PatchAll(); SL.OnPacksLoaded += SL_OnPacksLoaded; } private void SL_OnPacksLoaded() { ProtectionBubble.Setup(); } private ModConfig SetupConfig() { return new ModConfig { ModName = NAME, SettingsVersion = 1.0, Settings = new List<BBSetting> { new BoolSetting { SectionTitle = "Shield Behaviour", Name = Settings.OrigProtectionApplied, DefaultValue = false, Description = "Original Protection Stat still applied to incoming damage" }, new FloatSetting { Name = Settings.RegenDelay, DefaultValue = 5.0f, Description = "Delay after last received damage for Protection Bubble to continue regenerating", MinValue = 0f, MaxValue = 30f, Increment = 0.1f, RoundTo = 1 }, new FloatSetting { Name = Settings.RegenRate, DefaultValue = 0.1f, Description = "Amount of Protection Bubble restored per 0.1 seconds (flat value).", MinValue = 0.01f, MaxValue = 10f, Increment = 0.05f, RoundTo = 1 }, new FloatSetting { Name = Settings.ShieldRatio, Description = "Protection Stat to Shield Health ratio. Default is 2:1.", DefaultValue = 200f, MinValue = 1f, MaxValue = 1000f, Increment = 1f, ShowPercent = true }, new BoolSetting { SectionTitle = "Visual Effects", Name = Settings.ShowFX, Description = "Show Visual FX on Character when Shield is active", DefaultValue = true } } }; } } public class Settings { public const string OrigProtectionApplied = "OrigProtectionApplied"; public const string RegenDelay = "RegenDelay"; public const string RegenRate = "RegenRate"; public const string ShieldRatio = "ShieldRatio"; public const string ShowFX = "ShowVFX"; } }
33.567308
120
0.466628
[ "MIT" ]
Daimyo21/Outward-Mods
! Small Mods/ProtectionBubble/ProtectionBubble/ProtectionBubbleMod.cs
3,493
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ArmaforcesMissionBotWeb.HelperClasses { public class AccessTokenResponse { public string access_token; public string token_type; public string expires_in; public string refresh_token; public string scope; } }
21.764706
47
0.716216
[ "MIT" ]
ArmaForces/Boderator
ArmaforcesMissionBotWeb/HelperClasses/AccessTokenResponse.cs
372
C#
namespace TasteIt.Web { using System.Reflection; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Infrastructure.Mapping; public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { // custom DbConfig.Initialize(); EnginesConfig.StartOnlyRazor(); var autoMapperConfig = new AutoMapperConfig(); autoMapperConfig.Execute(Assembly.GetExecutingAssembly()); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
30.461538
70
0.656566
[ "MIT" ]
marianamn/TasteIt
TasteIt/Web/TasteIt.Web/Global.asax.cs
794
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.Runtime.InteropServices; using System.Text; using System.Globalization; using System.Diagnostics.Contracts; namespace System.IO { /// <summary> /// Provides centralized methods for creating exceptions for System.IO.FileSystem. /// </summary> [Pure] internal static class __Error { internal static Exception GetEndOfFile() { return new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF); } internal static Exception GetFileNotOpen() { return new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed); } internal static Exception GetReadNotSupported() { return new NotSupportedException(SR.NotSupported_UnreadableStream); } internal static Exception GetSeekNotSupported() { return new NotSupportedException(SR.NotSupported_UnseekableStream); } internal static Exception GetWrongAsyncResult() { return new ArgumentException(SR.Arg_WrongAsyncResult); } internal static Exception GetEndReadCalledTwice() { // Should ideally be InvalidOperationExc but we can't maitain parity with Stream and FileStream without some work return new ArgumentException(SR.InvalidOperation_EndReadCalledMultiple); } internal static Exception GetEndWriteCalledTwice() { // Should ideally be InvalidOperationExc but we can't maintain parity with Stream and FileStream without some work return new ArgumentException(SR.InvalidOperation_EndWriteCalledMultiple); } internal static Exception GetWriteNotSupported() { return new NotSupportedException(SR.NotSupported_UnwritableStream); } } }
32.639344
126
0.681567
[ "MIT" ]
FiveTimesTheFun/corefx
src/System.IO.FileSystem/src/System/IO/__Error.cs
1,991
C#
using System.Collections.Generic; using System.Threading.Tasks; using DataBase.Entities; using DataBase.Interfaces; using Microsoft.Extensions.DependencyInjection; namespace Core.Module.CharacterData { public class CharacterList { private readonly ICharacterRepository _characterRepository; private readonly IUserItemRepository _userItemRepository; private readonly IDictionary<int, int> _userItem; private readonly List<CharacterListModel> _listModels; public CharacterList() { _characterRepository = Initializer.ServiceProvider.GetRequiredService<IUnitOfWork>().Characters; _userItemRepository = Initializer.ServiceProvider.GetRequiredService<IUnitOfWork>().UserItems; _userItem = new Dictionary<int, int>(); _listModels = new List<CharacterListModel>(); } public async Task<List<CharacterListModel>> GetCharacterList(string accountName) { var list = await _characterRepository.GetCharactersByAccountNameAsync(accountName); list.ForEach(PrepareCharacterList); return _listModels; } private async void PrepareCharacterList(CharacterEntity entity) { var items = await _userItemRepository.GetInventoryItemsByOwnerId(entity.CharacterId); items.ForEach(item => { _userItem.Add(item.UserItemId, item.ItemId); }); var characterList = new CharacterListModel { CharacterId = entity.CharacterId, CharacterName = entity.CharacterName, Level = entity.Level, ClassId = entity.ClassId, Race = entity.Race, Gender = entity.Gender, X = entity.XLoc, Y = entity.YLoc, Z = entity.ZLoc, Hp = entity.Hp, Mp = entity.Mp, MaxHp = entity.MaxHp, MaxMp = entity.MaxMp, Sp = entity.Sp, Exp = entity.Exp, Pk = entity.Pk, HairShapeIndex = entity.HairShapeIndex, HairColorIndex = entity.HairColorIndex, FaceIndex = entity.FaceIndex, StUnderwear = entity.StUnderwear, StRightEar = entity.StRightEar, StLeftEar = entity.StLeftEar, StNeck = entity.StNeck, StRightFinger = entity.StRightFinger, StLeftFinger = entity.StLeftFinger, StHead = entity.StHead, StRightHand = entity.StRightHand, StLeftHand = entity.StLeftHand, StGloves = entity.StGloves, StChest = entity.StChest, StLegs = entity.StLegs, StFeet = entity.StFeet, StBack = entity.StBack, StBothHand = entity.StBothHand, StHair = entity.StHair, StFace = entity.StFace, StHairAll = entity.StHairAll, }; _listModels.Add(characterList); } public int GetItem(int userItemId) { return _userItem.ContainsKey(userItemId) ? _userItem[userItemId] : 0; } } }
40.506024
109
0.570791
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
dr3dd/L2Interlude
Core/Module/CharacterData/CharacterList.cs
3,364
C#
using System; using System.Runtime.InteropServices; using System.Collections.Generic; using BulletSharp.Math; using static BulletSharp.UnsafeNativeMethods; namespace BulletSharp { public class ConvexHullShape : PolyhedralConvexAabbCachingShape { private Vector3Array _unscaledPoints; public ConvexHullShape() { IntPtr native = btConvexHullShape_new(); InitializeCollisionShape(native); } public ConvexHullShape(float[] points) : this(points, points.Length / 3, 3 * sizeof(float)) { } public ConvexHullShape(float[] points, int numPoints, int stride = 3 * sizeof(float)) { IntPtr native = btConvexHullShape_new4(points, numPoints, stride); InitializeCollisionShape(native); } public ConvexHullShape(IEnumerable<Vector3> points, int numPoints) { IntPtr native = btConvexHullShape_new(); InitializeCollisionShape(native); int i = 0; foreach (Vector3 v in points) { Vector3 viter = v; AddPointRef(ref viter, false); i++; if (i == numPoints) { break; } } RecalcLocalAabb(); } public ConvexHullShape(IEnumerable<Vector3> points) { IntPtr native = btConvexHullShape_new(); InitializeCollisionShape(native); foreach (Vector3 v in points) { Vector3 viter = v; AddPointRef(ref viter, false); } RecalcLocalAabb(); } public void AddPointRef(ref Vector3 point, bool recalculateLocalAabb = true) { btConvexHullShape_addPoint(Native, ref point, recalculateLocalAabb); } public void AddPoint(Vector3 point, bool recalculateLocalAabb = true) { btConvexHullShape_addPoint(Native, ref point, recalculateLocalAabb); } public void GetScaledPoint(int i, out Vector3 value) { btConvexHullShape_getScaledPoint(Native, i, out value); } public Vector3 GetScaledPoint(int i) { Vector3 value; btConvexHullShape_getScaledPoint(Native, i, out value); return value; } public void OptimizeConvexHull() { btConvexHullShape_optimizeConvexHull(Native); } public int NumPoints => btConvexHullShape_getNumPoints(Native); public Vector3Array UnscaledPoints { get { if (_unscaledPoints == null || _unscaledPoints.Count != NumPoints) { _unscaledPoints = new Vector3Array(btConvexHullShape_getUnscaledPoints(Native), NumPoints); } return _unscaledPoints; } } } [StructLayout(LayoutKind.Sequential)] internal struct ConvexHullShapeData { public ConvexInternalShapeData ConvexInternalShapeData; public IntPtr UnscaledPointsFloatPtr; public IntPtr UnscaledPointsDoublePtr; public int NumUnscaledPoints; public int Padding; public static int Offset(string fieldName) { return Marshal.OffsetOf(typeof(ConvexHullShapeData), fieldName).ToInt32(); } } }
23.732759
123
0.732655
[ "Apache-2.0" ]
xtom0369/BulletPhysicsForUnity
BulletSharpPInvoke/BulletSharp/Collision/ConvexHullShape.cs
2,753
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; namespace Linguistics.Core { /// <summary> /// Предложение /// </summary> [Serializable] public class Sentence : ISerializerToRDF { /// <summary> /// Подпредложения в виде списка /// </summary> /// должен быть всегда заполнен public SubSentence[] SubsentsFlatten { get; private set; } /// <summary> /// Подпредложения в виде дерева /// </summary> /// должен быть всегда заполнен public SubSentence[] SubsentsHierarchical { get; private set; } /// <summary> /// Начальная позиция в тексте /// </summary> public int StartPosition { get; protected set; } /// <summary> /// Язык /// </summary> public string Language { get; set; } #region [.ctor().] public Sentence(int startPosition) { StartPosition = startPosition; } #endregion /// <summary> /// Задание иерархии подпредложений /// </summary> /// <param name="hierarchy">иерархия подпредложений</param> public void SetSubSentencesHeirarchy(SubSentence[] hierarchy) { SubsentsHierarchical = hierarchy; SubsentsFlatten = GetFlattenSubSentences(); SubsentsFlatten.SetRelations(this); } /// <summary> /// Получение коллекции всех подпредложений из иерархии в порядке следования /// </summary> /// <returns>коллекция подпредложений</returns> private SubSentence[] GetFlattenSubSentences() { List<SubSentence> result = new List<SubSentence>(); foreach (var subSentence in SubsentsHierarchical) GetFlattenSubSentences(subSentence, ref result); return result.ToArray(); } /// <summary> /// Пополнение заданной коллекции заданным подпредложением и всеми его подпредложениями-потомками /// </summary> /// <param name="parentSubSentence">заданное подпредложение</param> /// <param name="result">пополняемая коллекция</param> private void GetFlattenSubSentences(SubSentence parentSubSentence, ref List<SubSentence> result) { result.Add(parentSubSentence); if (parentSubSentence.SubTextInfo == null) { var children = ((SubSentence)parentSubSentence).Children; if (children == null) return; foreach (var subSentence in children) GetFlattenSubSentences(subSentence, ref result); } } #region [ISerializeRDF] public XElement ToXElement() { XElement result = new XElement(UnitTextType.SENT.ToString()); result.SetAttributeValue(RDF.Attribute.StartPosition, StartPosition); result.SetAttributeValue(RDF.Attribute.Language, Language); foreach (var subSentence in SubsentsHierarchical) result.Add(subSentence.ToXElement()); return result; } #endregion } }
27.459184
99
0.709402
[ "MIT" ]
elzin/SentimentAnalysisService
Sources/Core/csharp/Linguistics.Core/TextHierarchy/Sentence.cs
3,093
C#
#nullable disable using System.Text.RegularExpressions; namespace NadekoBot.Modules.Music.Resolvers; public class RadioResolver : IRadioResolver { private readonly Regex _plsRegex = new("File1=(?<url>.*?)\\n", RegexOptions.Compiled); private readonly Regex _m3URegex = new("(?<url>^[^#].*)", RegexOptions.Compiled | RegexOptions.Multiline); private readonly Regex _asxRegex = new("<ref href=\"(?<url>.*?)\"", RegexOptions.Compiled); private readonly Regex _xspfRegex = new("<location>(?<url>.*?)</location>", RegexOptions.Compiled); public async Task<ITrackInfo> ResolveByQueryAsync(string query) { if (IsRadioLink(query)) query = await HandleStreamContainers(query); return new SimpleTrackInfo(query.TrimTo(50), query, "https://cdn.discordapp.com/attachments/155726317222887425/261850925063340032/1482522097_radio.png", TimeSpan.MaxValue, MusicPlatform.Radio, query); } public static bool IsRadioLink(string query) => (query.StartsWith("http", StringComparison.InvariantCulture) || query.StartsWith("ww", StringComparison.InvariantCulture)) && (query.Contains(".pls") || query.Contains(".m3u") || query.Contains(".asx") || query.Contains(".xspf")); private async Task<string> HandleStreamContainers(string query) { string file = null; try { using var http = new HttpClient(); file = await http.GetStringAsync(query); } catch { return query; } if (query.Contains(".pls")) //File1=http://armitunes.com:8000/ //Regex.Match(query) { try { var m = _plsRegex.Match(file); var res = m.Groups["url"]?.ToString(); return res?.Trim(); } catch { Log.Warning("Failed reading .pls:\n{PlsFile}", file); return null; } } if (query.Contains(".m3u")) /* # This is a comment C:\xxx4xx\xxxxxx3x\xx2xxxx\xx.mp3 C:\xxx5xx\x6xxxxxx\x7xxxxx\xx.mp3 */ { try { var m = _m3URegex.Match(file); var res = m.Groups["url"]?.ToString(); return res?.Trim(); } catch { Log.Warning("Failed reading .m3u:\n{M3uFile}", file); return null; } } if (query.Contains(".asx")) //<ref href="http://armitunes.com:8000"/> { try { var m = _asxRegex.Match(file); var res = m.Groups["url"]?.ToString(); return res?.Trim(); } catch { Log.Warning("Failed reading .asx:\n{AsxFile}", file); return null; } } if (query.Contains(".xspf")) /* <?xml version="1.0" encoding="UTF-8"?> <playlist version="1" xmlns="http://xspf.org/ns/0/"> <trackList> <track><location>file:///mp3s/song_1.mp3</location></track> */ { try { var m = _xspfRegex.Match(file); var res = m.Groups["url"]?.ToString(); return res?.Trim(); } catch { Log.Warning("Failed reading .xspf:\n{XspfFile}", file); return null; } } return query; } }
31.308333
118
0.483098
[ "MIT" ]
StefanPuia/nadeko
src/NadekoBot/Modules/Music/_Common/Resolvers/RadioResolveStrategy.cs
3,759
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(AudioSource))] public class ClipHandler : MonoBehaviour { [SerializeField] int m_ID; [SerializeField] bool b_PitchRandom = true; [SerializeField] bool b_PlayInWorld = true; [SerializeField] AudioSource m_Audio; public void SetID (int i) { m_ID = i; } private void UnLoad() { ObjectPool.m_Instance.UnLoadObjectToPool(m_ID, this.gameObject); } IEnumerator WaitToUnLoad() { yield return new WaitForSeconds(m_Audio.clip.length); UnLoad(); } public void PlayInWorld(Vector3 pos, float volumeScale) { float height = Camera.main.transform.position.y - pos.y; pos.y += height; pos.z += -Mathf.Tan((90 - Camera.main.transform.eulerAngles.x) * Mathf.Deg2Rad) * (height - 1f); AudioSource.PlayClipAtPoint(m_Audio.clip, pos, volumeScale); } private void SetPitch() { if (!b_PitchRandom) return; m_Audio.pitch = Random.Range(0.95f, 1.4f); } private void PlaySound() { if (!b_PlayInWorld) { m_Audio.PlayOneShot(m_Audio.clip); } else PlayInWorld(transform.position, 1); } private void OnEnable() { SetPitch(); PlaySound(); StartCoroutine(WaitToUnLoad()); } }
26.411765
104
0.648849
[ "MIT" ]
IvanCKP/HELLDIVERS_Like
HellDivers_UnityProject/Assets/Scripts/Audio/ClipHandler.cs
1,349
C#
// RESTComponent // RESTComponent.RTComponent.Configuration // ComponentConfiguration.cs // // Created by Bartosz Rachwal. // Copyright (c) 2015 Bartosz Rachwal. The National Institute of Advanced Industrial Science and Technology, Japan. All rights reserved. using System; namespace RESTComponent.RTComponent.Configuration { public class ComponentConfiguration : IComponentConfiguration { private string defaultHost = "+"; private int defaultPort = 9000; private int pixelFormat; public int PixelFormat { get { return pixelFormat; } set { if (value == pixelFormat) { return; } pixelFormat = value; ConfigurationChanged?.Invoke(this, EventArgs.Empty); } } public event EventHandler ConfigurationChanged; public int Port { get { return defaultPort; } set { if (value == defaultPort) { return; } defaultPort = value; ConfigurationChanged?.Invoke(this, EventArgs.Empty); } } public string Host { get { return defaultHost; } set { if (string.IsNullOrEmpty(value)) return; var newHost = value.Trim().ToLower() == "localhost" ? "+" : value; if (newHost.Equals(defaultHost)) { return; } defaultHost = newHost; ConfigurationChanged?.Invoke(this, EventArgs.Empty); } } } }
24.561644
137
0.493586
[ "MIT" ]
rachwal/RTM-REST-API
RESTComponent.RTComponent.Configuration/ComponentConfiguration.cs
1,795
C#
using System; using System.Linq; namespace Dictator.Core.Services { /// <summary> /// Provides functionality related to the presidential decision mechanic. /// </summary> public class DecisionService : IDecisionService { private Decision[] decisions; private readonly IAccountService accountService; private readonly IGroupService groupService; /// <summary> /// Initializes a new instance of the <see cref="DecisionService"/> class from a <see cref="IAccountService"/> and /// a <see cref="IGroupService"/> components. /// </summary> /// <param name="accountService">The service used to provide functionality related to the treasury and associated /// costs and the Swiss bank account.</param> /// <param name="groupService">The service used to provide functionality related to the groups or factions.</param> public DecisionService(IAccountService accountService, IGroupService groupService) { this.accountService = accountService; this.groupService = groupService; Initialise(); } public void Initialise() { decisions = new Decision[] { new Decision(DecisionType.PleaseAGroup, DecisionSubType.None, 0, 0, "QLLMMLMM", "NMMLML", "MAKE ARMY CHIEF \"VICE-PRESIDENT\""), new Decision(DecisionType.PleaseAGroup, DecisionSubType.None, -1/*L*/, -4/*I*/, "LQNMOMNM", "MMMLMM", "SET UP FREE CLINICS for WORKERS "), new Decision(DecisionType.PleaseAGroup, DecisionSubType.None, 0, 0, "LKQMMLLM", "LLOMML", "GIVE LANDOWNERS REGIONAL POWERS "), new Decision(DecisionType.PleaseAGroup, DecisionSubType.None, 5/*R*/, 0, "KMMMQMKN", "LMMLPM", "SELL AMERICAN ARMS to LEFTOTO "), new Decision(DecisionType.PleaseAGroup, DecisionSubType.None,12/*Y*/, 0, "MMLMLMKP", "MMMMMM", "SELL MINING RIGHTS to U.S. FIRMS"), new Decision(DecisionType.PleaseAGroup, DecisionSubType.None,0, 10/*W*/, "KMMMMMPJ", "MMMMMM", "RENT the RUSSIANS a NAVAL BASE "), new Decision(DecisionType.PleaseAllGroups, DecisionSubType.None,0, -8/*E*/, "NPPMMMMM", "LMMLMM", "DECREASE GENERAL TAXATION LEVEL "), new Decision(DecisionType.PleaseAllGroups, DecisionSubType.None, -8/*E*/, 0, "PPPMMMMM", "MMMLMM", "STAGE a BIG POPULARITY CAMPAIGN "), new Decision(DecisionType.PleaseAllGroups, DecisionSubType.None,0, 8/*U*/, "PPPMMDMM", "ONNNMD", "CUT S.POLICE POWERS COMPLETELY "), new Decision(DecisionType.ImproveYourChanges, DecisionSubType.None, 0, -6/*G*/, "JJJMMUMM", "LLLLMU", "INCREASE S.POLICE POWERS a LOT "), new Decision(DecisionType.ImproveYourChanges, DecisionSubType.IncreaseBodyGuard, -4/*I*/, 0, "KLLMMLMM", "KMMMML", "INCREASE YOUR BODYGUARD *"), new Decision(DecisionType.ImproveYourChanges, DecisionSubType.PurchaseHelicopter, -12/*A*/, 0, "IIJMMKMM", "MMMMMM", "BUY an ESCAPE HELICOPTER "), new Decision(DecisionType.ImproveYourChanges, DecisionSubType.TransferToSwissAccount, 0, 0, "MMMMMMMM", "MMMMMM", "SEE TO YOUR SWISS BANK ACCOUNT *"), new Decision(DecisionType.RaiseSomeCash, DecisionSubType.AskForRussianLoan, 0, 0, "MMMMMMMM", "MMMMMM", "ASK the RUSSIANS for a \"LOAN\" *"), new Decision(DecisionType.RaiseSomeCash, DecisionSubType.AskForAmericanLoan, 0, 0, "MMMMMMMM", "MMMMMM", "ASK AMERICANS for FOREIGN \"AID\"*"), new Decision(DecisionType.RaiseSomeCash, DecisionSubType.None, 12/*Z*/, 0, "NNPMGMKM", "MMMMMM", "NATIONALISE LEFTOTAN BUSINESSES "), new Decision(DecisionType.StrengthenAGroup, DecisionSubType.None, -5/*H*/, 0, "PMMMJMLM", "RMMKKL", "BUY HEAVY ARTILLERY for THE ARMY"), new Decision(DecisionType.StrengthenAGroup, DecisionSubType.None,0, 0, "MPLMMLMM", "MRLPML", "ALLOW PEASANTS FREE MOVEMENT "), new Decision(DecisionType.StrengthenAGroup, DecisionSubType.None,0, 0, "LLPMMLMM", "LLRLML", "ALLOW LANDOWNERS PRIVATE MILITIA") }; } /// <summary> /// Retrieves all the decisions of a specific type. /// </summary> /// <param name="decisionType">The type of decision.</param> /// <returns>An array of decisions of the specified type.</returns> public Decision[] GetDecisionsByType(DecisionType decisionType) { Decision[] decisionCopy = (Decision[])decisions.Clone(); return decisionCopy.Where(x => x.Type == decisionType).ToArray(); } /// <summary> /// Retrieves a decisions with the specified type and index. /// </summary> /// <param name="decisionType">The type of decision.</param> /// <param name="optionSelected">The position of the decision within the group of decisions with the specified type.</param> /// <returns>The position that matches the specified type and at the specific position.</returns> public Decision GetDecisionByTypeAndIndex(DecisionType decisionType, int optionNumber) { if (optionNumber < 0) { throw new ArgumentException(nameof(optionNumber)); } Decision[] decisions = GetDecisionsByType(decisionType); if (optionNumber > decisions.Length) { throw new ArgumentException(nameof(optionNumber)); } return decisions[optionNumber - 1]; } /// <summary> /// Determines if a presidential option exists and is available for selection. /// </summary> /// <param name="decisionType">The type of decision.</param> /// <param name="optionNumber">The option number within the type group of the decision.</param> /// <returns><c>true</c> if the presidential decision exists and is available for selection; otherwise, <c>false</c>.</returns> public bool DoesPresidentialOptionExistAndIsAvailable(DecisionType decisionType, int optionNumber) { Decision[] decisions = GetDecisionsByType(decisionType); if (optionNumber > decisions.Length) { return false; } if (decisions[optionNumber - 1].HasBeenUsed) { return false; } return true; } /// <summary> /// Marks a presidential decision option as used. /// </summary> /// <param name="text">The text of the presidential decision which will be marked as used.</param> public void MarkDecisionAsUsed(string text) { Decision item = decisions.Where(x => x.Text == text).Single(); item.HasBeenUsed = true; } /// <summary> /// Applies the effects of a decision on the groups popularity and strength with the costs of treasury. /// </summary> /// <param name="decision">The decision whose effects will be apply.</param> public void ApplyDecisionEffects(Decision decision) { if (decision == null) { throw new ArgumentNullException(); } groupService.ApplyPopularityChange(decision.GroupPopularityChanges); groupService.ApplyStrengthChange(decision.GroupStrengthChanges); accountService.ApplyTreasuryChanges(decision.Cost, decision.MonthlyCost); } } }
52.784722
169
0.629259
[ "MIT" ]
sfvicente/Dictator
Src/Dictator.Engine/Services/DecisionService.cs
7,603
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DatePickerDialog")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DatePickerDialog")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a557ce8c-9dbe-4b93-8fc4-95ffc126cf14")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] // Add some common permissions, these can be removed if not needed [assembly: UsesPermission(Android.Manifest.Permission.Internet)] [assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
39.880952
85
0.739104
[ "Apache-2.0" ]
Pkirugu/xamarin-recipes
android/other_ux/fragment/select_a_date_in_a_fragment/DatePickerDialog/Properties/AssemblyInfo.cs
1,678
C#
using LibraryApp.Models; using System.Collections.Generic; namespace LibraryApp.Services { public interface IFilteringService { IList<Book> FilterBooks(string filteringArg); } }
19.9
53
0.738693
[ "MIT" ]
deividasbagdanskis/visma-internship-2021
LibraryApp/Services/IFilteringService.cs
201
C#
namespace CodingMilitia.PlayBall.GroupManagement.Web.Models { public class GroupModel { public long Id { get; set; } public string Name { get; set; } } }
22.625
59
0.635359
[ "MIT" ]
aspnetcorefromzerotooverkillorg/GroupManagement
src/CodingMilitia.PlayBall.GroupManagement.Web/Models/GroupModel.cs
181
C#
namespace Api { public class Options { public string StorageConnectionString { get; set; } public string FullImageContainerName { get; set; } public string ThumbnailImageContainerName { get; set; } } }
21.818182
63
0.65
[ "MIT" ]
23dproject/AZ-204-DevelopingSolutionsforMicrosoftAzure
Allfiles/Labs/01/Starter/API/Options.cs
242
C#
using ENode.Domain; using ENode.EQueue; namespace ENode.Tests { public class DomainExceptionTopicProvider : AbstractTopicProvider<IDomainException> { public override string GetTopic(IDomainException source) { return "DomainExceptionTopic"; } } }
21.142857
87
0.685811
[ "MIT" ]
Caskia/enode
src/ENode.Tests/Providers/DomainExceptionTopicProvider.cs
298
C#
using System; public class Pet { private string name; private int age; private string kind; public Pet(string name, int age, string kind) { this.Name = name; this.Age = age; this.Kind = kind; } public string Name { get => name; set => name = value; } public int Age { get => age; set => age = value; } public string Kind { get => kind; set => kind = value; } public override string ToString() { return $"{this.Name} {this.Age} {this.Kind}"; } }
22.041667
60
0.561437
[ "MIT" ]
tanyta78/CSharpOOPAdv
03_IteratorsAndComparators/PetClinic/Pet.cs
531
C#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Game.Rulesets.Objects.Types; using osuTK; namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces { /// <summary> /// A <see cref="SliderBody"/> which changes its curve depending on the snaking progress. /// </summary> public class SnakingSliderBody : SliderBody, ISliderProgress { public readonly List<Vector2> CurrentCurve = new List<Vector2>(); public readonly Bindable<bool> SnakingIn = new Bindable<bool>(); public readonly Bindable<bool> SnakingOut = new Bindable<bool>(); public double? SnakedStart { get; private set; } public double? SnakedEnd { get; private set; } public override Vector2 PathOffset => snakedPathOffset; /// <summary> /// The top-left position of the path when fully snaked. /// </summary> private Vector2 snakedPosition; /// <summary> /// The offset of the path from <see cref="snakedPosition"/> when fully snaked. /// </summary> private Vector2 snakedPathOffset; private readonly Slider slider; public SnakingSliderBody(Slider slider) { this.slider = slider; } [BackgroundDependencyLoader] private void load() { Refresh(); } public void UpdateProgress(double completionProgress) { var span = slider.SpanAt(completionProgress); var spanProgress = slider.ProgressAt(completionProgress); double start = 0; double end = SnakingIn ? MathHelper.Clamp((Time.Current - (slider.StartTime - slider.TimePreempt)) / slider.TimeFadeIn, 0, 1) : 1; if (span >= slider.SpanCount() - 1) { if (Math.Min(span, slider.SpanCount() - 1) % 2 == 1) { start = 0; end = SnakingOut ? spanProgress : 1; } else { start = SnakingOut ? spanProgress : 0; } } setRange(start, end); } public void Refresh() { // Generate the entire curve slider.Path.GetPathToProgress(CurrentCurve, 0, 1); SetVertices(CurrentCurve); // The body is sized to the full path size to avoid excessive autosize computations Size = Path.Size; snakedPosition = Path.PositionInBoundingBox(Vector2.Zero); snakedPathOffset = Path.PositionInBoundingBox(Path.Vertices[0]); var lastSnakedStart = SnakedStart ?? 0; var lastSnakedEnd = SnakedEnd ?? 0; SnakedStart = null; SnakedEnd = null; setRange(lastSnakedStart, lastSnakedEnd); } private void setRange(double p0, double p1) { if (p0 > p1) MathHelper.Swap(ref p0, ref p1); if (SnakedStart == p0 && SnakedEnd == p1) return; SnakedStart = p0; SnakedEnd = p1; slider.Path.GetPathToProgress(CurrentCurve, p0, p1); SetVertices(CurrentCurve); // The bounding box of the path expands as it snakes, which in turn shifts the position of the path. // Depending on the direction of expansion, it may appear as if the path is expanding towards the position of the slider // rather than expanding out from the position of the slider. // To remove this effect, the path's position is shifted towards its final snaked position Path.Position = snakedPosition - Path.PositionInBoundingBox(Vector2.Zero); } } }
34.193277
143
0.574343
[ "MIT" ]
Dragicafit/osu
osu.Game.Rulesets.Osu/Objects/Drawables/Pieces/SnakingSliderBody.cs
3,953
C#
// <copyright file="ItemCraftAction.cs" company="MUnique"> // Licensed under the MIT License. See LICENSE file in the project root for full license information. // </copyright> namespace MUnique.OpenMU.GameLogic.PlayerActions.Items { using System; using System.Collections.Generic; using System.Linq; using MUnique.OpenMU.DataModel.Configuration.ItemCrafting; /// <summary> /// The action to craft items with crafting NPCs. /// </summary> public class ItemCraftAction { private readonly IDictionary<ItemCrafting, IItemCraftingHandler> craftingHandlerCache = new Dictionary<ItemCrafting, IItemCraftingHandler>(); /// <summary> /// Mixes the items at the currently opened Monster crafter. /// </summary> /// <param name="player">The player.</param> /// <param name="mixTypeId">The mix type identifier.</param> public void MixItems(Player player, byte mixTypeId) { var npcStats = player.OpenedNpc.Definition; ItemCrafting crafting = npcStats?.ItemCraftings.FirstOrDefault(c => c.Number == mixTypeId); if (crafting == null) { return; } IItemCraftingHandler craftingHandler; if (!this.craftingHandlerCache.TryGetValue(crafting, out craftingHandler)) { craftingHandler = this.CreateCraftingHandler(player, crafting); this.craftingHandlerCache.Add(crafting, craftingHandler); } craftingHandler.DoMix(player); } private IItemCraftingHandler CreateCraftingHandler(Player player, ItemCrafting crafting) { if (crafting.SimpleCraftingSettings != null) { return new SimpleItemCraftingHandler(crafting.SimpleCraftingSettings); } if (crafting.ItemCraftingHandlerClassName != null) { var type = Type.GetType(crafting.ItemCraftingHandlerClassName); if (type != null) { return Activator.CreateInstance(type, player.GameContext) as IItemCraftingHandler; } throw new ArgumentException($"Item crafting handler '{crafting.ItemCraftingHandlerClassName}' not found.", nameof(crafting)); } throw new ArgumentException("No simple crafting settings or item crafting handler name specified.", nameof(crafting)); } } }
37.954545
149
0.630339
[ "MIT" ]
CodeKJ/OpenMU
src/GameLogic/PlayerActions/Items/ItemCraftAction.cs
2,507
C#
using System.Reflection; using BridgeRpc.AspNetCore.Router.Abstraction; namespace BridgeRpc.AspNetCore.Router.Basic { public class RpcMethod : IRpcMethod { public MethodInfo Prototype { get; set; } public RpcController Controller { get; set; } } }
25.090909
53
0.713768
[ "MIT" ]
zhshize/BridgeRpcAspNetCore
src/BridgeRpc.AspNetCore.Router/Basic/RpcMethod.cs
276
C#