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.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using DalSic; namespace Consultorio.ConsultaAmbulatoria.ControlPerinatal.Actividades { public partial class Default : System.Web.UI.Page { private int idPaciente { get { return ViewState["idPaciente"] == null ? 0 : Convert.ToInt32(ViewState["idPaciente"]); } set { ViewState["idPaciente"] = value; } } private int idHistoriaClinicaPerinatal { get { return ViewState["idHistoriaClinicaPerinatal"] == null ? 0 : Convert.ToInt32(ViewState["idHistoriaClinicaPerinatal"]); } set { ViewState["idHistoriaClinicaPerinatal"] = value; } } protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) return; int idTemp; if (Int32.TryParse(Request.QueryString["idHistoriaClinicaPerinatal"], out idTemp)) { idHistoriaClinicaPerinatal = idTemp; AprHistoriaClinicaPerinatal oHCP = new AprHistoriaClinicaPerinatal(idHistoriaClinicaPerinatal); if(!oHCP.Activa) { btnNuevo.Enabled = false; } rptActividades.DataSource = new AprActividadControlPerinatalCollection().Where(AprActividadControlPerinatal.Columns.IdHistoriaClinicaPerinatal, idTemp). OrderByDesc(AprActividadControlPerinatal.Columns.Fecha).Load(); rptActividades.DataBind(); } } protected void btnNuevo_Click(object sender, EventArgs e) { Response.Redirect(String.Format("Edit.aspx?idHistoriaClinicaPerinatal={0}", idHistoriaClinicaPerinatal)); } } }
38.5
168
0.628247
[ "MIT" ]
saludnqn/consultorio
Consultorio/ConsultaAmbulatoria/ControlPerinatal/Actividades/Default.aspx.cs
1,850
C#
namespace XrmFramework.MSBuild.Generation { public class MSBuildInformationProvider : IMSBuildInformationProvider { private readonly string _msbuildVersion; public MSBuildInformationProvider(string msbuildVersion) { _msbuildVersion = msbuildVersion; } public string GetMSBuildVersion() { return _msbuildVersion; } } }
22.888889
73
0.652913
[ "MIT" ]
cgoconseils/XrmFramework
src/XrmFramework.MSBuild.Generation/MSBuildInformationProvider.cs
412
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=\"667\">667</a>|Relation definition already exists| | | <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.| | * * The version of the OpenAPI document: 0.11.3648 * 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> /// The request used in the AggregatedReturns. /// </summary> [DataContract(Name = "AggregatedReturnsRequest")] public partial class AggregatedReturnsRequest : IEquatable<AggregatedReturnsRequest> { /// <summary> /// Initializes a new instance of the <see cref="AggregatedReturnsRequest" /> class. /// </summary> [JsonConstructorAttribute] protected AggregatedReturnsRequest() { } /// <summary> /// Initializes a new instance of the <see cref="AggregatedReturnsRequest" /> class. /// </summary> /// <param name="metrics">A list of metrics to calculate in the AggregatedReturns. (required).</param> /// <param name="recipeId">recipeId.</param> /// <param name="compositeMethod">The method used to calculate the Portfolio performance: Equal/Asset..</param> /// <param name="period">The type of the returns used to calculate the aggregation result: Daily/Monthly..</param> /// <param name="outputFrequency">The type of calculated output: Daily/Weekly/Monthly/Quarterly/Half-Yearly/Yearly..</param> /// <param name="alternativeInceptionDate">Optional - either a date, or the key for a portfolio property containing a date. If provided, the given date will override the inception date for this request..</param> public AggregatedReturnsRequest(List<PerformanceReturnsMetric> metrics = default(List<PerformanceReturnsMetric>), ResourceId recipeId = default(ResourceId), string compositeMethod = default(string), string period = default(string), string outputFrequency = default(string), string alternativeInceptionDate = default(string)) { // to ensure "metrics" is required (not null) this.Metrics = metrics ?? throw new ArgumentNullException("metrics is a required property for AggregatedReturnsRequest and cannot be null"); this.RecipeId = recipeId; this.CompositeMethod = compositeMethod; this.Period = period; this.OutputFrequency = outputFrequency; this.AlternativeInceptionDate = alternativeInceptionDate; } /// <summary> /// A list of metrics to calculate in the AggregatedReturns. /// </summary> /// <value>A list of metrics to calculate in the AggregatedReturns.</value> [DataMember(Name = "metrics", IsRequired = true, EmitDefaultValue = false)] public List<PerformanceReturnsMetric> Metrics { get; set; } /// <summary> /// Gets or Sets RecipeId /// </summary> [DataMember(Name = "recipeId", EmitDefaultValue = false)] public ResourceId RecipeId { get; set; } /// <summary> /// The method used to calculate the Portfolio performance: Equal/Asset. /// </summary> /// <value>The method used to calculate the Portfolio performance: Equal/Asset.</value> [DataMember(Name = "compositeMethod", EmitDefaultValue = true)] public string CompositeMethod { get; set; } /// <summary> /// The type of the returns used to calculate the aggregation result: Daily/Monthly. /// </summary> /// <value>The type of the returns used to calculate the aggregation result: Daily/Monthly.</value> [DataMember(Name = "period", EmitDefaultValue = true)] public string Period { get; set; } /// <summary> /// The type of calculated output: Daily/Weekly/Monthly/Quarterly/Half-Yearly/Yearly. /// </summary> /// <value>The type of calculated output: Daily/Weekly/Monthly/Quarterly/Half-Yearly/Yearly.</value> [DataMember(Name = "outputFrequency", EmitDefaultValue = true)] public string OutputFrequency { get; set; } /// <summary> /// Optional - either a date, or the key for a portfolio property containing a date. If provided, the given date will override the inception date for this request. /// </summary> /// <value>Optional - either a date, or the key for a portfolio property containing a date. If provided, the given date will override the inception date for this request.</value> [DataMember(Name = "alternativeInceptionDate", EmitDefaultValue = true)] public string AlternativeInceptionDate { 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 AggregatedReturnsRequest {\n"); sb.Append(" Metrics: ").Append(Metrics).Append("\n"); sb.Append(" RecipeId: ").Append(RecipeId).Append("\n"); sb.Append(" CompositeMethod: ").Append(CompositeMethod).Append("\n"); sb.Append(" Period: ").Append(Period).Append("\n"); sb.Append(" OutputFrequency: ").Append(OutputFrequency).Append("\n"); sb.Append(" AlternativeInceptionDate: ").Append(AlternativeInceptionDate).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 AggregatedReturnsRequest); } /// <summary> /// Returns true if AggregatedReturnsRequest instances are equal /// </summary> /// <param name="input">Instance of AggregatedReturnsRequest to be compared</param> /// <returns>Boolean</returns> public bool Equals(AggregatedReturnsRequest input) { if (input == null) return false; return ( this.Metrics == input.Metrics || this.Metrics != null && input.Metrics != null && this.Metrics.SequenceEqual(input.Metrics) ) && ( this.RecipeId == input.RecipeId || (this.RecipeId != null && this.RecipeId.Equals(input.RecipeId)) ) && ( this.CompositeMethod == input.CompositeMethod || (this.CompositeMethod != null && this.CompositeMethod.Equals(input.CompositeMethod)) ) && ( this.Period == input.Period || (this.Period != null && this.Period.Equals(input.Period)) ) && ( this.OutputFrequency == input.OutputFrequency || (this.OutputFrequency != null && this.OutputFrequency.Equals(input.OutputFrequency)) ) && ( this.AlternativeInceptionDate == input.AlternativeInceptionDate || (this.AlternativeInceptionDate != null && this.AlternativeInceptionDate.Equals(input.AlternativeInceptionDate)) ); } /// <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.Metrics != null) hashCode = hashCode * 59 + this.Metrics.GetHashCode(); if (this.RecipeId != null) hashCode = hashCode * 59 + this.RecipeId.GetHashCode(); if (this.CompositeMethod != null) hashCode = hashCode * 59 + this.CompositeMethod.GetHashCode(); if (this.Period != null) hashCode = hashCode * 59 + this.Period.GetHashCode(); if (this.OutputFrequency != null) hashCode = hashCode * 59 + this.OutputFrequency.GetHashCode(); if (this.AlternativeInceptionDate != null) hashCode = hashCode * 59 + this.AlternativeInceptionDate.GetHashCode(); return hashCode; } } } }
122.813397
16,252
0.628526
[ "MIT" ]
finbourne/lusid-sdk-csharp
sdk/Lusid.Sdk/Model/AggregatedReturnsRequest.cs
25,668
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 Image_Comparison.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Image_Comparison.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
38.736111
182
0.604518
[ "MIT" ]
adamchlebek/ImageComparison
Properties/Resources.Designer.cs
2,791
C#
using System; using DShop.Common.Messages; using Newtonsoft.Json; namespace DShop.Services.Discounts.Messages.Events { public class DiscountCreated : IEvent { public Guid Id { get; } public Guid CustomerId { get; } public string Code { get; } public double Percentage { get; } [JsonConstructor] public DiscountCreated(Guid id, Guid customerId, string code, double percentage) { Id = id; CustomerId = customerId; Code = code; Percentage = percentage; } } }
25.041667
56
0.577371
[ "MIT" ]
mpelekh/DNC-DShop.Services.Discounts
src/DShop.Services.Discounts/Messages/Events/DiscountCreated.cs
601
C#
using buildeR.Common.DTO.Message; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace buildeR.BLL.Interfaces { public interface IChatService { Task<MessageDTO> SendMessage(MessageDTO messageDTO); Task<List<MessageDTO>> GetGroupMessages(int groupId); } }
22.6
61
0.746313
[ "MIT" ]
BinaryStudioAcademy/bsa-2020-buildeR
backend/buildeR.BLL/Interfaces/IChatService.cs
341
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.InteropServices.ComTypes; using System.Runtime.Versioning; namespace System.Runtime.InteropServices { public static partial class Marshal { internal static bool IsBuiltInComSupported => false; public static int GetHRForException(Exception? e) { return e?.HResult ?? 0; } public static bool AreComObjectsAvailableForCleanup() => false; [SupportedOSPlatform("windows")] public static IntPtr CreateAggregatedObject(IntPtr pOuter, object o) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [RequiresUnreferencedCode("Built-in COM support is not trim compatible", Url = "https://aka.ms/dotnet-illink/com")] [SupportedOSPlatform("windows")] public static object BindToMoniker(string monikerName) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static void CleanupUnusedObjectsInCurrentContext() { } [SupportedOSPlatform("windows")] public static IntPtr CreateAggregatedObject<T>(IntPtr pOuter, T o) where T : notnull { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static object? CreateWrapperOfType(object? o, Type t) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static TWrapper CreateWrapperOfType<T, TWrapper>(T? o) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static void ChangeWrapperHandleStrength(object otp, bool fIsWeak) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static int FinalReleaseComObject(object o) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static IntPtr GetComInterfaceForObject(object o, Type T) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static IntPtr GetComInterfaceForObject(object o, Type T, CustomQueryInterfaceMode mode) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static IntPtr GetComInterfaceForObject<T, TInterface>([DisallowNull] T o) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static object? GetComObjectData(object obj, object key) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static IntPtr GetIDispatchForObject(object o) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static IntPtr GetIUnknownForObject(object o) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static void GetNativeVariantForObject(object? obj, IntPtr pDstNativeVariant) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static void GetNativeVariantForObject<T>(T? obj, IntPtr pDstNativeVariant) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static object GetTypedObjectForIUnknown(IntPtr pUnk, Type t) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static object GetObjectForIUnknown(IntPtr pUnk) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static object? GetObjectForNativeVariant(IntPtr pSrcNativeVariant) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static T? GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static object?[] GetObjectsForNativeVariants(IntPtr aSrcNativeVariant, int cVars) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static int GetStartComSlot(Type t) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static int GetEndComSlot(Type t) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } #pragma warning disable IDE0060 internal static Type? GetTypeFromCLSID(Guid clsid, string? server, bool throwOnError) { if (throwOnError) throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); return null; } #pragma warning restore IDE0060 [SupportedOSPlatform("windows")] public static string GetTypeInfoName(ITypeInfo typeInfo) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static object GetUniqueObjectForIUnknown(IntPtr unknown) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static bool IsComObject(object o!!) => false; public static bool IsTypeVisibleFromCom(Type t!!) => false; [SupportedOSPlatform("windows")] public static int ReleaseComObject(object o) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } [SupportedOSPlatform("windows")] public static bool SetComObjectData(object obj, object key, object? data) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } } }
36.210784
123
0.678218
[ "MIT" ]
BodyBuildingKang/runtime
src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.NoCom.cs
7,387
C#
using System; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Miningcore.Blockchain.Ethereum; using Miningcore.Contracts; using Miningcore.Extensions; using Miningcore.Messaging; using Miningcore.Native; using Miningcore.Notifications.Messages; using NLog; namespace Miningcore.Crypto.Hashing.Ethash { public class Dag : IDisposable { public Dag(ulong epoch) { Epoch = epoch; } public ulong Epoch { get; set; } private IntPtr handle = IntPtr.Zero; private static readonly Semaphore sem = new(1, 1); internal static IMessageBus messageBus; public DateTime LastUsed { get; set; } public static unsafe string GetDefaultDagDirectory() { var chars = new byte[512]; fixed (byte* data = chars) { if(LibEthhash.ethash_get_default_dirname(data, chars.Length)) { int length; for(length = 0; length < chars.Length; length++) { if(data[length] == 0) break; } return Encoding.UTF8.GetString(data, length); } } return null; } public void Dispose() { if(handle != IntPtr.Zero) { LibEthhash.ethash_full_delete(handle); handle = IntPtr.Zero; } } public async ValueTask GenerateAsync(string dagDir, ILogger logger, CancellationToken ct) { Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(dagDir), $"{nameof(dagDir)} must not be empty"); if(handle == IntPtr.Zero) { await Task.Run(() => { try { sem.WaitOne(); // re-check after obtaining lock if(handle != IntPtr.Zero) return; logger.Info(() => $"Generating DAG for epoch {Epoch}"); var started = DateTime.Now; var block = Epoch * EthereumConstants.EpochLength; // Generate a temporary cache var light = LibEthhash.ethash_light_new(block); try { // Generate the actual DAG handle = LibEthhash.ethash_full_new(dagDir, light, progress => { logger.Info(() => $"Generating DAG for epoch {Epoch}: {progress}%"); return !ct.IsCancellationRequested ? 0 : 1; }); if(handle == IntPtr.Zero) throw new OutOfMemoryException("ethash_full_new IO or memory error"); logger.Info(() => $"Done generating DAG for epoch {Epoch} after {DateTime.Now - started}"); } finally { if(light != IntPtr.Zero) LibEthhash.ethash_light_delete(light); } } finally { sem.Release(); } }, ct); } } public unsafe bool Compute(ILogger logger, byte[] hash, ulong nonce, out byte[] mixDigest, out byte[] result) { Contract.RequiresNonNull(hash, nameof(hash)); logger.LogInvoke(); var sw = Stopwatch.StartNew(); mixDigest = null; result = null; var value = new LibEthhash.ethash_return_value(); fixed (byte* input = hash) { LibEthhash.ethash_full_compute(handle, input, nonce, ref value); } if(value.success) { mixDigest = value.mix_hash.value; result = value.result.value; } messageBus?.SendTelemetry("Ethash", TelemetryCategory.Hash, sw.Elapsed, value.success); return value.success; } } }
29.899329
119
0.46532
[ "MIT" ]
4AlexG/miningcore
src/Miningcore/Crypto/Hashing/Ethash/Dag.cs
4,455
C#
namespace BattleshipGame.Models.Ships { public class Cruiser : Ship { public Cruiser() { Name = "Cruiser"; BattleShipType = BattleShipType.Cruiser; Holes = 3; Hits = 0; } } }
15.5
46
0.580645
[ "MIT-0" ]
jiteshkaranjkar/battleshipgame
.aws-sam/build/getAllItemsFunction/src/BattleshipGame/Models/Ships/Cruiser.cs
217
C#
using UnityEngine; using UnityEngine.Events; using System.Collections.Generic; namespace Lean.Touch { /// <summary>This component allows you to detect when a specific amount of fingers begin touching the screen.</summary> [HelpURL(LeanTouch.PlusHelpUrlPrefix + "LeanMultiHeld")] [AddComponentMenu(LeanTouch.ComponentPathPrefix + "Multi Held")] public class LeanMultiHeld : MonoBehaviour { [System.Serializable] public class FingerData : LeanFingerData { public Vector2 Movement; } [System.Serializable] public class LeanFingerListEvent : UnityEvent<List<LeanFinger>> {} [System.Serializable] public class Vector3Event : UnityEvent<Vector3> {} [System.Serializable] public class Vector2Event : UnityEvent<Vector2> {} /// <summary>Ignore fingers with StartedOverGui?</summary> public bool IgnoreStartedOverGui = true; /// <summary>Ignore fingers with IsOverGui?</summary> public bool IgnoreIsOverGui; /// <summary>Do nothing if this LeanSelectable isn't selected?</summary> public LeanSelectable RequiredSelectable; /// <summary>The amount of fingers we are interested in.</summary> public int RequiredCount = 2; /// <summary>The finger must be held for this many seconds.</summary> public float MinimumAge = 1.0f; /// <summary>The finger cannot move more than this many pixels relative to the reference DPI.</summary> public float MaximumMovement = 5.0f; /// <summary>This event will be called if the above conditions are met when you begin holding fingers down.</summary> public LeanFingerListEvent OnFingersDown { get { if (onFingersDown == null) onFingersDown = new LeanFingerListEvent(); return onFingersDown; } } [SerializeField] private LeanFingerListEvent onFingersDown; /// <summary>This event will be called if the above conditions are met when you begin holding fingers down.</summary> public LeanFingerListEvent OnFingersUpdate { get { if (onFingersUpdate == null) onFingersUpdate = new LeanFingerListEvent(); return onFingersUpdate; } } [SerializeField] private LeanFingerListEvent onFingersUpdate; /// <summary>This event will be called if the above conditions are no longer met.</summary> public LeanFingerListEvent OnFingersUp { get { if (onFingersUp == null) onFingersUp = new LeanFingerListEvent(); return onFingersUp; } } [SerializeField] private LeanFingerListEvent onFingersUp; /// <summary>The method used to find world coordinates from a finger. See LeanScreenDepth documentation for more information.</summary> public LeanScreenDepth ScreenDepth = new LeanScreenDepth(LeanScreenDepth.ConversionType.DepthIntercept); /// <summary>This event will be called if the above conditions are met when you first touch the screen. /// Vector3 = Finger position in world space.</summary> public Vector3Event OnWorldDown { get { if (onWorldDown == null) onWorldDown = new Vector3Event(); return onWorldDown; } } [SerializeField] private Vector3Event onWorldDown; /// <summary>This event will be called if the above conditions are met when you first touch the screen. /// Vector3 = Finger position in world space.</summary> public Vector3Event OnWorldUpdate { get { if (onWorldUpdate == null) onWorldUpdate = new Vector3Event(); return onWorldUpdate; } } [SerializeField] private Vector3Event onWorldUpdate; /// <summary>This event will be called if the above conditions are met when you first touch the screen. /// Vector3 = Finger position in world space.</summary> public Vector3Event OnWorldUp { get { if (onWorldUp == null) onWorldUp = new Vector3Event(); return onWorldUp; } } [SerializeField] private Vector3Event onWorldUp; /// <summary>This event will be called if the above conditions are met when you first touch the screen. /// Vector2 = Finger position in screen space.</summary> public Vector2Event OnScreenDown { get { if (onScreenDown == null) onScreenDown = new Vector2Event(); return onScreenDown; } } [SerializeField] private Vector2Event onScreenDown; /// <summary>This event will be called if the above conditions are met when you first touch the screen. /// Vector2 = Finger position in screen space.</summary> public Vector2Event OnScreenUpdate { get { if (onScreenUpdate == null) onScreenUpdate = new Vector2Event(); return onScreenUpdate; } } [SerializeField] private Vector2Event onScreenUpdate; /// <summary>This event will be called if the above conditions are met when you first touch the screen. /// Vector2 = Finger position in screen space.</summary> public Vector2Event OnScreenUp { get { if (onScreenUp == null) onScreenUp = new Vector2Event(); return onScreenUp; } } [SerializeField] private Vector2Event onScreenUp; // Additional finger data [SerializeField] private List<LeanFinger> fingers = new List<LeanFinger>(); // Additional finger data [SerializeField] private List<FingerData> fingerDatas = new List<FingerData>(); [SerializeField] private bool held; [SerializeField] private float duration; #if UNITY_EDITOR protected virtual void Reset() { RequiredSelectable = GetComponentInParent<LeanSelectable>(); } #endif protected virtual void Awake() { if (RequiredSelectable == null) { RequiredSelectable = GetComponentInParent<LeanSelectable>(); } } protected virtual void OnEnable() { LeanTouch.OnFingerDown += HandleFingerDown; LeanTouch.OnGesture += HandleGesture; } protected virtual void OnDisable() { LeanTouch.OnFingerDown -= HandleFingerDown; LeanTouch.OnGesture -= HandleGesture; } private void HandleFingerDown(LeanFinger finger) { if (IgnoreStartedOverGui == true && finger.StartedOverGui == true) { return; } // Get link for this finger and reset var fingerData = LeanFingerData.FindOrCreate(ref fingerDatas, finger); fingerData.Movement = Vector2.zero; fingers.Add(finger); } private void HandleGesture(List<LeanFinger> tempFingers) { for (var i = fingers.Count - 1; i >= 0; i--) { // Try and find the link for this finger var finger = fingers[i]; var fingerData = fingerDatas[i]; if (finger.Set == true) { fingerData.Movement += finger.ScaledDelta; } else { fingers.RemoveAt(i); fingerDatas.RemoveAt(i); } } if (IsHeld == true) { duration += Time.deltaTime; if (held == false && duration >= MinimumAge) { held = true; InvokeDown(); } InvokeUpdate(); } else { duration = 0.0f; if (held == true) { held = false; InvokeUp(); } } } private bool IsHeld { get { if (RequiredCount == 0 || fingerDatas.Count != RequiredCount) { return false; } if (RequiredSelectable != null && RequiredSelectable.IsSelected == false) { return false; } foreach (var fingerData in fingerDatas) { if (fingerData.Movement.magnitude > MaximumMovement) { return false; } } return true; } } private void InvokeDown() { if (onFingersDown != null) { onFingersDown.Invoke(fingers); } var screenPosition = LeanGesture.GetScreenCenter(fingers); if (onWorldDown != null) { var position = ScreenDepth.Convert(screenPosition, gameObject); onWorldDown.Invoke(position); } if (onScreenDown != null) { onScreenDown.Invoke(screenPosition); } } private void InvokeUpdate() { if (onFingersUpdate != null) { onFingersUpdate.Invoke(fingers); } var screenPosition = LeanGesture.GetScreenCenter(fingers); if (onWorldUpdate != null) { var position = ScreenDepth.Convert(screenPosition, gameObject); onWorldUpdate.Invoke(position); } if (onScreenUpdate != null) { onScreenUpdate.Invoke(screenPosition); } } private void InvokeUp() { if (onFingersUp != null) { onFingersUp.Invoke(fingers); } var screenPosition = LeanGesture.GetScreenCenter(fingers); if (onWorldUp != null) { var position = ScreenDepth.Convert(screenPosition, gameObject); onWorldUp.Invoke(position); } if (onScreenUp != null) { onScreenUp.Invoke(screenPosition); } } } } #if UNITY_EDITOR namespace Lean.Touch.Inspector { using UnityEditor; [CanEditMultipleObjects] [CustomEditor(typeof(LeanMultiHeld))] public class LeanMultiHeld_Inspector : Lean.Common.LeanInspector<LeanMultiHeld> { private bool showUnusedEvents; protected override void DrawInspector() { Draw("IgnoreStartedOverGui", "Ignore fingers with StartedOverGui?"); Draw("IgnoreIsOverGui", "Ignore fingers with IsOverGui?"); Draw("RequiredSelectable", "Do nothing if this LeanSelectable isn't selected?"); Draw("RequiredCount", "The amount of fingers we are interested in."); Draw("MinimumAge", "The finger must be held for this many seconds."); Draw("MaximumMovement", "The finger cannot move more than this many pixels relative to the reference DPI."); EditorGUILayout.Separator(); var usedA = Any(t => t.OnFingersDown.GetPersistentEventCount() > 0); var usedB = Any(t => t.OnFingersUpdate.GetPersistentEventCount() > 0); var usedC = Any(t => t.OnFingersUp.GetPersistentEventCount() > 0); var usedD = Any(t => t.OnWorldDown.GetPersistentEventCount() > 0); var usedE = Any(t => t.OnWorldUpdate.GetPersistentEventCount() > 0); var usedF = Any(t => t.OnWorldUp.GetPersistentEventCount() > 0); var usedG = Any(t => t.OnScreenDown.GetPersistentEventCount() > 0); var usedH = Any(t => t.OnScreenUpdate.GetPersistentEventCount() > 0); var usedI = Any(t => t.OnScreenUp.GetPersistentEventCount() > 0); EditorGUI.BeginDisabledGroup(usedA && usedB && usedC && usedD && usedE && usedF && usedG && usedH && usedI); showUnusedEvents = EditorGUILayout.Foldout(showUnusedEvents, "Show Unused Events"); EditorGUI.EndDisabledGroup(); EditorGUILayout.Separator(); if (usedA == true || showUnusedEvents == true) { Draw("onFingersDown"); } if (usedB == true || showUnusedEvents == true) { Draw("onFingersUpdate"); } if (usedC == true || showUnusedEvents == true) { Draw("onFingersUp"); } if (usedD == true || usedE == true || usedF == true || showUnusedEvents == true) { Draw("ScreenDepth"); } if (usedD == true || showUnusedEvents == true) { Draw("onWorldDown"); } if (usedE == true || showUnusedEvents == true) { Draw("onWorldUpdate"); } if (usedF == true || showUnusedEvents == true) { Draw("onWorldUp"); } if (usedG == true || showUnusedEvents == true) { Draw("onScreenDown"); } if (usedH == true || showUnusedEvents == true) { Draw("onScreenUpdate"); } if (usedI == true || showUnusedEvents == true) { Draw("onScreenUp"); } } } } #endif
30.01108
216
0.697526
[ "MIT" ]
JohnnyCenter/SpaceShooter
Assets/Lean/Touch+/Scripts/LeanMultiHeld.cs
10,834
C#
using System; using StoreModels; using Xunit; namespace StoreTests { public class UnitTest1 { private Inventory inv = new Inventory(); [Theory] [InlineData (0, true)] [InlineData(-2, false)] public void CheckQuantity(int q, bool expected) { bool result = inv.CheckQuantity(q); Assert.Equal(result, expected); } } }
21.157895
55
0.584577
[ "MIT" ]
210215-USF-NET/Hans_Mittig-P0
StoreTests/UnitTest1.cs
402
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SteuerSoft.Network.Protocol.Util; namespace SteuerSoft.Network.Protocol.Client.Material { public class MethodCaller<TParam, TResult> { private Func<WapEndPoint, TParam, Task<TResult>> _caller; public WapEndPoint EndPoint { get; } internal MethodCaller(Func<WapEndPoint, TParam, Task<TResult>> caller, WapEndPoint endPoint) { _caller = caller; EndPoint = endPoint; } public Task<TResult> Call(TParam param) { return _caller(EndPoint, param); } } }
24.5
100
0.657434
[ "MIT" ]
2steuer/wap-protocol
SteuerSoft.Network.Protocol.Client/Material/MethodCaller.cs
688
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.Network.V20181001.Inputs { /// <summary> /// Connection draining allows open connections to a backend server to be active for a specified time after the backend server got removed from the configuration. /// </summary> public sealed class ApplicationGatewayConnectionDrainingArgs : Pulumi.ResourceArgs { /// <summary> /// The number of seconds connection draining is active. Acceptable values are from 1 second to 3600 seconds. /// </summary> [Input("drainTimeoutInSec", required: true)] public Input<int> DrainTimeoutInSec { get; set; } = null!; /// <summary> /// Whether connection draining is enabled or not. /// </summary> [Input("enabled", required: true)] public Input<bool> Enabled { get; set; } = null!; public ApplicationGatewayConnectionDrainingArgs() { } } }
35.114286
166
0.672091
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20181001/Inputs/ApplicationGatewayConnectionDrainingArgs.cs
1,229
C#
#region Using directives using System.IO; using System.Linq; using System.Reflection; using NBi.Xml; using NBi.Xml.Constraints; using NUnit.Framework; using NBi.Xml.Constraints.Comparer; using NBi.Core.ResultSet; #endregion namespace NBi.Testing.Xml.Unit.Constraints { [TestFixture] public class SingleRowXmlTest : BaseXmlTest { [Test] public void Deserialize_SampleFile_ReadCorrectlyNoRows() { int testNr = 0; // Create an instance of the XmlSerializer specifying type and namespace. TestSuiteXml ts = DeserializeSample(); Assert.That(ts.Tests[testNr].Constraints, Has.Count.EqualTo(1)); Assert.That(ts.Tests[testNr].Constraints[0], Is.TypeOf<SingleRowXml>()); Assert.That(ts.Tests[testNr].Constraints[0].Not, Is.False); } [Test] public void Deserialize_SampleFile_ReadCorrectlyFormulaComparer() { int testNr = 0; // Create an instance of the XmlSerializer specifying type and namespace. TestSuiteXml ts = DeserializeSample(); var singleRow = ts.Tests[testNr].Constraints[0] as SingleRowXml; var comparison = singleRow.Predication; Assert.That((comparison.Operand as ColumnNameIdentifier).Name, Is.EqualTo("ModDepId")); Assert.That(comparison.ColumnType, Is.EqualTo(ColumnType.Numeric)); Assert.That(comparison.Predicate, Is.TypeOf<MoreThanXml>()); Assert.That(comparison.Predicate.Not, Is.EqualTo(false)); var moreThan = comparison.Predicate as MoreThanXml; Assert.That(moreThan.Reference, Is.EqualTo("10")); } } }
32.903846
99
0.658095
[ "Apache-2.0" ]
TheAutomatingMrLynch/NBi
NBi.Testing.Xml/Constraints/SingleRowXmlTest.cs
1,713
C#
namespace SimpleShop.AdminApp.Commands { using Contracts; using IO.Contracts; using Services.Contracts; public class LoginCommand : ICommand { private readonly IConsoleReader reader; private readonly IConsoleWriter writer; private readonly IAdminSessionService adminSessionService; public LoginCommand( IConsoleReader reader, IConsoleWriter writer, IAdminSessionService adminSessionService) { this.reader = reader; this.writer = writer; this.adminSessionService = adminSessionService; } public string Execute() { if (this.adminSessionService.IsLoggedIn()) { return "Please logout!"; } this.writer.Write("Enter username: "); var username = this.reader.ReadLine(); this.writer.Write("Enter password: "); var password = this.reader.ReadLine(); var admin = this.adminSessionService.Login(username, password); if (admin == null) { return "Invalid username or password!"; } return $"Admin {admin.Username} login successfully!"; } } }
27.255319
75
0.57299
[ "MIT" ]
kalintsenkov/SimpleShopConsoleApp
SimpleShop.AdminApp/Commands/LoginCommand.cs
1,283
C#
using System; using System.Runtime.InteropServices; namespace RustCSharp { class Program { [DllImport("blotout.dll", EntryPoint = "bo_session_end")] private static extern void bo_session_end(); [DllImport("blotout.dll", EntryPoint = "bo_init")] private static extern void bo_init(string token, string sdk_end_point); [DllImport("blotout.dll", EntryPoint = "bo_capture")] private static extern void bo_capture(string event_name, string json_string); [DllImport("blotout.dll", EntryPoint = "bo_log_pii_event")] private static extern void bo_log_pii_event(string event_name, string json_string); [DllImport("blotout.dll", EntryPoint = "bo_log_phi_event")] private static extern void bo_log_phi_event(string event_name, string json_string); [DllImport("blotout.dll", EntryPoint = "bo_enable_log")] private static extern void bo_enable_log(bool log_enabled); static void Main(string[] args) { Console.WriteLine("Hello World!"); TestSDKInit(); TestPublishEvents(); TestPublishPHIEvents(); TestPublishPIIEvents(); } private static void TestSDKInit() { string token = "BEZAVGGW4GZZZ3N"; string endPoint = "http://stage.blotout.io"; string bundleID = "com.blotout.rustsaleDemoApp"; bo_init(token, endPoint, bundleID); } private static void TestPublishEvents() { string eventName = "Rust Event from sdk testing"; string jsonString = "{\"some property\": \"some value\", \"some other property\": \"some other value\"}"; bo_capture(eventName,jsonString); } private static void TestPublishPIIEvents() { string eventName = "Rust Event from sdk testing"; string jsonString = "{\"email id\": \"ankuradhikari08@gmail.com\", \"gender\": \"male\"}"; bo_log_pii_event(eventName, jsonString); } private static void TestPublishPHIEvents() { string eventName = "Rust Event from sdk testing"; string jsonString = "{\"email id\": \"ankur@blotout.io\", \"gender\": \"male\"}"; bo_log_phi_event(eventName, jsonString); } } }
38.721311
152
0.612193
[ "MIT" ]
blotoutio/sdk-rust
demo/windows/RustCSharp/RustCSharp/Program.cs
2,364
C#
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using KSP.UI.Screens; using ToolbarControl_NS; using System.Collections; namespace StageRecovery { [KSPAddon(KSPAddon.Startup.FlightEditorAndKSC, false)] public class StageRecovery : MonoBehaviour { public static StageRecovery instance; //Flag that says whether the VesselDestroyEvent has been added, so we don't accidentally add it twice. //private bool eventAdded = false; private bool sceneChangeComplete = false; private Coroutine recalculateCoroutine; private List<RecoveryItem> RecoveryQueue = new List<RecoveryItem>(); //Vessels added to this are pre-recovered private List<Guid> StageWatchList = new List<Guid>(); //Vessels added to this list are watched for pre-recovery private static Dictionary<Guid, double> RecoverAttemptLog = new Dictionary<Guid, double>(); //Vessel guid <-> UT at time of recovery. For checking for duplicates. UT is so we can clear if we revert. //We persist this throughout a whole gaming session just so it isn't wiped out by scene changes private static double cutoffAlt = 23000; //List of scenes where we shouldn't run the mod. I toyed with runOnce, but couldn't get it working private static List<GameScenes> forbiddenScenes = new List<GameScenes> { GameScenes.LOADING, GameScenes.LOADINGBUFFER, GameScenes.CREDITS, GameScenes.MAINMENU, GameScenes.SETTINGS }; //Fired when the mod loads each scene public void Awake() { Log.Info("[SR] Awake Start"); instance = this; //If we're in the MainMenu, don't do anything if (forbiddenScenes.Contains(HighLogic.LoadedScene)) { return; } } private void OnGUI() { if (Settings.Instance != null && Settings.Instance.gui != null) { Settings.Instance.gui.SetGUIPositions(); } } //When the scene changes and the mod is destroyed public void OnDestroy() { //If we're in the MainMenu, don't do anything if (forbiddenScenes.Contains(HighLogic.LoadedScene) || Settings.Instance == null || Settings.Instance.gui == null) { return; } Settings.Instance.gui.DoOnDestroy(); GameEvents.onGameSceneLoadRequested.Remove(GameSceneLoadEvent); GameEvents.onVesselWillDestroy.Remove(VesselDestroyEvent); GameEvents.onVesselGoOnRails.Remove(VesselUnloadEvent); GameEvents.OnGameSettingsApplied.Remove(GameSettingsAppliedEvent); if (HighLogic.LoadedSceneIsEditor) { GameEvents.onEditorShipModified.Remove(ShipModifiedEvent); } } //Fired when the mod loads each scene public void Start() { Log.Info("[SR] Start start"); if (Settings.Instance != null) { Settings.Instance.gui.hideAll(); } //If we're in the MainMenu, don't do anything if (forbiddenScenes.Contains(HighLogic.LoadedScene)) { return; } Settings.Instance.gui.InitializeToolbar(this.gameObject); //If the event hasn't been added yet, run this code (adds the event and the stock button) //if (!eventAdded) { GameEvents.onGameSceneLoadRequested.Add(GameSceneLoadEvent); //Add the VesselDestroyEvent to the listeners //GameEvents.onVesselDestroy.Add(VesselDestroyEvent); GameEvents.onVesselWillDestroy.Add(VesselDestroyEvent); //Add the event that listens for unloads (for removing launch clamps) GameEvents.onVesselGoOnRails.Add(VesselUnloadEvent); //GameEvents..Add(DecoupleEvent); GameEvents.OnGameSettingsApplied.Add(GameSettingsAppliedEvent); GameEvents.onVesselRecovered.Add(onVesselRecovered); GameEvents.onVesselTerminated.Add(onVesselTerminated); cutoffAlt = ComputeCutoffAlt(Planetarium.fetch.Home) + 1000; Log.Info("[SR] Determined cutoff altitude to be " + cutoffAlt); //Register with the RecoveryController (do we only do this once?) var s = RecoveryControllerWrapper.RegisterModWithRecoveryController("StageRecovery"); Log.Info("[SR] RecoveryController registration success: " + s); //Set the eventAdded flag to true so this code doesn't run again //eventAdded = true; //Confine the RecoveryModifier to be between 0 and 1 Settings2.Instance.RecoveryModifier = (Settings2.Instance.RecoveryModifier < 0) ? 0 : (Settings2.Instance.RecoveryModifier > 1) ? 1 : Settings2.Instance.RecoveryModifier; //Load and resave the BlackList. The save ensures that the file will be created if it doesn't exist. Settings.Instance.BlackList.Load(); Settings.Instance.BlackList.Save(); } if (!HighLogic.LoadedSceneIsFlight) { Settings.Instance.ClearStageLists(); } if (HighLogic.LoadedSceneIsFlight) { foreach (Vessel v in FlightGlobals.Vessels) { TryWatchVessel(v); } } if (HighLogic.LoadedSceneIsEditor) { GameEvents.onEditorShipModified.Add(ShipModifiedEvent); } //Remove anything that happens in the future List<Guid> removeList = new List<Guid>(); double currentUT = Planetarium.GetUniversalTime(); foreach (KeyValuePair<Guid, double> logItem in RecoverAttemptLog) { if (logItem.Value >= currentUT) { removeList.Add(logItem.Key); } } foreach (Guid removeItem in removeList) { RecoverAttemptLog.Remove(removeItem); } //end future removal sceneChangeComplete = true; } void onVesselRecovered(ProtoVessel pv, bool b) { Log.Info("onVesselRecovered: " + pv.vesselName); } void onVesselTerminated(ProtoVessel pv) { Log.Info("onVesselTerminated: " + pv.vesselName); } private IEnumerator DelayedRecalculate() { yield return new WaitForSecondsRealtime(Settings1.Instance.autocalcDelaySec); EditorGUI.Instance.Recalculate(); recalculateCoroutine = null; } public void ShipModifiedEvent(ShipConstruct sc) { if (recalculateCoroutine != null) StopCoroutine(recalculateCoroutine); recalculateCoroutine = StartCoroutine(DelayedRecalculate()); } public void GameSceneLoadEvent(GameScenes newScene) { sceneChangeComplete = false; if (newScene != GameScenes.FLIGHT) { clampsRecovered.Clear(); } } private List<Vessel> clampsRecovered = new List<Vessel>(); public void VesselUnloadEvent(Vessel vessel) { //If we're disabled, just return if (!Settings1.Instance.SREnabled) { return; } //If the vessel or the protovessel are null then we surely can't do anything with them if (vessel == null || vessel.protoVessel == null) { return; } ProtoVessel pv = vessel.protoVessel; //If we aren't supposed to recover clamps, then don't try. if (Settings1.Instance.RecoverClamps) { //If we've already recovered the clamps, then no need to try again if (clampsRecovered.Find(a => a.id == vessel.id) != null) { return; } //Assign the pv variable to the protovessel, then look for if the root is a clamp if (pv.protoPartSnapshots.Count > 0 && pv.protoPartSnapshots[0].modules.Exists(m => m.moduleName == "LaunchClamp")) { //We look for the launchclamp module, which will hopefully cover FASA and stock. Log.Info("[SR] Recovering a clamp!"); //Add it to the recovered clamps list so we don't try to recover it again clampsRecovered.Add(vessel); float totalRefund = 0; //Loop over all the parts and calculate their cost (we recover at 100% since we're at the launchpad/runway) foreach (ProtoPartSnapshot pps in pv.protoPartSnapshots) { float out1, out2; totalRefund += ShipConstruction.GetPartCosts(pps, pps.partInfo, out out1, out out2); } //Add dem funds to da total. Get dem funds! AddFunds(totalRefund); //Fire the successful recovery event. Even though this isn't a stage we still need to do this for things like KCT to recover the parts. //Can be averted with stock functions if I can get them working properly APIManager.instance.RecoverySuccessEvent.Fire(vessel, new float[] { 100, totalRefund, 0 }, "SUCCESS"); //And then we try a bunch of things to make sure the clamps are removed (remove it from the flight state, kill it, and destroy it) HighLogic.CurrentGame.flightState.protoVessels.Remove(pv); vessel.Die(); Destroy(vessel); //So, question for myself. Would it be better to try to manually fire the recovery events? Would that really be worth anything? } } //If it's a stage that will be destroyed, we need to manually recover the Kerbals if (Settings1.Instance.PreRecover && pv.GetVesselCrew().Count > 0) { //Check if the conditions for vessel destruction are met if (vessel != FlightGlobals.ActiveVessel && !vessel.isEVA && vessel.mainBody == Planetarium.fetch.Home && pv.situation != Vessel.Situations.LANDED && vessel.altitude < cutoffAlt && vessel.altitude > 0 && (FlightGlobals.ActiveVessel.transform.position - vessel.transform.position).sqrMagnitude > Math.Pow(vessel.vesselRanges.GetSituationRanges(Vessel.Situations.FLYING).pack, 2) - 250) { Log.Info("[SR] Vessel " + pv.vesselName + " is going to be destroyed. Pre-recovering!"); //Kerbal death should be handled by SR instead RecoverVessel(vessel, true); } else { TryWatchVessel(vessel); } } } void GameSettingsAppliedEvent() { Settings.Instance.gui.DoOnDestroy(); Settings.Instance.gui.InitializeToolbar(this.gameObject); } public void FixedUpdate() { if (!sceneChangeComplete) { return; } //For each vessel in the watchlist, check to see if it reaches an atm density of 0.01 and if so, pre-recover it foreach (Guid id in new List<Guid>(StageWatchList)) { Vessel vessel = FlightGlobals.Vessels.Find(v => v.id == id); if (vessel == null) { StageWatchList.Remove(id); continue; } if ((!vessel.loaded || vessel.packed) && vessel.mainBody == Planetarium.fetch.Home && vessel.altitude < cutoffAlt && vessel.altitude > 0 && (FlightGlobals.ActiveVessel.transform.position - vessel.transform.position).sqrMagnitude > Math.Pow(vessel.vesselRanges.GetSituationRanges(Vessel.Situations.FLYING).pack, 2) - 250) { if (!SRShouldRecover(vessel)) { StageWatchList.Remove(id); continue; } Log.Info($"[SR] Vessel {vessel.vesselName} ({id}) is about to be destroyed at altitude {vessel.altitude}. Pre-recovering vessel."); RecoverVessel(vessel, true); StageWatchList.Remove(id); } } } public static float ComputeCutoffAlt(CelestialBody body, float stepSize = 100) { float alt = (float)body.atmosphereDepth; while (alt > 0) { double pres = body.GetPressure(alt); if (pres < 1.0) { alt -= stepSize; } else { break; } } return alt; } public static bool TryWatchVessel(Vessel ves) { if (FMRS_Enabled(false)) //If FMRS is active then we don't watch any vessels (we don't care if it's watching for chutes at all, we just need to know if it's on) { return false; } //If the vessel is around the home planet and the periapsis is below 23km, then we add it to the watch list //must have crew as well if (ves != null && FlightGlobals.ActiveVessel != ves && ves.situation != Vessel.Situations.LANDED && ves.situation != Vessel.Situations.PRELAUNCH && ves.situation != Vessel.Situations.SPLASHED && ves.protoVessel.GetVesselCrew().Count > 0 && ves.orbit != null && ves.mainBody == Planetarium.fetch.Home && ves.orbit.PeA < cutoffAlt && !ves.isEVA && ves.altitude > 0) { if (instance.StageWatchList.Contains(ves.id)) { return true; } instance.StageWatchList.Add(ves.id); Log.Info("[SR] Added vessel " + ves.vesselName + " (" + ves.id + ") to watchlist."); return true; } return false; } //Small function to add funds to the game and write a log message about it. //Returns the new total. public static double AddFunds(double toAdd) { if (HighLogic.CurrentGame.Mode != Game.Modes.CAREER) { return 0; } Funding.Instance.AddFunds(toAdd, TransactionReasons.VesselRecovery); Log.Info("[SR] Adding funds: " + toAdd + ", New total: " + Funding.Instance.Funds); return (Funding.Instance.Funds); } public static int BuildingUpgradeLevel(SpaceCenterFacility facility) { int lvl = 0; if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER && Settings1.Instance.UseUpgrades) { lvl = (int)Math.Round((ScenarioUpgradeableFacilities.GetFacilityLevelCount(facility) * ScenarioUpgradeableFacilities.GetFacilityLevel(facility))); } else { lvl = ScenarioUpgradeableFacilities.GetFacilityLevelCount(facility); //returns 2 for VAB in Sandbox } return lvl; } //Function to estimate the final velocity given a stage's mass and parachute info public static double VelocityEstimate(double mass, double chuteAreaTimesCd) { if (chuteAreaTimesCd <= 0) { return 200; } if (mass <= 0) { return 0; } CelestialBody home = Planetarium.fetch.Home; return Math.Sqrt((2000 * mass * 9.81) / (home.GetDensity(home.GetPressure(0), home.GetTemperature(0)) * chuteAreaTimesCd)); //This is according to the formulas used by Stupid_Chris in the Real Chute drag calculator program included with Real Chute. Source: https://github.com/StupidChris/RealChute/blob/master/Drag%20Calculator/RealChute%20drag%20calculator/RCDragCalc.cs } //Helper function that I found on StackExchange that helps immensly with dealing with Reflection. I'm not that good at reflection (accessing other mod's functions and data) public static object GetMemberInfoValue(System.Reflection.MemberInfo member, object sourceObject) { object newVal; if (member is System.Reflection.FieldInfo) { newVal = ((System.Reflection.FieldInfo)member).GetValue(sourceObject); } else { newVal = ((System.Reflection.PropertyInfo)member).GetValue(sourceObject, null); } return newVal; } /// <summary> /// Check to see if FMRS is installed and enabled /// </summary> /// <param name="parachuteSetting">If true, check if the defer parachutes to SR is set (and enabled). Otherwise return only the enabled state. /// Defaults to true.</param> public static bool FMRS_Enabled(bool parachuteSetting = true) { try { Type FMRSType = null; AssemblyLoader.loadedAssemblies.TypeOperation(t => { if (t.FullName == "FMRS.FMRS_Util") { FMRSType = t; } }); if (FMRSType == null) { return false; } UnityEngine.Object FMRSUtilClass = GameObject.FindObjectOfType(FMRSType); bool enabled = (bool)GetMemberInfoValue(FMRSType.GetMember("_SETTING_Enabled")[0], FMRSUtilClass); if (enabled) { enabled = (bool)GetMemberInfoValue(FMRSType.GetMember("_SETTING_Armed")[0], FMRSUtilClass); } //if we are checking the parachute setting is set if (enabled && parachuteSetting) { enabled = (bool)GetMemberInfoValue(FMRSType.GetMember("_SETTING_Parachutes")[0], null); //this setting is a static if (enabled) { enabled = !(bool)GetMemberInfoValue(FMRSType.GetMember("_SETTING_Defer_Parachutes_to_StageRecovery")[0], null); //this setting is a static //we "not" it because if they're deferring to us then it's the same as them being disabled (when not considering crew or probes) } } return enabled; } catch (Exception ex) { Debug.LogException(ex); return false; } } //The main show. The VesselDestroyEvent is activated whenever KSP destroys a vessel. We only care about it in a specific set of circumstances private void VesselDestroyEvent(Vessel v) { Log.Info("[SR] VesselDestroyEvent"); //If we're disabled, just return if (!Settings1.Instance.SREnabled) { Log.Info("[SR] not enabled"); return; } if (!sceneChangeComplete) { Log.Info("[SR] sceneChangeComplete is false"); return; } //If FlightGlobals is null, just return. We can't do anything if (FlightGlobals.fetch == null) { Log.Info("[SR] , flightGlobals is null"); return; } //If the protoVessel is null, we can't do anything so just return if (v.protoVessel == null) { Log.Info("[SR] v.protoVessel is null"); return; } //Check if we should even recover it if (!SRShouldRecover(v)) { Log.Info("[SR] , SRShouldRecover is false"); return; } //Our criteria for even attempting recovery. Broken down: vessel exists, hasn't had recovery attempted, isn't the active vessel, is around Kerbin, is either unloaded or packed, altitude is within atmosphere, //is flying or sub orbital, and is not an EVA (aka, Kerbals by themselves) if (v != null && !RecoverAttemptLog.ContainsKey(v.id) && !(HighLogic.LoadedSceneIsFlight && v.isActiveVessel) && (v.mainBody == Planetarium.fetch.Home) && (!v.loaded || v.packed) && (v.altitude < v.mainBody.atmosphereDepth) && (v.situation == Vessel.Situations.FLYING || v.situation == Vessel.Situations.SUB_ORBITAL || v.situation == Vessel.Situations.ORBITING) && !v.isEVA) { Log.Info("[SR] Recovering vessel"); RecoverVessel(v, false); } else Log.Info("[SR] "); Log.Info(" Not recovering vessel"); } private static void RecoverVessel(Vessel v, bool preRecovery) { //Indicate that we've at least attempted recovery of this vessel RecoverAttemptLog.Add(v.id, Planetarium.GetUniversalTime()); bool OnlyBlacklistedItems = true; foreach (ProtoPartSnapshot pps in v.protoVessel.protoPartSnapshots) { if (!Settings.Instance.BlackList.Contains(pps.partInfo.title)) { OnlyBlacklistedItems = false; break; } } if (OnlyBlacklistedItems) { return; } //If we got this far, we can assume we're going to be attempting to recover the vessel, so we should fire the processing event APIManager.instance.OnRecoveryProcessingStart.Fire(v); //Create a new RecoveryItem. Calling this calculates everything regarding the success or failure of the recovery. We need it for display purposes in the main gui Log.Info("[SR] Searching in RecoveryQueue (" + instance.RecoveryQueue.Count + ") for " + v.id); RecoveryItem Stage; if (instance.RecoveryQueue.Count > 0 && instance.RecoveryQueue.Exists(ri => ri.vessel.id == v.id)) { Stage = instance.RecoveryQueue.Find(ri => ri.vessel.id == v.id); instance.RecoveryQueue.Remove(Stage); Log.Info("[SR] Found vessel in the RecoveryQueue."); } else { Stage = new RecoveryItem(v); } Stage.Process(preRecovery); //Fire the pertinent RecoveryEvent (success or failure). Aka, make the API do its work Stage.FireEvent(); //Add the Stage to the correct list of stages. Either the Recovered Stages list or the Destroyed Stages list, for display on the main gui Stage.AddToList(); //Post a message to the stock message system, if people are still using that. Stage.PostStockMessage(); //Remove all crew on the vessel Stage.RemoveCrew(); if (preRecovery) { //remove the vessel so it doesn't get destroyed v.Die(); } //Fire the event stating we are done processing APIManager.instance.OnRecoveryProcessingFinish.Fire(v); } public static double ProcessPartList(List<Part> vesselParts) { double totalMass = 0; vesselParts.ForEach(p => totalMass += p.mass + p.GetResourceMass()); double chuteArea = GetChuteArea(vesselParts); return VelocityEstimate(totalMass, chuteArea); } public static double ProcessPartList(List<ProtoPartSnapshot> vesselParts) { double totalMass = 0; vesselParts.ForEach(p => totalMass += p.mass + GetResourceMass(p.resources)); double chuteArea = GetChuteArea(vesselParts); return VelocityEstimate(totalMass, chuteArea); } public static double GetChuteArea(List<ProtoPartSnapshot> protoParts) { double RCParameter = 0; bool realChuteInUse = false; try { foreach (ProtoPartSnapshot p in protoParts) { if (p.modules.Exists(ppms => ppms.moduleName == "RealChuteModule")) { if (!realChuteInUse) { RCParameter = 0; } //First off, get the PPMS since we'll need that ProtoPartModuleSnapshot realChute = p.modules.First(mod => mod.moduleName == "RealChuteModule"); //Assuming that's not somehow null, then we continue if (realChute != null) //Some of this was adopted from DebRefund, as Vendan's method of handling multiple parachutes is better than what I had. { //We make a list of ConfigNodes containing the parachutes (usually 1, but now there can be any number of them) //We get that from the PPMS ConfigNode rcNode = new ConfigNode(); realChute.Save(rcNode); //It's existence means that RealChute is installed and in use on the craft (you could have it installed and use stock chutes, so we only check if it's on the craft) realChuteInUse = true; RCParameter += ProcessRealchute(rcNode); } } else if (p.modules.Exists(ppms => ppms.moduleName == "RealChuteFAR")) //RealChute Lite for FAR { if (!realChuteInUse) { RCParameter = 0; } ProtoPartModuleSnapshot realChute = p.modules.First(mod => mod.moduleName == "RealChuteFAR"); float diameter = 0.0F; //realChute.moduleValues.GetValue("deployedDiameter") if (realChute.moduleRef != null) { try { diameter = realChute.moduleRef.Fields.GetValue<float>("deployedDiameter"); Log.Info($"[SR] Diameter is {diameter}."); } catch (Exception e) { Debug.LogError("[SR] Exception while finding deployedDiameter for RealChuteFAR module on moduleRef."); Debug.LogException(e); } } else { Log.Info("[SR] moduleRef is null, attempting workaround to find diameter."); object dDefault = p.partInfo.partPrefab.Modules["RealChuteFAR"]?.Fields?.GetValue("deployedDiameter"); //requires C# 6 if (dDefault != null) { diameter = Convert.ToSingle(dDefault); Log.Info($"[SR] Workaround gave a diameter of {diameter}."); } else { Log.Info("[SR] Couldn't get default value, setting to 0 and calling it a day."); diameter = 0.0F; } } float dragC = 1.0f; //float.Parse(realChute.moduleValues.GetValue("staticCd")); RCParameter += (dragC * Mathf.Pow(diameter, 2) * Math.PI / 4.0); realChuteInUse = true; } else if (!realChuteInUse && p.modules.Exists(ppms => ppms.moduleName == "ModuleParachute")) { //Credit to m4v and RCSBuildAid: https://github.com/m4v/RCSBuildAid/blob/master/Plugin/CoDMarker.cs Part part = p.partRef ?? p.partPrefab; //the part reference, or the part prefab DragCubeList dragCubes = part.DragCubes; dragCubes.SetCubeWeight("DEPLOYED", 1); dragCubes.SetCubeWeight("SEMIDEPLOYED", 0); dragCubes.SetCubeWeight("PACKED", 0); dragCubes.SetOcclusionMultiplier(0); Quaternion rotation = Quaternion.LookRotation(Vector3d.up); try { rotation = Quaternion.LookRotation(part.partTransform?.InverseTransformDirection(Vector3d.up) ?? Vector3d.up); } catch (Exception) { //Debug.LogException(e); } dragCubes.SetDragVectorRotation(rotation); } if (!realChuteInUse) { Part part = p.partRef ?? p.partPrefab; //the part reference, or the part prefab DragCubeList dragCubes = part.DragCubes; dragCubes.ForceUpdate(false, true); dragCubes.SetDragWeights(); dragCubes.SetPartOcclusion(); Vector3 dir = Vector3d.up; dragCubes.SetDrag(dir, 0.03f); //mach 0.03, or about 10m/s double dragCoeff = dragCubes.AreaDrag * PhysicsGlobals.DragCubeMultiplier; RCParameter += (dragCoeff * PhysicsGlobals.DragMultiplier); } } } catch (Exception e) { Debug.LogError("[SR] Error occured while trying to determine total chute area."); Debug.LogException(e); } return RCParameter; } public static double GetChuteArea(List<Part> parts) { double RCParameter = 0; bool realChuteInUse = false; try { foreach (Part p in parts) { //Make a list of all the Module Names for easy checking later. This can be avoided, but is convenient. List<string> ModuleNames = new List<string>(); foreach (PartModule pm in p.Modules) { ModuleNames.Add(pm.moduleName); } if (ModuleNames.Contains("RealChuteModule")) { if (!realChuteInUse) { RCParameter = 0; } //First off, get the PPMS since we'll need that PartModule realChute = p.Modules["RealChuteModule"]; //Assuming that's not somehow null, then we continue if (realChute != null) //Some of this was adopted from DebRefund, as Vendan's method of handling multiple parachutes is better than what I had. { //We make a list of ConfigNodes containing the parachutes (usually 1, but now there can be any number of them) //We get that from the PPMS ConfigNode rcNode = new ConfigNode(); realChute.Save(rcNode); //It's existence means that RealChute is installed and in use on the craft (you could have it installed and use stock chutes, so we only check if it's on the craft) realChuteInUse = true; RCParameter += ProcessRealchute(rcNode); } } else if (ModuleNames.Contains("RealChuteFAR")) //RealChute Lite for FAR { if (!realChuteInUse) { RCParameter = 0; } PartModule realChute = p.Modules["RealChuteFAR"]; float diameter = 0.0F; //realChute.moduleValues.GetValue("deployedDiameter") if (realChute != null) { try { diameter = realChute.Fields.GetValue<float>("deployedDiameter"); Log.Info($"[SR] Diameter is {diameter}."); } catch (Exception e) { Debug.LogError("[SR] Exception while finding deployedDiameter for RealChuteFAR module on module."); Debug.LogException(e); } } else { Log.Info("[SR] moduleRef is null, attempting workaround to find diameter."); object dDefault = p.partInfo.partPrefab.Modules["RealChuteFAR"]?.Fields?.GetValue("deployedDiameter"); //requires C# 6 if (dDefault != null) { diameter = Convert.ToSingle(dDefault); Log.Info($"[SR] Workaround gave a diameter of {diameter}."); } else { Log.Info("[SR] Couldn't get default value, setting to 0 and calling it a day."); diameter = 0.0F; } } float dragC = 1.0f; //float.Parse(realChute.moduleValues.GetValue("staticCd")); RCParameter += (dragC * Mathf.Pow(diameter, 2) * Math.PI / 4.0); realChuteInUse = true; } else if (!realChuteInUse && ModuleNames.Contains("ModuleParachute")) { //Credit to m4v and RCSBuildAid: https://github.com/m4v/RCSBuildAid/blob/master/Plugin/CoDMarker.cs Part part = p ?? p.partInfo.partPrefab; //the part, or the part prefab DragCubeList dragCubes = part.DragCubes; dragCubes.SetCubeWeight("DEPLOYED", 1); dragCubes.SetCubeWeight("SEMIDEPLOYED", 0); dragCubes.SetCubeWeight("PACKED", 0); dragCubes.SetOcclusionMultiplier(0); Quaternion rotation = Quaternion.LookRotation(Vector3d.up); try { rotation = Quaternion.LookRotation(part.partTransform?.InverseTransformDirection(Vector3d.up) ?? Vector3d.up); } catch (Exception e) { Debug.LogException(e); } dragCubes.SetDragVectorRotation(rotation); } if (!realChuteInUse) { Part part = p ?? p.partInfo.partPrefab; //the part reference, or the part prefab DragCubeList dragCubes = part.DragCubes; dragCubes.ForceUpdate(false, true); dragCubes.SetDragWeights(); dragCubes.SetPartOcclusion(); Vector3 dir = Vector3d.up; try { dir = -part.partTransform?.InverseTransformDirection(Vector3d.down) ?? Vector3d.up; } catch (Exception e) { //Debug.LogException(e); Log.Info("[SR] The expected excpetion is still present. " + e.Message); } dragCubes.SetDrag(dir, 0.03f); //mach 0.03, or about 10m/s double dragCoeff = dragCubes.AreaDrag * PhysicsGlobals.DragCubeMultiplier; RCParameter += (dragCoeff * PhysicsGlobals.DragMultiplier); } } } catch (Exception e) { Debug.LogError("[SR] Error occured while trying to determine total chute area."); Debug.LogException(e); } return RCParameter; } private static double GetResourceMass(List<ProtoPartResourceSnapshot> resources) { double mass = 0; //Loop through the available resources foreach (ProtoPartResourceSnapshot resource in resources) { //Extract the amount information double amount = resource.amount; //Using the name of the resource, find it in the PartResourceLibrary PartResourceDefinition RD = PartResourceLibrary.Instance.GetDefinition(resource.resourceName); //The mass of that resource is the amount times the density mass += amount * RD.density; } //Return the total mass return mass; } private static double ProcessRealchute(ConfigNode node) { double RCParameter = 0; //This is where the Reflection starts. We need to access the material library that RealChute has, so we first grab it's Type Type matLibraryType = null; AssemblyLoader.loadedAssemblies.TypeOperation(t => { if (t.FullName == "RealChute.Libraries.MaterialsLibrary.MaterialsLibrary") { matLibraryType = t; } }); ConfigNode[] parachutes = node.GetNodes("PARACHUTE"); //We then act on each individual parachute in the module foreach (ConfigNode chute in parachutes) { //First off, the diameter of the parachute. From that we can (later) determine the Vt, assuming a circular chute float diameter = float.Parse(chute.GetValue("deployedDiameter")); //The name of the material the chute is made of. We need this to get the actual material object and then the drag coefficient string mat = chute.GetValue("material"); //This grabs the method that RealChute uses to get the material. We will invoke that with the name of the material from before. System.Reflection.MethodInfo matMethod = matLibraryType.GetMethod("GetMaterial", new Type[] { typeof(string) }); //In order to invoke the method, we need to grab the active instance of the material library object MatLibraryInstance = matLibraryType.GetProperty("Instance").GetValue(null, null); //With the library instance we can invoke the GetMaterial method (passing the name of the material as a parameter) to receive an object that is the material object materialObject = matMethod.Invoke(MatLibraryInstance, new object[] { mat }); //With that material object we can extract the dragCoefficient using the helper function above. float dragC = Convert.ToSingle(GetMemberInfoValue(materialObject.GetType().GetMember("DragCoefficient")[0], materialObject)); //Now we calculate the RCParameter. Simple addition of this doesn't result in perfect results for Vt with parachutes with different diameter or drag coefficients //But it works perfectly for multiple identical parachutes (the normal case) RCParameter += (dragC * Mathf.Pow(diameter, 2) * Math.PI / 4.0); } return RCParameter; } /// <summary> /// Checks whether StageRecovery should recover the vessel /// </summary> /// <param name="vessel">The vessel to check</param> /// <returns>True if SR should handle it, false otherwise</returns> private static bool SRShouldRecover(Vessel vessel) { //Check if the stage was claimed by another mod string controllingMod = RecoveryControllerWrapper.ControllingMod(vessel); Log.Info("[SR] Controlling mod is " + (controllingMod ?? "null")); if (HighLogic.LoadedSceneIsFlight) //outside of the flight scene we're gonna handle everything { if (string.IsNullOrEmpty(controllingMod) || string.Equals(controllingMod, "auto", StringComparison.OrdinalIgnoreCase)) { if (FMRS_Enabled(false)) { //FMRS is installed and is active, but we aren't sure if they're handling chutes yet Log.Info("[SR] FMRS is active..."); if (!FMRS_Enabled(true)) { //FMRS is active, but isn't handling parachutes or deferred it to us. So if there isn't crew or a form of control, then we handle it Log.Info("[SR] But FMRS isn't handling chutes..."); if ((vessel.protoVessel.wasControllable) || vessel.protoVessel.GetVesselCrew().Count > 0) { //crewed or was controlled, so FMRS will get it Log.Info("[SR] But this stage has control/kerbals, so have fun FMRS!"); return false; } Log.Info("[SR] So we've got this stage! Maybe next time FMRS."); // if we've gotten here, FMRS probably isn't handling the craft and we should instead. } else { //FRMS is active, is handling chutes, and hasn't deferred it to us. We aren't gonna handle this case at all Log.Info("[SR] And FMRS is handling everything, have fun!"); return false; } } else { Log.Info("[SR] FMRS is not active."); } } else if (string.Equals(controllingMod, "StageRecovery", StringComparison.OrdinalIgnoreCase)) { Log.Info("[SR] Vessel specified StageRecovery as its processor."); return true; } else //another mod has requested full control over recovery of the vessel { Log.Info($"[SR] Vessel specified '{controllingMod}' as its processor."); return false; } } return true; } } } /* Copyright (C) 2018 Michael Marvin This program is free software: you can redistribute it and/or modify it under the terms of the GNU 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; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */
45.857728
259
0.527152
[ "MIT" ]
captain828/StageRecovery
StageRecovery/StageRecovery.cs
44,805
C#
using Microsoft.VisualStudio.Web.CodeGeneration.Contracts.Messaging; namespace Microsoft.VisualStudio.Web.CodeGeneration.Utils.Messaging { public interface IMessageHandler { bool HandleMessage(IMessageSender sender, Message message); } }
28.777778
69
0.783784
[ "Apache-2.0" ]
Arvinds-ds/Scaffolding
src/Shared/General/Messaging/IMessageHandler.cs
261
C#
// <auto-generated /> using System; using Daedalic.ProductDatabase.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Daedalic.ProductDatabase.Migrations { [DbContext(typeof(DaedalicProductDatabaseContext))] [Migration("20200131073221_GameWebsites")] partial class GameWebsites { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.0") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Daedalic.ProductDatabase.Models.Configuration", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Data") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Configuration"); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.Developer", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Developer"); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.Engine", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Version") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Engine"); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.Game", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("AssetIndexProjectId") .HasColumnType("nvarchar(max)"); b.Property<int?>("DeveloperId") .HasColumnType("int"); b.Property<string>("FacebookPageName") .HasColumnType("nvarchar(max)"); b.Property<int?>("GenreId") .HasColumnType("int"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("TwitterHandle") .HasColumnType("nvarchar(max)"); b.Property<string>("WebsiteUrl") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("DeveloperId"); b.HasIndex("GenreId"); b.ToTable("Game"); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.Genre", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Genre"); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.ImplementedLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("GameId") .HasColumnType("int"); b.Property<int>("LanguageId") .HasColumnType("int"); b.Property<int>("LanguageStatusId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("GameId"); b.HasIndex("LanguageId"); b.HasIndex("LanguageStatusId"); b.ToTable("ImplementedLanguage"); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.Language", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Language"); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.LanguageStatus", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Summary") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("LanguageStatus"); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.LanguageType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("LanguageType"); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.Platform", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Platform"); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.Publisher", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Publisher"); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.Release", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<bool>("EarlyAccess") .HasColumnType("bit"); b.Property<int?>("EngineId") .HasColumnType("int"); b.Property<int>("GameId") .HasColumnType("int"); b.Property<DateTime?>("GmcDate") .HasColumnType("datetime2"); b.Property<int?>("PlatformId") .HasColumnType("int"); b.Property<int?>("PublisherId") .HasColumnType("int"); b.Property<DateTime?>("ReleaseDate") .HasColumnType("datetime2"); b.Property<int>("ReleaseStatusId") .HasColumnType("int"); b.Property<int?>("StoreId") .HasColumnType("int"); b.Property<string>("Summary") .HasColumnType("nvarchar(max)"); b.Property<string>("Version") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("EngineId"); b.HasIndex("GameId"); b.HasIndex("PlatformId"); b.HasIndex("PublisherId"); b.HasIndex("ReleaseStatusId"); b.HasIndex("StoreId"); b.ToTable("Release"); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.ReleaseStatus", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("ReleaseStatus"); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.ReleasedLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("LanguageId") .HasColumnType("int"); b.Property<int>("ReleaseId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("LanguageId"); b.HasIndex("ReleaseId"); b.ToTable("ReleasedLanguage"); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.Store", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Store"); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.SupportedLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("GameId") .HasColumnType("int"); b.Property<int>("LanguageId") .HasColumnType("int"); b.Property<int>("LanguageTypeId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("GameId"); b.HasIndex("LanguageId"); b.HasIndex("LanguageTypeId"); b.ToTable("SupportedLanguage"); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.Game", b => { b.HasOne("Daedalic.ProductDatabase.Models.Developer", "Developer") .WithMany("Games") .HasForeignKey("DeveloperId"); b.HasOne("Daedalic.ProductDatabase.Models.Genre", "Genre") .WithMany() .HasForeignKey("GenreId"); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.ImplementedLanguage", b => { b.HasOne("Daedalic.ProductDatabase.Models.Game", "Game") .WithMany("ImplementedLanguages") .HasForeignKey("GameId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Daedalic.ProductDatabase.Models.Language", "Language") .WithMany() .HasForeignKey("LanguageId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Daedalic.ProductDatabase.Models.LanguageStatus", "LanguageStatus") .WithMany() .HasForeignKey("LanguageStatusId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.Release", b => { b.HasOne("Daedalic.ProductDatabase.Models.Engine", "Engine") .WithMany() .HasForeignKey("EngineId"); b.HasOne("Daedalic.ProductDatabase.Models.Game", "Game") .WithMany("Releases") .HasForeignKey("GameId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Daedalic.ProductDatabase.Models.Platform", "Platform") .WithMany() .HasForeignKey("PlatformId"); b.HasOne("Daedalic.ProductDatabase.Models.Publisher", "Publisher") .WithMany() .HasForeignKey("PublisherId"); b.HasOne("Daedalic.ProductDatabase.Models.ReleaseStatus", "Status") .WithMany() .HasForeignKey("ReleaseStatusId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Daedalic.ProductDatabase.Models.Store", "Store") .WithMany() .HasForeignKey("StoreId"); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.ReleasedLanguage", b => { b.HasOne("Daedalic.ProductDatabase.Models.Language", "Language") .WithMany() .HasForeignKey("LanguageId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Daedalic.ProductDatabase.Models.Release", "Release") .WithMany("Languages") .HasForeignKey("ReleaseId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Daedalic.ProductDatabase.Models.SupportedLanguage", b => { b.HasOne("Daedalic.ProductDatabase.Models.Game", "Game") .WithMany("SupportedLanguages") .HasForeignKey("GameId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Daedalic.ProductDatabase.Models.Language", "Language") .WithMany() .HasForeignKey("LanguageId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Daedalic.ProductDatabase.Models.LanguageType", "LanguageType") .WithMany() .HasForeignKey("LanguageTypeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
37.797071
125
0.467648
[ "MIT" ]
DaedalicEntertainment/product-database
Source/ProductDatabase/Daedalic.ProductDatabase/Migrations/20200131073221_GameWebsites.Designer.cs
18,069
C#
using Ryujinx.Common; using Ryujinx.Common.Configuration; using Ryujinx.Common.Configuration.Hid; using Ryujinx.Common.Logging; using Ryujinx.Configuration.Hid; using Ryujinx.Configuration.System; using Ryujinx.Configuration.Ui; using System; using System.Collections.Generic; namespace Ryujinx.Configuration { public class ConfigurationState { /// <summary> /// UI configuration section /// </summary> public class UiSection { public class Columns { public ReactiveObject<bool> FavColumn { get; private set; } public ReactiveObject<bool> IconColumn { get; private set; } public ReactiveObject<bool> AppColumn { get; private set; } public ReactiveObject<bool> DevColumn { get; private set; } public ReactiveObject<bool> VersionColumn { get; private set; } public ReactiveObject<bool> TimePlayedColumn { get; private set; } public ReactiveObject<bool> LastPlayedColumn { get; private set; } public ReactiveObject<bool> FileExtColumn { get; private set; } public ReactiveObject<bool> FileSizeColumn { get; private set; } public ReactiveObject<bool> PathColumn { get; private set; } public Columns() { FavColumn = new ReactiveObject<bool>(); IconColumn = new ReactiveObject<bool>(); AppColumn = new ReactiveObject<bool>(); DevColumn = new ReactiveObject<bool>(); VersionColumn = new ReactiveObject<bool>(); TimePlayedColumn = new ReactiveObject<bool>(); LastPlayedColumn = new ReactiveObject<bool>(); FileExtColumn = new ReactiveObject<bool>(); FileSizeColumn = new ReactiveObject<bool>(); PathColumn = new ReactiveObject<bool>(); } } public class ColumnSortSettings { public ReactiveObject<int> SortColumnId { get; private set; } public ReactiveObject<bool> SortAscending { get; private set; } public ColumnSortSettings() { SortColumnId = new ReactiveObject<int>(); SortAscending = new ReactiveObject<bool>(); } } /// <summary> /// Used to toggle columns in the GUI /// </summary> public Columns GuiColumns { get; private set; } /// <summary> /// Used to configure column sort settings in the GUI /// </summary> public ColumnSortSettings ColumnSort { get; private set; } /// <summary> /// A list of directories containing games to be used to load games into the games list /// </summary> public ReactiveObject<List<string>> GameDirs { get; private set; } /// <summary> /// Enable or disable custom themes in the GUI /// </summary> public ReactiveObject<bool> EnableCustomTheme { get; private set; } /// <summary> /// Path to custom GUI theme /// </summary> public ReactiveObject<string> CustomThemePath { get; private set; } /// <summary> /// Start games in fullscreen mode /// </summary> public ReactiveObject<bool> StartFullscreen { get; private set; } public UiSection() { GuiColumns = new Columns(); ColumnSort = new ColumnSortSettings(); GameDirs = new ReactiveObject<List<string>>(); EnableCustomTheme = new ReactiveObject<bool>(); CustomThemePath = new ReactiveObject<string>(); StartFullscreen = new ReactiveObject<bool>(); } } /// <summary> /// Logger configuration section /// </summary> public class LoggerSection { /// <summary> /// Enables printing debug log messages /// </summary> public ReactiveObject<bool> EnableDebug { get; private set; } /// <summary> /// Enables printing stub log messages /// </summary> public ReactiveObject<bool> EnableStub { get; private set; } /// <summary> /// Enables printing info log messages /// </summary> public ReactiveObject<bool> EnableInfo { get; private set; } /// <summary> /// Enables printing warning log messages /// </summary> public ReactiveObject<bool> EnableWarn { get; private set; } /// <summary> /// Enables printing error log messages /// </summary> public ReactiveObject<bool> EnableError { get; private set; } /// <summary> /// Enables printing guest log messages /// </summary> public ReactiveObject<bool> EnableGuest { get; private set; } /// <summary> /// Enables printing FS access log messages /// </summary> public ReactiveObject<bool> EnableFsAccessLog { get; private set; } /// <summary> /// Controls which log messages are written to the log targets /// </summary> public ReactiveObject<LogClass[]> FilteredClasses { get; private set; } /// <summary> /// Enables or disables logging to a file on disk /// </summary> public ReactiveObject<bool> EnableFileLog { get; private set; } /// <summary> /// Controls which OpenGL log messages are recorded in the log /// </summary> public ReactiveObject<GraphicsDebugLevel> GraphicsDebugLevel { get; private set; } public LoggerSection() { EnableDebug = new ReactiveObject<bool>(); EnableStub = new ReactiveObject<bool>(); EnableInfo = new ReactiveObject<bool>(); EnableWarn = new ReactiveObject<bool>(); EnableError = new ReactiveObject<bool>(); EnableGuest = new ReactiveObject<bool>(); EnableFsAccessLog = new ReactiveObject<bool>(); FilteredClasses = new ReactiveObject<LogClass[]>(); EnableFileLog = new ReactiveObject<bool>() { Name = "File Log", Category = "Logger" }; GraphicsDebugLevel = new ReactiveObject<GraphicsDebugLevel>(); } } /// <summary> /// System configuration section /// </summary> public class SystemSection { /// <summary> /// Change System Language /// </summary> public ReactiveObject<Language> Language { get; private set; } /// <summary> /// Change System Region /// </summary> public ReactiveObject<Region> Region { get; private set; } /// <summary> /// Change System TimeZone /// </summary> public ReactiveObject<string> TimeZone { get; private set; } /// <summary> /// System Time Offset in Seconds /// </summary> public ReactiveObject<long> SystemTimeOffset { get; private set; } /// <summary> /// Enables or disables Docked Mode /// </summary> public ReactiveObject<bool> EnableDockedMode { get; private set; } /// <summary> /// Enables or disables profiled translation cache persistency /// </summary> public ReactiveObject<bool> EnablePtc { get; private set; } /// <summary> /// Enables integrity checks on Game content files /// </summary> public ReactiveObject<bool> EnableFsIntegrityChecks { get; private set; } /// <summary> /// Enables FS access log output to the console. Possible modes are 0-3 /// </summary> public ReactiveObject<int> FsGlobalAccessLogMode { get; private set; } /// <summary> /// The selected audio backend /// </summary> public ReactiveObject<AudioBackend> AudioBackend { get; private set; } /// <summary> /// Enable or disable ignoring missing services /// </summary> public ReactiveObject<bool> IgnoreMissingServices { get; private set; } public SystemSection() { Language = new ReactiveObject<Language>(); Region = new ReactiveObject<Region>(); TimeZone = new ReactiveObject<string>(); SystemTimeOffset = new ReactiveObject<long>(); EnableDockedMode = new ReactiveObject<bool>() { Name = "Docked", Category = "System" }; EnablePtc = new ReactiveObject<bool>() { Name = "PPTC", Category = "System" }; EnableFsIntegrityChecks = new ReactiveObject<bool>() { Name = "Enable File Integrity Checks", Category = "System" }; FsGlobalAccessLogMode = new ReactiveObject<int>() { Name = "File Global Access Log", Category = "System" }; AudioBackend = new ReactiveObject<AudioBackend>() { Name = "Audio Backend", Category = "System" }; IgnoreMissingServices = new ReactiveObject<bool>() { Name = "Ignore Missing Services", Category = "System" }; } } /// <summary> /// Hid configuration section /// </summary> public class HidSection { /// <summary> /// Enable or disable keyboard support (Independent from controllers binding) /// </summary> public ReactiveObject<bool> EnableKeyboard { get; private set; } /// <summary> /// Hotkey Keyboard Bindings /// </summary> public ReactiveObject<KeyboardHotkeys> Hotkeys { get; private set; } /// <summary> /// Input device configuration. /// NOTE: This ReactiveObject won't issue an event when the List has elements added or removed. /// TODO: Implement a ReactiveList class. /// </summary> public ReactiveObject<List<InputConfig>> InputConfig { get; private set; } public HidSection() { EnableKeyboard = new ReactiveObject<bool>(); Hotkeys = new ReactiveObject<KeyboardHotkeys>(); InputConfig = new ReactiveObject<List<InputConfig>>(); } } /// <summary> /// Graphics configuration section /// </summary> public class GraphicsSection { /// <summary> /// Max Anisotropy. Values range from 0 - 16. Set to -1 to let the game decide. /// </summary> public ReactiveObject<float> MaxAnisotropy { get; private set; } /// <summary> /// Aspect Ratio applied to the renderer window. /// </summary> public ReactiveObject<AspectRatio> AspectRatio { get; private set; } /// <summary> /// Resolution Scale. An integer scale applied to applicable render targets. Values 1-4, or -1 to use a custom floating point scale instead. /// </summary> public ReactiveObject<int> ResScale { get; private set; } /// <summary> /// Custom Resolution Scale. A custom floating point scale applied to applicable render targets. Only active when Resolution Scale is -1. /// </summary> public ReactiveObject<float> ResScaleCustom { get; private set; } /// <summary> /// Dumps shaders in this local directory /// </summary> public ReactiveObject<string> ShadersDumpPath { get; private set; } /// <summary> /// Enables or disables Vertical Sync /// </summary> public ReactiveObject<bool> EnableVsync { get; private set; } /// <summary> /// Enables or disables Shader cache /// </summary> public ReactiveObject<bool> EnableShaderCache { get; private set; } public GraphicsSection() { ResScale = new ReactiveObject<int>() { Name = "Res Scale", Category = "Graphics" }; ResScaleCustom = new ReactiveObject<float>() { Name = "Custom Scale", Category = "Graphics" }; MaxAnisotropy = new ReactiveObject<float>() { Name = "Anisotrophy", Category = "Graphics" }; AspectRatio = new ReactiveObject<AspectRatio>() { Name = "Aspect Ratio", Category = "Graphics" }; ShadersDumpPath = new ReactiveObject<string>(); EnableVsync = new ReactiveObject<bool>() { Name = "VSync" , Category = "Graphics"}; EnableShaderCache = new ReactiveObject<bool>() { Name = "Shader Cache", Category = "Graphics" }; } } /// <summary> /// The default configuration instance /// </summary> public static ConfigurationState Instance { get; private set; } /// <summary> /// The Ui section /// </summary> public UiSection Ui { get; private set; } /// <summary> /// The Logger section /// </summary> public LoggerSection Logger { get; private set; } /// <summary> /// The System section /// </summary> public SystemSection System { get; private set; } /// <summary> /// The Graphics section /// </summary> public GraphicsSection Graphics { get; private set; } /// <summary> /// The Hid section /// </summary> public HidSection Hid { get; private set; } /// <summary> /// Enables or disables Discord Rich Presence /// </summary> public ReactiveObject<bool> EnableDiscordIntegration { get; private set; } /// <summary> /// Checks for updates when Ryujinx starts when enabled /// </summary> public ReactiveObject<bool> CheckUpdatesOnStart { get; private set; } /// <summary> /// Show "Confirm Exit" Dialog /// </summary> public ReactiveObject<bool> ShowConfirmExit { get; private set; } /// <summary> /// Hide Cursor on Idle /// </summary> public ReactiveObject<bool> HideCursorOnIdle { get; private set; } private ConfigurationState() { Ui = new UiSection(); Logger = new LoggerSection(); System = new SystemSection(); Graphics = new GraphicsSection(); Hid = new HidSection(); EnableDiscordIntegration = new ReactiveObject<bool>(); CheckUpdatesOnStart = new ReactiveObject<bool>(); ShowConfirmExit = new ReactiveObject<bool>(); HideCursorOnIdle = new ReactiveObject<bool>(); } public ConfigurationFileFormat ToFileFormat() { List<ControllerConfig> controllerConfigList = new List<ControllerConfig>(); List<KeyboardConfig> keyboardConfigList = new List<KeyboardConfig>(); foreach (InputConfig inputConfig in Hid.InputConfig.Value) { if (inputConfig is ControllerConfig controllerConfig) { controllerConfigList.Add(controllerConfig); } else if (inputConfig is KeyboardConfig keyboardConfig) { keyboardConfigList.Add(keyboardConfig); } } ConfigurationFileFormat configurationFile = new ConfigurationFileFormat { Version = ConfigurationFileFormat.CurrentVersion, ResScale = Graphics.ResScale, ResScaleCustom = Graphics.ResScaleCustom, MaxAnisotropy = Graphics.MaxAnisotropy, AspectRatio = Graphics.AspectRatio, GraphicsShadersDumpPath = Graphics.ShadersDumpPath, LoggingEnableDebug = Logger.EnableDebug, LoggingEnableStub = Logger.EnableStub, LoggingEnableInfo = Logger.EnableInfo, LoggingEnableWarn = Logger.EnableWarn, LoggingEnableError = Logger.EnableError, LoggingEnableGuest = Logger.EnableGuest, LoggingEnableFsAccessLog = Logger.EnableFsAccessLog, LoggingFilteredClasses = Logger.FilteredClasses, LoggingGraphicsDebugLevel = Logger.GraphicsDebugLevel, EnableFileLog = Logger.EnableFileLog, SystemLanguage = System.Language, SystemRegion = System.Region, SystemTimeZone = System.TimeZone, SystemTimeOffset = System.SystemTimeOffset, DockedMode = System.EnableDockedMode, EnableDiscordIntegration = EnableDiscordIntegration, CheckUpdatesOnStart = CheckUpdatesOnStart, ShowConfirmExit = ShowConfirmExit, HideCursorOnIdle = HideCursorOnIdle, EnableVsync = Graphics.EnableVsync, EnableShaderCache = Graphics.EnableShaderCache, EnablePtc = System.EnablePtc, EnableFsIntegrityChecks = System.EnableFsIntegrityChecks, FsGlobalAccessLogMode = System.FsGlobalAccessLogMode, AudioBackend = System.AudioBackend, IgnoreMissingServices = System.IgnoreMissingServices, GuiColumns = new GuiColumns { FavColumn = Ui.GuiColumns.FavColumn, IconColumn = Ui.GuiColumns.IconColumn, AppColumn = Ui.GuiColumns.AppColumn, DevColumn = Ui.GuiColumns.DevColumn, VersionColumn = Ui.GuiColumns.VersionColumn, TimePlayedColumn = Ui.GuiColumns.TimePlayedColumn, LastPlayedColumn = Ui.GuiColumns.LastPlayedColumn, FileExtColumn = Ui.GuiColumns.FileExtColumn, FileSizeColumn = Ui.GuiColumns.FileSizeColumn, PathColumn = Ui.GuiColumns.PathColumn, }, ColumnSort = new ColumnSort { SortColumnId = Ui.ColumnSort.SortColumnId, SortAscending = Ui.ColumnSort.SortAscending }, GameDirs = Ui.GameDirs, EnableCustomTheme = Ui.EnableCustomTheme, CustomThemePath = Ui.CustomThemePath, StartFullscreen = Ui.StartFullscreen, EnableKeyboard = Hid.EnableKeyboard, Hotkeys = Hid.Hotkeys, KeyboardConfig = keyboardConfigList, ControllerConfig = controllerConfigList }; return configurationFile; } public void LoadDefault() { Graphics.ResScale.Value = 1; Graphics.ResScaleCustom.Value = 1.0f; Graphics.MaxAnisotropy.Value = -1.0f; Graphics.AspectRatio.Value = AspectRatio.Fixed16x9; Graphics.ShadersDumpPath.Value = ""; Logger.EnableDebug.Value = false; Logger.EnableStub.Value = true; Logger.EnableInfo.Value = true; Logger.EnableWarn.Value = true; Logger.EnableError.Value = true; Logger.EnableGuest.Value = true; Logger.EnableFsAccessLog.Value = false; Logger.FilteredClasses.Value = Array.Empty<LogClass>(); Logger.GraphicsDebugLevel.Value = GraphicsDebugLevel.None; Logger.EnableFileLog.Value = true; System.Language.Value = Language.AmericanEnglish; System.Region.Value = Region.USA; System.TimeZone.Value = "UTC"; System.SystemTimeOffset.Value = 0; System.EnableDockedMode.Value = true; EnableDiscordIntegration.Value = true; CheckUpdatesOnStart.Value = true; ShowConfirmExit.Value = true; HideCursorOnIdle.Value = false; Graphics.EnableVsync.Value = true; Graphics.EnableShaderCache.Value = true; System.EnablePtc.Value = true; System.EnableFsIntegrityChecks.Value = true; System.FsGlobalAccessLogMode.Value = 0; System.AudioBackend.Value = AudioBackend.OpenAl; System.IgnoreMissingServices.Value = false; Ui.GuiColumns.FavColumn.Value = true; Ui.GuiColumns.IconColumn.Value = true; Ui.GuiColumns.AppColumn.Value = true; Ui.GuiColumns.DevColumn.Value = true; Ui.GuiColumns.VersionColumn.Value = true; Ui.GuiColumns.TimePlayedColumn.Value = true; Ui.GuiColumns.LastPlayedColumn.Value = true; Ui.GuiColumns.FileExtColumn.Value = true; Ui.GuiColumns.FileSizeColumn.Value = true; Ui.GuiColumns.PathColumn.Value = true; Ui.ColumnSort.SortColumnId.Value = 0; Ui.ColumnSort.SortAscending.Value = false; Ui.GameDirs.Value = new List<string>(); Ui.EnableCustomTheme.Value = false; Ui.CustomThemePath.Value = ""; Ui.StartFullscreen.Value = false; Hid.EnableKeyboard.Value = false; Hid.Hotkeys.Value = new KeyboardHotkeys { ToggleVsync = Key.Tab }; Hid.InputConfig.Value = new List<InputConfig> { new KeyboardConfig { Index = 0, ControllerType = ControllerType.JoyconPair, PlayerIndex = PlayerIndex.Player1, LeftJoycon = new NpadKeyboardLeft { StickUp = Key.W, StickDown = Key.S, StickLeft = Key.A, StickRight = Key.D, StickButton = Key.F, DPadUp = Key.Up, DPadDown = Key.Down, DPadLeft = Key.Left, DPadRight = Key.Right, ButtonMinus = Key.Minus, ButtonL = Key.E, ButtonZl = Key.Q, ButtonSl = Key.Home, ButtonSr = Key.End }, RightJoycon = new NpadKeyboardRight { StickUp = Key.I, StickDown = Key.K, StickLeft = Key.J, StickRight = Key.L, StickButton = Key.H, ButtonA = Key.Z, ButtonB = Key.X, ButtonX = Key.C, ButtonY = Key.V, ButtonPlus = Key.Plus, ButtonR = Key.U, ButtonZr = Key.O, ButtonSl = Key.PageUp, ButtonSr = Key.PageDown }, EnableMotion = false, MirrorInput = false, Slot = 0, AltSlot = 0, Sensitivity = 100, GyroDeadzone = 1, DsuServerHost = "127.0.0.1", DsuServerPort = 26760 } }; } public void Load(ConfigurationFileFormat configurationFileFormat, string configurationFilePath) { bool configurationFileUpdated = false; if (configurationFileFormat.Version < 0 || configurationFileFormat.Version > ConfigurationFileFormat.CurrentVersion) { Common.Logging.Logger.Warning?.Print(LogClass.Application, $"Unsupported configuration version {configurationFileFormat.Version}, loading default."); LoadDefault(); return; } if (configurationFileFormat.Version < 2) { Common.Logging.Logger.Warning?.Print(LogClass.Application, $"Outdated configuration version {configurationFileFormat.Version}, migrating to version 2."); configurationFileFormat.SystemRegion = Region.USA; configurationFileUpdated = true; } if (configurationFileFormat.Version < 3) { Common.Logging.Logger.Warning?.Print(LogClass.Application, $"Outdated configuration version {configurationFileFormat.Version}, migrating to version 3."); configurationFileFormat.SystemTimeZone = "UTC"; configurationFileUpdated = true; } if (configurationFileFormat.Version < 4) { Common.Logging.Logger.Warning?.Print(LogClass.Application, $"Outdated configuration version {configurationFileFormat.Version}, migrating to version 4."); configurationFileFormat.MaxAnisotropy = -1; configurationFileUpdated = true; } if (configurationFileFormat.Version < 5) { Common.Logging.Logger.Warning?.Print(LogClass.Application, $"Outdated configuration version {configurationFileFormat.Version}, migrating to version 5."); configurationFileFormat.SystemTimeOffset = 0; configurationFileUpdated = true; } if (configurationFileFormat.Version < 6) { Common.Logging.Logger.Warning?.Print(LogClass.Application, $"Outdated configuration version {configurationFileFormat.Version}, migrating to version 6."); configurationFileFormat.ControllerConfig = new List<ControllerConfig>(); configurationFileFormat.KeyboardConfig = new List<KeyboardConfig> { new KeyboardConfig { Index = 0, ControllerType = ControllerType.JoyconPair, PlayerIndex = PlayerIndex.Player1, LeftJoycon = new NpadKeyboardLeft { StickUp = Key.W, StickDown = Key.S, StickLeft = Key.A, StickRight = Key.D, StickButton = Key.F, DPadUp = Key.Up, DPadDown = Key.Down, DPadLeft = Key.Left, DPadRight = Key.Right, ButtonMinus = Key.Minus, ButtonL = Key.E, ButtonZl = Key.Q, ButtonSl = Key.Unbound, ButtonSr = Key.Unbound }, RightJoycon = new NpadKeyboardRight { StickUp = Key.I, StickDown = Key.K, StickLeft = Key.J, StickRight = Key.L, StickButton = Key.H, ButtonA = Key.Z, ButtonB = Key.X, ButtonX = Key.C, ButtonY = Key.V, ButtonPlus = Key.Plus, ButtonR = Key.U, ButtonZr = Key.O, ButtonSl = Key.Unbound, ButtonSr = Key.Unbound }, EnableMotion = false, MirrorInput = false, Slot = 0, AltSlot = 0, Sensitivity = 100, GyroDeadzone = 1, DsuServerHost = "127.0.0.1", DsuServerPort = 26760 } }; configurationFileUpdated = true; } // Only needed for version 6 configurations. if (configurationFileFormat.Version == 6) { Common.Logging.Logger.Warning?.Print(LogClass.Application, $"Outdated configuration version {configurationFileFormat.Version}, migrating to version 7."); for (int i = 0; i < configurationFileFormat.KeyboardConfig.Count; i++) { if (configurationFileFormat.KeyboardConfig[i].Index != KeyboardConfig.AllKeyboardsIndex) { configurationFileFormat.KeyboardConfig[i].Index++; } } } if (configurationFileFormat.Version < 8) { Common.Logging.Logger.Warning?.Print(LogClass.Application, $"Outdated configuration version {configurationFileFormat.Version}, migrating to version 8."); configurationFileFormat.EnablePtc = true; configurationFileUpdated = true; } if (configurationFileFormat.Version < 9) { Common.Logging.Logger.Warning?.Print(LogClass.Application, $"Outdated configuration version {configurationFileFormat.Version}, migrating to version 9."); configurationFileFormat.ColumnSort = new ColumnSort { SortColumnId = 0, SortAscending = false }; configurationFileFormat.Hotkeys = new KeyboardHotkeys { ToggleVsync = Key.Tab }; configurationFileUpdated = true; } if (configurationFileFormat.Version < 10) { Common.Logging.Logger.Warning?.Print(LogClass.Application, $"Outdated configuration version {configurationFileFormat.Version}, migrating to version 10."); configurationFileFormat.AudioBackend = AudioBackend.OpenAl; configurationFileUpdated = true; } if (configurationFileFormat.Version < 11) { Common.Logging.Logger.Warning?.Print(LogClass.Application, $"Outdated configuration version {configurationFileFormat.Version}, migrating to version 11."); configurationFileFormat.ResScale = 1; configurationFileFormat.ResScaleCustom = 1.0f; configurationFileUpdated = true; } if (configurationFileFormat.Version < 12) { Common.Logging.Logger.Warning?.Print(LogClass.Application, $"Outdated configuration version {configurationFileFormat.Version}, migrating to version 12."); configurationFileFormat.LoggingGraphicsDebugLevel = GraphicsDebugLevel.None; configurationFileUpdated = true; } if (configurationFileFormat.Version < 14) { Common.Logging.Logger.Warning?.Print(LogClass.Application, $"Outdated configuration version {configurationFileFormat.Version}, migrating to version 14."); configurationFileFormat.CheckUpdatesOnStart = true; configurationFileUpdated = true; } if (configurationFileFormat.Version < 16) { Common.Logging.Logger.Warning?.Print(LogClass.Application, $"Outdated configuration version {configurationFileFormat.Version}, migrating to version 16."); configurationFileFormat.EnableShaderCache = true; configurationFileUpdated = true; } if (configurationFileFormat.Version < 17) { Common.Logging.Logger.Warning?.Print(LogClass.Application, $"Outdated configuration version {configurationFileFormat.Version}, migrating to version 17."); configurationFileFormat.StartFullscreen = false; configurationFileUpdated = true; } if (configurationFileFormat.Version < 18) { Common.Logging.Logger.Warning?.Print(LogClass.Application, $"Outdated configuration version {configurationFileFormat.Version}, migrating to version 18."); configurationFileFormat.AspectRatio = AspectRatio.Fixed16x9; configurationFileUpdated = true; } if (configurationFileFormat.Version < 20) { Common.Logging.Logger.Warning?.Print(LogClass.Application, $"Outdated configuration version {configurationFileFormat.Version}, migrating to version 20."); configurationFileFormat.ShowConfirmExit = true; configurationFileUpdated = true; } if (configurationFileFormat.Version < 22) { Common.Logging.Logger.Warning?.Print(LogClass.Application, $"Outdated configuration version {configurationFileFormat.Version}, migrating to version 22."); configurationFileFormat.HideCursorOnIdle = false; configurationFileUpdated = true; } List<InputConfig> inputConfig = new List<InputConfig>(); inputConfig.AddRange(configurationFileFormat.ControllerConfig); inputConfig.AddRange(configurationFileFormat.KeyboardConfig); Graphics.ResScale.Value = configurationFileFormat.ResScale; Graphics.ResScaleCustom.Value = configurationFileFormat.ResScaleCustom; Graphics.MaxAnisotropy.Value = configurationFileFormat.MaxAnisotropy; Graphics.AspectRatio.Value = configurationFileFormat.AspectRatio; Graphics.ShadersDumpPath.Value = configurationFileFormat.GraphicsShadersDumpPath; Logger.EnableDebug.Value = configurationFileFormat.LoggingEnableDebug; Logger.EnableStub.Value = configurationFileFormat.LoggingEnableStub; Logger.EnableInfo.Value = configurationFileFormat.LoggingEnableInfo; Logger.EnableWarn.Value = configurationFileFormat.LoggingEnableWarn; Logger.EnableError.Value = configurationFileFormat.LoggingEnableError; Logger.EnableGuest.Value = configurationFileFormat.LoggingEnableGuest; Logger.EnableFsAccessLog.Value = configurationFileFormat.LoggingEnableFsAccessLog; Logger.FilteredClasses.Value = configurationFileFormat.LoggingFilteredClasses; Logger.GraphicsDebugLevel.Value = configurationFileFormat.LoggingGraphicsDebugLevel; Logger.EnableFileLog.Value = configurationFileFormat.EnableFileLog; System.Language.Value = configurationFileFormat.SystemLanguage; System.Region.Value = configurationFileFormat.SystemRegion; System.TimeZone.Value = configurationFileFormat.SystemTimeZone; System.SystemTimeOffset.Value = configurationFileFormat.SystemTimeOffset; System.EnableDockedMode.Value = configurationFileFormat.DockedMode; EnableDiscordIntegration.Value = configurationFileFormat.EnableDiscordIntegration; CheckUpdatesOnStart.Value = configurationFileFormat.CheckUpdatesOnStart; ShowConfirmExit.Value = configurationFileFormat.ShowConfirmExit; HideCursorOnIdle.Value = configurationFileFormat.HideCursorOnIdle; Graphics.EnableVsync.Value = configurationFileFormat.EnableVsync; Graphics.EnableShaderCache.Value = configurationFileFormat.EnableShaderCache; System.EnablePtc.Value = configurationFileFormat.EnablePtc; System.EnableFsIntegrityChecks.Value = configurationFileFormat.EnableFsIntegrityChecks; System.FsGlobalAccessLogMode.Value = configurationFileFormat.FsGlobalAccessLogMode; System.AudioBackend.Value = configurationFileFormat.AudioBackend; System.IgnoreMissingServices.Value = configurationFileFormat.IgnoreMissingServices; Ui.GuiColumns.FavColumn.Value = configurationFileFormat.GuiColumns.FavColumn; Ui.GuiColumns.IconColumn.Value = configurationFileFormat.GuiColumns.IconColumn; Ui.GuiColumns.AppColumn.Value = configurationFileFormat.GuiColumns.AppColumn; Ui.GuiColumns.DevColumn.Value = configurationFileFormat.GuiColumns.DevColumn; Ui.GuiColumns.VersionColumn.Value = configurationFileFormat.GuiColumns.VersionColumn; Ui.GuiColumns.TimePlayedColumn.Value = configurationFileFormat.GuiColumns.TimePlayedColumn; Ui.GuiColumns.LastPlayedColumn.Value = configurationFileFormat.GuiColumns.LastPlayedColumn; Ui.GuiColumns.FileExtColumn.Value = configurationFileFormat.GuiColumns.FileExtColumn; Ui.GuiColumns.FileSizeColumn.Value = configurationFileFormat.GuiColumns.FileSizeColumn; Ui.GuiColumns.PathColumn.Value = configurationFileFormat.GuiColumns.PathColumn; Ui.ColumnSort.SortColumnId.Value = configurationFileFormat.ColumnSort.SortColumnId; Ui.ColumnSort.SortAscending.Value = configurationFileFormat.ColumnSort.SortAscending; Ui.GameDirs.Value = configurationFileFormat.GameDirs; Ui.EnableCustomTheme.Value = configurationFileFormat.EnableCustomTheme; Ui.CustomThemePath.Value = configurationFileFormat.CustomThemePath; Ui.StartFullscreen.Value = configurationFileFormat.StartFullscreen; Hid.EnableKeyboard.Value = configurationFileFormat.EnableKeyboard; Hid.Hotkeys.Value = configurationFileFormat.Hotkeys; Hid.InputConfig.Value = inputConfig; if (configurationFileUpdated) { ToFileFormat().SaveConfig(configurationFilePath); Common.Logging.Logger.Notice.Print(LogClass.Application, $"Configuration file updated to version {ConfigurationFileFormat.CurrentVersion}"); } } public static void Initialize() { if (Instance != null) { throw new InvalidOperationException("Configuration is already initialized"); } Instance = new ConfigurationState(); } } }
46.555051
170
0.536852
[ "MIT" ]
Kevinjeter/Ryujinx
Ryujinx.Common/Configuration/ConfigurationState.cs
41,015
C#
using System; using System.Management; namespace SubZero.Models { /// <summary> /// Helper for working with MSI WMI Objects /// </summary> public class MSIWmiHelper : IDisposable { #region Private Fields private bool disposedValue; #endregion Private Fields #region Public Constructors /// <summary> /// Initializes WMI helper for MSI Laptops /// </summary> public MSIWmiHelper() { //Init Windows Management Instrumentation Roots, specific to MSI var WMIRoot = new ManagementScope("root\\WMI", new ConnectionOptions { Impersonation = ImpersonationLevel.Impersonate, Authentication = AuthenticationLevel.Connect, EnablePrivileges = true }); var CIMV2Root = new ManagementScope("root\\CIMV2", new ConnectionOptions { Impersonation = ImpersonationLevel.Impersonate, Authentication = AuthenticationLevel.Connect, EnablePrivileges = true }); //Init Windows Management Instrumentation, specific to MSI MSI_CPU = new ManagementObjectSearcher(WMIRoot, new ObjectQuery("SELECT * FROM MSI_CPU")); MSI_GPU = new ManagementObjectSearcher(WMIRoot, new ObjectQuery("SELECT * FROM MSI_VGA")); MSI_AP = new ManagementObjectSearcher(WMIRoot, new ObjectQuery("SELECT AP FROM MSI_AP")); MSI_LaptopModel = new ManagementObjectSearcher(CIMV2Root, new ObjectQuery("SELECT Model FROM Win32_ComputerSystem")); MSI_System = new ManagementObjectSearcher(WMIRoot, new ObjectQuery("SELECT * FROM MSI_System")); //Test if they are valid using (ManagementObjectCollection test = MSI_CPU.Get()) { IsAvailableMSI_CPU = test.Count != 0; } using (ManagementObjectCollection test = MSI_GPU.Get()) { IsAvailableMSI_GPU = test.Count != 0; } using (ManagementObjectCollection test = MSI_AP.Get()) { IsAvailableMSI_AP = test.Count != 0; } using (ManagementObjectCollection test = MSI_LaptopModel.Get()) { IsAvailableMSI_LaptopModel = test.Count != 0; } using (ManagementObjectCollection test = MSI_System.Get()) { IsAvailableMSI_System = test.Count != 0; } } #endregion Public Constructors #region Public Properties /// <summary> /// Is MSI AP Available to be used? /// </summary> public bool IsAvailableMSI_AP { get; private set; } /// <summary> /// Is MSI CPU Available to be used? /// </summary> public bool IsAvailableMSI_CPU { get; private set; } /// <summary> /// Is MSI GPU Available to be used? /// </summary> public bool IsAvailableMSI_GPU { get; private set; } /// <summary> /// Is MSI Laptop Model ready to be used? /// </summary> public bool IsAvailableMSI_LaptopModel { get; private set; } /// <summary> /// Is MSI System Available to be used? /// </summary> public bool IsAvailableMSI_System { get; private set; } /// <summary> /// AP WMI /// </summary> public ManagementObjectSearcher MSI_AP { get; private set; } /// <summary> /// CPU WMI /// </summary> public ManagementObjectSearcher MSI_CPU { get; private set; } /// <summary> /// GPU WMI /// </summary> public ManagementObjectSearcher MSI_GPU { get; private set; } /// <summary> /// MSI Laptop Model /// </summary> public ManagementObjectSearcher MSI_LaptopModel { get; private set; } /// <summary> /// MSI System WMI /// </summary> public ManagementObjectSearcher MSI_System { get; private set; } #endregion Public Properties #region Public Methods /// <summary> /// Dispose implementation /// </summary> public void Dispose() { // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method Dispose(disposing: true); GC.SuppressFinalize(this); } #endregion Public Methods #region Protected Methods /// <summary> /// Dispose implementation /// </summary> /// <param name="disposing">Is managed disposing?</param> protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { //Managed disposing MSI_AP.Dispose(); MSI_CPU.Dispose(); MSI_GPU.Dispose(); MSI_LaptopModel.Dispose(); MSI_System.Dispose(); } //Unmanaged disposing MSI_AP = null; MSI_CPU = null; MSI_GPU = null; MSI_LaptopModel = null; MSI_System = null; //Confirm dispose disposedValue = true; } } #endregion Protected Methods } }
32.541667
129
0.542345
[ "Apache-2.0" ]
TekuSP/SubZero
SubZero/Models/MSIWmiHelper.cs
5,469
C#
using System; using NPoco; using Umbraco.Core.Persistence.DatabaseAnnotations; namespace Umbraco.Core.Persistence.Dtos { [TableName(TableName)] [PrimaryKey("id", AutoIncrement = false)] [ExplicitColumns] internal class ContentScheduleDto { public const string TableName = Constants.DatabaseSchema.Tables.ContentSchedule; [Column("id")] [PrimaryKeyColumn(AutoIncrement = false)] public Guid Id { get; set; } [Column("nodeId")] [ForeignKey(typeof(ContentDto))] public int NodeId { get; set; } [Column("languageId")] [ForeignKey(typeof(LanguageDto))] [NullSetting(NullSetting = NullSettings.Null)] // can be invariant public int? LanguageId { get; set; } [Column("date")] public DateTime Date { get; set; } [Column("action")] public string Action { get; set; } } }
26.852941
88
0.629792
[ "MIT" ]
0Neji/Umbraco-CMS
src/Umbraco.Core/Persistence/Dtos/ContentScheduleDto.cs
915
C#
using NUnit.Framework; using Realmar.DataBindings.Editor.TestFramework.BaseTests; namespace Realmar.DataBindings.Editor.Tests { [TestFixture] internal class Positive_E2E_ConverterTests : SandboxedTest { [Test] public void OneWay_IntToString() => RunTest(); [Test] public void TwoWay_IntToString() => RunTest(); [Test] public void TwoWay_GenericConverter() => RunTest(); } }
20.684211
59
0.753181
[ "MIT" ]
laicasaane/unity-data-binding
Assets/DataBindings/Editor/Tests/Positive_E2E_ConverterTests.cs
393
C#
using i3dm.export.Tileset; using NUnit.Framework; using System.Collections.Generic; namespace i3dm.export.tests { public class TilesetGeneratorTests { [Test] public void GetTilesetTests() { // arrange var bounds = new BoundingBox3D(510231.3587475557, 6875083.881813413, 0, 525809.8658122736, 6887810.502260326, 0); var bbTile = new BoundingBox3D(510231.34375, 6881084, 0, 511231.34375, 6882084, 0); var tile = new TileInfo() { Bounds = bbTile }; // act var result = TilesetGenerator.GetTileSet(bounds, new List<TileInfo> { tile }, new List<double> { 500, 0 }, "REPLACE"); // assert (todo add more checks) Assert.IsNotNull(result); Assert.IsTrue(result.asset.version == "1.0"); } } }
31.111111
130
0.605952
[ "MIT" ]
fnicollet/i3dm.export
tests/TilesetGeneratorTests.cs
842
C#
using SFA.DAS.CommitmentsV2.Types; using System; namespace SFA.DAS.CommitmentsV2.Messages.Events { public class TransferRequestApprovedEvent { public long TransferRequestId { get; } public long CohortId { get; } public DateTime ApprovedOn { get; } public UserInfo UserInfo { get; } public TransferRequestApprovedEvent(long transferRequestId, long cohortId, DateTime approvedOn, UserInfo userInfo) { TransferRequestId = transferRequestId; CohortId = cohortId; ApprovedOn = approvedOn; UserInfo = userInfo; } } }
29.904762
122
0.654459
[ "MIT" ]
SkillsFundingAgency/das-commitments
src/CommitmentsV2/SFA.DAS.CommitmentsV2.Messages/Events/TransferRequestApprovedEvent.cs
628
C#
using System; using ClearHl7.Helpers; using ClearHl7.Serialization; namespace ClearHl7.V251.Types { /// <summary> /// HL7 Version 2 MOC - Money And Charge Code. /// </summary> public class MoneyAndChargeCode : IType { /// <summary> /// Gets or sets a value that indicates whether this instance is a subcomponent of another HL7 component instance. /// </summary> public bool IsSubcomponent { get; set; } /// <summary> /// MOC.1 - Monetary Amount. /// </summary> public Money MonetaryAmount { get; set; } /// <summary> /// MOC.2 - Charge Code. /// </summary> public CodedElement ChargeCode { get; set; } /// <summary> /// Initializes properties of this instance with values parsed from the given delimited string. Separators defined in the Configuration class are used to split the string. /// </summary> /// <param name="delimitedString">A string representation that will be deserialized into the object instance.</param> public void FromDelimitedString(string delimitedString) { FromDelimitedString(delimitedString, null); } /// <summary> /// Initializes properties of this instance with values parsed from the given delimited string. The provided separators are used to split the string. /// </summary> /// <param name="delimitedString">A string representation that will be deserialized into the object instance.</param> /// <param name="separators">The separators to use for splitting the string.</param> public void FromDelimitedString(string delimitedString, Separators separators) { Separators seps = separators ?? new Separators().UsingConfigurationValues(); string[] separator = IsSubcomponent ? seps.SubcomponentSeparator : seps.ComponentSeparator; string[] segments = delimitedString == null ? Array.Empty<string>() : delimitedString.Split(separator, StringSplitOptions.None); MonetaryAmount = segments.Length > 0 && segments[0].Length > 0 ? TypeSerializer.Deserialize<Money>(segments[0], true, seps) : null; ChargeCode = segments.Length > 1 && segments[1].Length > 0 ? TypeSerializer.Deserialize<CodedElement>(segments[1], true, seps) : null; } /// <summary> /// Returns a delimited string representation of this instance. /// </summary> /// <returns>A string.</returns> public string ToDelimitedString() { System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CurrentCulture; string separator = IsSubcomponent ? Configuration.SubcomponentSeparator : Configuration.ComponentSeparator; return string.Format( culture, StringHelper.StringFormatSequence(0, 2, separator), MonetaryAmount?.ToDelimitedString(), ChargeCode?.ToDelimitedString() ).TrimEnd(separator.ToCharArray()); } } }
45.323944
180
0.620572
[ "MIT" ]
davebronson/clear-hl7-net
src/ClearHl7/V251/Types/MoneyAndChargeCode.cs
3,220
C#
using DMCIT.Core.Entities.Core; using DMCIT.Core.Entities.Messaging; using DMCIT.Core.Interfaces; using DMCIT.Core.Services; using DMCIT.Core.SharedKernel; using DMCIT.Infrastructure.Providers; using DMCIT.Infrastructure.Services; using Hangfire.Server; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DMCIT.Infrastructure.Data { public class MessagingRepository : IMessagingRepository { private readonly IRepository _rep; private readonly AppDbContext _db; private readonly ILogger _logger; private readonly ISendMessageService _service; private readonly IProcessManagerService _processService; private readonly ISettingRepository _setting; private readonly IServiceProvider _sp; public MessagingRepository(IServiceProvider sp, AppDbContext db, IRepository rep, ISendMessageService service, ILogger<IMessagingRepository> logger, IProcessManagerService processService, ISettingRepository setting) { _sp = sp; _rep = rep; _db = db; _logger = logger; _service = service; _processService = processService; _setting = setting; } IQueryable<MessageBatch> ApplyMessageBatchFilter(IQueryable<MessageBatch> query, dynamic filter) { if (filter != null) { var dict = filter as Dictionary<string, object>; if (dict.ContainsKey("start") && dict["start"] != null) { var start = dict["start"] as DateTime?; query = query.Where(u => u.DateCreated >= start.Value); } if (dict.ContainsKey("end") && dict["end"] != null) { var end = dict["end"] as DateTime?; query = query.Where(u => u.DateCreated <= end.Value); } } return query; } public async Task<ICollection<MessageBatch>> GetMessageBatches(GetListParams<MessageBatch> p) { var ls = await _rep.List(p); return ls; } public async Task UpdateMessageBatch(MessageBatch entity) { await _rep.Update(entity); } public async Task<int> GetMessageBatchesCount(GetListParams<MessageBatch> p) { var count = await _rep.Count(p); return count; } public async Task<int> GetMessagesCount(GetListParams<SentMessage> param) { return await _rep.Count(param); } public async Task<MessageBatch> CreateMessageBatch(AppUser actor) { var batch = new MessageBatch { AutoMessageConfigId = null, MessageSourceId = null, DateRemoved = null }; var eBatch = await _rep.Add(batch, actor); return eBatch; } public async Task<MessageBatch> CreateMessageBatch(ICollection<SentMessage> messages, AppUser actor) { var eBatch = await CreateMessageBatch(actor); eBatch.SentMessages = new List<SentMessage>(); foreach (var item in messages) { item.Status = (int)SentMessage.SentMessageStatus.WAITING; item.ResponseMessage = null; item.MessageBatchId = eBatch.Id; item.SentTime = null; item.ResponseTime = null; var eMessage = await _rep.Add(item, actor); eBatch.SentMessages.Add(eMessage); } return eBatch; } public async Task<MessageBatch> GetMessageBatch(int id) { Func<IQueryable<MessageBatch>, IQueryable<MessageBatch>> func = query => query .Include(u => u.SentMessages) .ThenInclude(u => u.ReceiverProvider) .ThenInclude(u => u.MessageServiceProvider) .Include(u => u.SentMessages) .ThenInclude(u => u.ReceiverProvider) .ThenInclude(u => u.MessageReceiver); return await _rep.GetById<MessageBatch>(id, func); } public async Task UpdateSentMessage(SentMessage entity) { var temp = entity.ReceiverProvider; entity.ReceiverProvider = null; await _rep.Update(entity); entity.ReceiverProvider = temp; } public async Task<SentMessage> GetSentMessageById(int id) { return await _rep.GetById<SentMessage>(id); } public async Task<ICollection<SentMessage>> GetSentMessages(GetListParams<SentMessage> p) { var temp = p.extension; if (temp == null) temp = u => u; p.extension = v => temp(v.Include(u => u.ReceiverProvider) .ThenInclude(u => u.MessageServiceProvider) .Include(u => u.ReceiverProvider) .ThenInclude(u => u.MessageReceiver)); return await _rep.List<SentMessage>(p); } async Task<ICollection<SentMessage>> loadWillSendMessage(MessageBatch batch) { var param = new GetListParams<SentMessage>(); param.filter = new Dictionary<string, object>(); param.filter.Add("MessageBatchId", batch.Id); param.SetGetAllItems(); var sentMessages = await GetSentMessages(param); batch.SentMessages = null; batch.ActionTime = DateTime.Now; await UpdateMessageBatch(batch); return sentMessages; } async Task<IMessagingProvider> checkProviderObject(SentMessage item) { MessageServiceProvider provider = item.ReceiverProvider.MessageServiceProvider; var pClassName = provider.Module; var classType = Type.GetType(pClassName + ",DMCIT.Infrastructure"); IMessagingProvider result = null; if (classType != null) { result = ActivatorUtilities.CreateInstance(_sp, classType) as IMessagingProvider; } if (result == null) { item.Status = (int)SentMessage.SentMessageStatus.ERROR; item.ResponseTime = DateTime.Now; var er = $"NO IMPLEMENT {pClassName} TO PROVIDER {provider.Name} FOUND"; item.ResponseMessage = er; //TODO: Create MessageProviderNotFound await UpdateSentMessage(item); } return result; } async Task sendMessage(SentMessage item, IMessagingProvider provider) { item.Status = (int)SentMessage.SentMessageStatus.SENDING; await UpdateSentMessage(item); var result = await provider.SendMessage(item.Content, item.ReceiverProvider.ReceiverAddress); item.ResponseTime = DateTime.Now; item.ResponseMessage = result.ResponseMessage; if (result.Success) { item.Status = (int)SentMessage.SentMessageStatus.SENT; } else { item.Status = (int)SentMessage.SentMessageStatus.ERROR; item.ResponseMessage = result.ResponseMessage; } await UpdateSentMessage(item); } async Task<MessageBatch> sentMessageBatch(MessageBatch batch, SendMessageBatchEventCollection events) { var sentMessages = await loadWillSendMessage(batch); events?.OnSendMessageBatchStart?.Invoke(batch); foreach (var item in sentMessages) { try { if (item.Status != (int)SentMessage.SentMessageStatus.WAITING || item.SentTime != null) { //TODO: create MessageSentException class throw new Exception("THIS MESSAGE HAS BEEN SENT TO RECIPIENT"); } item.SentTime = DateTime.Now; //Find send message module, if no module found, mark this message is error with this reason. IMessagingProvider provider = await checkProviderObject(item); if (provider != null) { await sendMessage(item, provider); //TODO: define progress data events?.OnSendMessageSucceed?.Invoke(item); } } catch (SendMessageException e) { item.ResponseMessage = e.Message; item.Status = (int)SentMessage.SentMessageStatus.ERROR; events?.OnSendMessageFailed?.Invoke(item, e.Message); } finally { await UpdateSentMessage(item); } } batch.FinishTime = DateTime.Now; await UpdateMessageBatch(batch); batch.SentMessages = sentMessages; return batch; } public async Task SendMessageBatchHangfire(int batchId, AppUser actor, PerformContext context) { var events = SendMessageBatchEventCollection.CreateProcessEvent(_service, actor, context); Func<Task> task = async () => { await SendMessageBatch(batchId, actor, events); }; var title = $"Send message batch #{batchId}"; await _processService.StartProcess(context, title, task, actor); } public async Task<MessageBatch> SendMessageBatch(int batchId, AppUser actor, SendMessageBatchEventCollection events) { try { //Trigger event events?.OnSendMessageBatchInitialize?.Invoke(batchId, actor); // var batch = await GetMessageBatch(batchId); if (batch == null) { //TODO: Create MessageBatchNotFoundException class throw new Exception("Message batch not found"); } if (batch.FinishTime != null) { //TODO: Create InvalidMessageBatch Exception throw new Exception("Message batch not found"); } //Send messages batch = await sentMessageBatch(batch, events); //Has to remove batchState out of hub //Trigger events events?.OnSendMessageBatchEnd?.Invoke(batch); return batch; } catch (Exception e) { var temp = e; var mes = temp.Message; while (temp.InnerException != null) { temp = temp.InnerException; mes += Environment.NewLine + temp.Message; } events?.OnSendMessageBatchFailed?.Invoke(batchId, mes); throw; } } } }
37.627063
223
0.554864
[ "MIT" ]
thanhtuan260593/dmcit-netcore
src/DMCIT.Infrastructure/Data/MessagingRepository.cs
11,403
C#
using System.Linq; using GraphQL.Client.Http; using GraphQL.Client.Serializer.Newtonsoft; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Peer.Domain; using Peer.Domain.Configuration; using Peer.Domain.GraphQL; using Peer.Domain.Util; using wimm.Secundatives; namespace Peer.GitHub { public class GitHubWebRegistrationHandler : IRegistrationHandler { private readonly IServiceCollection _services; public string ProviderKey => ProviderConstants.Github; public GitHubWebRegistrationHandler(IServiceCollection services) { _services = services; } public Result<None, RegistrationError> Register(IConfigurationSection config) { var childConfigs = config.GetChildren().Select(x => x.Get<GitHubHandlerConfig>()) .Select(x => x.Into()) .Collect(); if (childConfigs.IsError) { //TODO:CN -- log here; return RegistrationError.BadConfig; } foreach (var gitHubConfig in childConfigs.Value) { _services.AddSingleton(sp => { var client = new GraphQLHttpClient("https://api.github.com/graphql", new NewtonsoftJsonSerializer()); client.HttpClient.DefaultRequestHeaders.Authorization = new("Bearer", gitHubConfig.AccessToken); return new NamedGraphQLBinding(gitHubConfig.Name, client); }); _services.AddSingleton<IPullRequestFetcher, GitHubRequestFetcher>(sp => { var client = sp.GetRequiredService<IGraphQLClientFactory>().GetClient(gitHubConfig.Name); return new GitHubRequestFetcher(client, gitHubConfig); }); } _services.TryAddSingleton<IGraphQLClientFactory, GraphQLClientFactory>(); return Maybe.None; } } }
35.474576
121
0.626374
[ "MIT" ]
wareismymind/peer
Peer.GitHub/GitHubWebRegistrationHandler.cs
2,093
C#
//----------------------------------------------------------------------- // <copyright file="RemainingTests.cs" company="Akka.NET Project"> // Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using Xunit; namespace Akka.TestKit.Tests.Xunit2.TestKitBaseTests { public class RemainingTests : TestKit.Xunit2.TestKit { [Fact] public void Throw_if_remaining_is_called_outside_Within() { Assert.Throws<InvalidOperationException>(() => Remaining); } } }
31.304348
88
0.534722
[ "Apache-2.0" ]
EnterpriseProductsLP/akka.net
src/core/Akka.TestKit.Tests/Xunit2/TestKitBaseTests/RemainingTests.cs
722
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 RazorLight.Host { using System; using System.Reflection; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RazorLight.Host.Resources", typeof(Resources).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Value cannot be null or empty.. /// </summary> public static string ArgumentCannotBeNullOrEmpy { get { return ResourceManager.GetString("ArgumentCannotBeNullOrEmpy", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;inherits&apos; keyword is not allowed when a &apos;{0}&apos; keyword is used.. /// </summary> public static string MvcRazorCodeParser_CannotHaveModelAndInheritsKeyword { get { return ResourceManager.GetString("MvcRazorCodeParser_CannotHaveModelAndInheritsKeyword", resourceCulture); } } /// <summary> /// Looks up a localized string similar to A property name must be specified when using the &apos;{0}&apos; statement. Format for a &apos;{0}&apos; statement is &apos;@{0} &lt;Type Name&gt; &lt;Property Name&gt;&apos;.. /// </summary> public static string MvcRazorCodeParser_InjectDirectivePropertyNameRequired { get { return ResourceManager.GetString("MvcRazorCodeParser_InjectDirectivePropertyNameRequired", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The &apos;{0}&apos; keyword must be followed by a type name on the same line.. /// </summary> public static string MvcRazorCodeParser_KeywordMustBeFollowedByTypeName { get { return ResourceManager.GetString("MvcRazorCodeParser_KeywordMustBeFollowedByTypeName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Only one &apos;{0}&apos; statement is allowed in a file.. /// </summary> public static string MvcRazorCodeParser_OnlyOneModelStatementIsAllowed { get { return ResourceManager.GetString("MvcRazorCodeParser_OnlyOneModelStatementIsAllowed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Invalid tag helper property &apos;{0}.{1}&apos;. Dictionary values must not be of type &apos;{2}&apos;.. /// </summary> public static string MvcRazorParser_InvalidPropertyType { get { return ResourceManager.GetString("MvcRazorParser_InvalidPropertyType", resourceCulture); } } } }
43.91453
230
0.602958
[ "Apache-2.0" ]
mcintyre321/RazorLight
src/RazorLight/Host/Resources.Designer.cs
5,140
C#
#region copyright //------------------------------------------------------------------------ // Copyright (C) Dmitriy Yukhanov - focus [http://codestage.net] //------------------------------------------------------------------------ #endregion namespace CodeStage.Maintainer.UI { using System.Diagnostics; using System.Globalization; using Core; using Settings; using Tools; using UnityEditor; using UnityEngine; using Debug = UnityEngine.Debug; internal class AboutTab : BaseTab { private const string UasLinkShort = "content/32199?aid=1011lGBp&pubref=Maintainer"; private const string UasLink = "https://assetstore.unity.com/packages/tools/utilities/maintainer-32199?aid=1011lGBp&pubref=Maintainer"; private const string UasReviewLink = UasLink + "#reviews"; private const string UasProfileLink = "https://assetstore.unity.com/publishers/3918?aid=1011lGBp&pubref=Maintainer"; private const string Homepage = "https://codestage.net/uas/maintainer"; private const string SupportLink = "https://codestage.net/contacts/"; private const string ChangelogLink = "https://codestage.net/uas_files/maintainer/changelog.txt"; private bool showDebug = false; protected override string CaptionName { get { return "About"; } } protected override Texture CaptionIcon { get { return CSIcons.About; } } public AboutTab(MaintainerWindow window) : base(window) {} public void Draw() { using (new GUILayout.HorizontalScope()) { /* logo */ using (new GUILayout.VerticalScope(UIHelpers.panelWithBackground, GUILayout.ExpandHeight(true), GUILayout.ExpandWidth(true))) { GUILayout.FlexibleSpace(); using (new GUILayout.HorizontalScope()) { GUILayout.FlexibleSpace(); var logo = CSImages.Logo; if (logo != null) { logo.wrapMode = TextureWrapMode.Clamp; var logoRect = EditorGUILayout.GetControlRect(GUILayout.Width(logo.width), GUILayout.Height(logo.height)); GUI.DrawTexture(logoRect, logo); GUILayout.Space(5); } GUILayout.FlexibleSpace(); } GUILayout.FlexibleSpace(); } /* buttons and stuff */ using (new GUILayout.HorizontalScope(UIHelpers.panelWithBackground, GUILayout.ExpandHeight(true), GUILayout.ExpandWidth(true))) { GUILayout.Space(10); using (new GUILayout.VerticalScope()) { GUILayout.Space(10); GUILayout.Label("<size=18>Maintainer v.<b>" + Maintainer.Version + "</b></size>", UIHelpers.centeredLabel); GUILayout.Space(10); GUILayout.Label("Developed by Dmitriy Yukhanov\n" + "Logo by Daniele Giardini\n" + "Icons by Google, Austin Andrews, Cody", UIHelpers.centeredLabel); GUILayout.Space(10); UIHelpers.Separator(); GUILayout.Space(10); if (UIHelpers.ImageButton("Homepage", CSIcons.Home)) { Application.OpenURL(Homepage); } GUILayout.Space(10); if (UIHelpers.ImageButton("Support contacts", CSIcons.Support)) { Application.OpenURL(SupportLink); } GUILayout.Space(10); if (UIHelpers.ImageButton("Full changelog (online)", CSIcons.Log)) { Application.OpenURL(ChangelogLink); } GUILayout.Space(10); //GUILayout.Space(10); //GUILayout.Label("Asset Store links", UIHelpers.centeredLabel); UIHelpers.Separator(); GUILayout.Space(10); if (UIHelpers.ImageButton("Code Stage at the Asset Store", CSIcons.Publisher)) { Application.OpenURL(UasProfileLink); } GUILayout.Space(10); if (UIHelpers.ImageButton("Maintainer at the Asset Store", CSIcons.AssetStore)) { Application.OpenURL(UasLink); } GUILayout.Space(10); if (UIHelpers.ImageButton("Rate & Write Review", CSIcons.Star)) { Application.OpenURL(UasReviewLink); } GUILayout.Label( "It's really important to know your opinion,\n rates & reviews are <b>greatly appreciated!</b>", UIHelpers.centeredLabel); GUILayout.Space(10); #if UNITY_2018_3_OR_NEWER if (Event.current.isKey && Event.current.type == EventType.KeyDown && Event.current.control && Event.current.keyCode == KeyCode.D) #else if (Event.current.isKey && Event.current.control && Event.current.keyCode == KeyCode.D) #endif { showDebug = !showDebug; Event.current.Use(); } if (showDebug) { GUILayout.Space(5); UIHelpers.Separator(); GUILayout.Space(5); GUILayout.Label("Welcome to secret debug mode =D"); if (GUILayout.Button("Remove Assets Map")) { AssetsMap.Delete(); } if (GUILayout.Button("Measure Assets Map build time")) { var sw = Stopwatch.StartNew(); AssetsMap.CreateNew(); sw.Stop(); Debug.Log("Asset Map build took " + sw.Elapsed.TotalSeconds.ToString("0.000", CultureInfo.InvariantCulture) + " seconds"); } if (GUILayout.Button("Remove Settings and Close")) { window.Close(); ProjectSettings.Delete(); } if (GUILayout.Button("Re-save all scenes in project")) { CSSceneTools.ReSaveAllScenes(); } } } GUILayout.Space(10); } } } } }
28.897297
137
0.628881
[ "MIT" ]
Stulk3/ITario-plus
Assets/Plugins/CodeStage/Maintainer/Editor/Scripts/UI/Tabs/AboutTab.cs
5,348
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. // The BigNumber class implements methods for formatting and parsing // big numeric values. To format and parse numeric values, applications should // use the Format and Parse methods provided by the numeric // classes (BigInteger). Those // Format and Parse methods share a common implementation // provided by this class, and are thus documented in detail here. // // Formatting // // The Format methods provided by the numeric classes are all of the // form // // public static String Format(XXX value, String format); // public static String Format(XXX value, String format, NumberFormatInfo info); // // where XXX is the name of the particular numeric class. The methods convert // the numeric value to a string using the format string given by the // format parameter. If the format parameter is null or // an empty string, the number is formatted as if the string "G" (general // format) was specified. The info parameter specifies the // NumberFormatInfo instance to use when formatting the number. If the // info parameter is null or omitted, the numeric formatting information // is obtained from the current culture. The NumberFormatInfo supplies // such information as the characters to use for decimal and thousand // separators, and the spelling and placement of currency symbols in monetary // values. // // Format strings fall into two categories: Standard format strings and // user-defined format strings. A format string consisting of a single // alphabetic character (A-Z or a-z), optionally followed by a sequence of // digits (0-9), is a standard format string. All other format strings are // used-defined format strings. // // A standard format string takes the form Axx, where A is an // alphabetic character called the format specifier and xx is a // sequence of digits called the precision specifier. The format // specifier controls the type of formatting applied to the number and the // precision specifier controls the number of significant digits or decimal // places of the formatting operation. The following table describes the // supported standard formats. // // C c - Currency format. The number is // converted to a string that represents a currency amount. The conversion is // controlled by the currency format information of the NumberFormatInfo // used to format the number. The precision specifier indicates the desired // number of decimal places. If the precision specifier is omitted, the default // currency precision given by the NumberFormatInfo is used. // // D d - Decimal format. This format is // supported for integral types only. The number is converted to a string of // decimal digits, prefixed by a minus sign if the number is negative. The // precision specifier indicates the minimum number of digits desired in the // resulting string. If required, the number will be left-padded with zeros to // produce the number of digits given by the precision specifier. // // E e Engineering (scientific) format. // The number is converted to a string of the form // "-d.ddd...E+ddd" or "-d.ddd...e+ddd", where each // 'd' indicates a digit (0-9). The string starts with a minus sign if the // number is negative, and one digit always precedes the decimal point. The // precision specifier indicates the desired number of digits after the decimal // point. If the precision specifier is omitted, a default of 6 digits after // the decimal point is used. The format specifier indicates whether to prefix // the exponent with an 'E' or an 'e'. The exponent is always consists of a // plus or minus sign and three digits. // // F f Fixed point format. The number is // converted to a string of the form "-ddd.ddd....", where each // 'd' indicates a digit (0-9). The string starts with a minus sign if the // number is negative. The precision specifier indicates the desired number of // decimal places. If the precision specifier is omitted, the default numeric // precision given by the NumberFormatInfo is used. // // G g - General format. The number is // converted to the shortest possible decimal representation using fixed point // or scientific format. The precision specifier determines the number of // significant digits in the resulting string. If the precision specifier is // omitted, the number of significant digits is determined by the type of the // number being converted (10 for int, 19 for long, 7 for // float, 15 for double, 19 for Currency, and 29 for // Decimal). Trailing zeros after the decimal point are removed, and the // resulting string contains a decimal point only if required. The resulting // string uses fixed point format if the exponent of the number is less than // the number of significant digits and greater than or equal to -4. Otherwise, // the resulting string uses scientific format, and the case of the format // specifier controls whether the exponent is prefixed with an 'E' or an // 'e'. // // N n Number format. The number is // converted to a string of the form "-d,ddd,ddd.ddd....", where // each 'd' indicates a digit (0-9). The string starts with a minus sign if the // number is negative. Thousand separators are inserted between each group of // three digits to the left of the decimal point. The precision specifier // indicates the desired number of decimal places. If the precision specifier // is omitted, the default numeric precision given by the // NumberFormatInfo is used. // // X x - Hexadecimal format. This format is // supported for integral types only. The number is converted to a string of // hexadecimal digits. The format specifier indicates whether to use upper or // lower case characters for the hexadecimal digits above 9 ('X' for 'ABCDEF', // and 'x' for 'abcdef'). The precision specifier indicates the minimum number // of digits desired in the resulting string. If required, the number will be // left-padded with zeros to produce the number of digits given by the // precision specifier. // // Some examples of standard format strings and their results are shown in the // table below. (The examples all assume a default NumberFormatInfo.) // // Value Format Result // 12345.6789 C $12,345.68 // -12345.6789 C ($12,345.68) // 12345 D 12345 // 12345 D8 00012345 // 12345.6789 E 1.234568E+004 // 12345.6789 E10 1.2345678900E+004 // 12345.6789 e4 1.2346e+004 // 12345.6789 F 12345.68 // 12345.6789 F0 12346 // 12345.6789 F6 12345.678900 // 12345.6789 G 12345.6789 // 12345.6789 G7 12345.68 // 123456789 G7 1.234568E8 // 12345.6789 N 12,345.68 // 123456789 N4 123,456,789.0000 // 0x2c45e x 2c45e // 0x2c45e X 2C45E // 0x2c45e X8 0002C45E // // Format strings that do not start with an alphabetic character, or that start // with an alphabetic character followed by a non-digit, are called // user-defined format strings. The following table describes the formatting // characters that are supported in user defined format strings. // // // 0 - Digit placeholder. If the value being // formatted has a digit in the position where the '0' appears in the format // string, then that digit is copied to the output string. Otherwise, a '0' is // stored in that position in the output string. The position of the leftmost // '0' before the decimal point and the rightmost '0' after the decimal point // determines the range of digits that are always present in the output // string. // // # - Digit placeholder. If the value being // formatted has a digit in the position where the '#' appears in the format // string, then that digit is copied to the output string. Otherwise, nothing // is stored in that position in the output string. // // . - Decimal point. The first '.' character // in the format string determines the location of the decimal separator in the // formatted value; any additional '.' characters are ignored. The actual // character used as a the decimal separator in the output string is given by // the NumberFormatInfo used to format the number. // // , - Thousand separator and number scaling. // The ',' character serves two purposes. First, if the format string contains // a ',' character between two digit placeholders (0 or #) and to the left of // the decimal point if one is present, then the output will have thousand // separators inserted between each group of three digits to the left of the // decimal separator. The actual character used as a the decimal separator in // the output string is given by the NumberFormatInfo used to format the // number. Second, if the format string contains one or more ',' characters // immediately to the left of the decimal point, or after the last digit // placeholder if there is no decimal point, then the number will be divided by // 1000 times the number of ',' characters before it is formatted. For example, // the format string '0,,' will represent 100 million as just 100. Use of the // ',' character to indicate scaling does not also cause the formatted number // to have thousand separators. Thus, to scale a number by 1 million and insert // thousand separators you would use the format string '#,##0,,'. // // % - Percentage placeholder. The presence of // a '%' character in the format string causes the number to be multiplied by // 100 before it is formatted. The '%' character itself is inserted in the // output string where it appears in the format string. // // E+ E- e+ e- - Scientific notation. // If any of the strings 'E+', 'E-', 'e+', or 'e-' are present in the format // string and are immediately followed by at least one '0' character, then the // number is formatted using scientific notation with an 'E' or 'e' inserted // between the number and the exponent. The number of '0' characters following // the scientific notation indicator determines the minimum number of digits to // output for the exponent. The 'E+' and 'e+' formats indicate that a sign // character (plus or minus) should always precede the exponent. The 'E-' and // 'e-' formats indicate that a sign character should only precede negative // exponents. // // \ - Literal character. A backslash character // causes the next character in the format string to be copied to the output // string as-is. The backslash itself isn't copied, so to place a backslash // character in the output string, use two backslashes (\\) in the format // string. // // 'ABC' "ABC" - Literal string. Characters // enclosed in single or double quotation marks are copied to the output string // as-is and do not affect formatting. // // ; - Section separator. The ';' character is // used to separate sections for positive, negative, and zero numbers in the // format string. // // Other - All other characters are copied to // the output string in the position they appear. // // For fixed point formats (formats not containing an 'E+', 'E-', 'e+', or // 'e-'), the number is rounded to as many decimal places as there are digit // placeholders to the right of the decimal point. If the format string does // not contain a decimal point, the number is rounded to the nearest // integer. If the number has more digits than there are digit placeholders to // the left of the decimal point, the extra digits are copied to the output // string immediately before the first digit placeholder. // // For scientific formats, the number is rounded to as many significant digits // as there are digit placeholders in the format string. // // To allow for different formatting of positive, negative, and zero values, a // user-defined format string may contain up to three sections separated by // semicolons. The results of having one, two, or three sections in the format // string are described in the table below. // // Sections: // // One - The format string applies to all values. // // Two - The first section applies to positive values // and zeros, and the second section applies to negative values. If the number // to be formatted is negative, but becomes zero after rounding according to // the format in the second section, then the resulting zero is formatted // according to the first section. // // Three - The first section applies to positive // values, the second section applies to negative values, and the third section // applies to zeros. The second section may be left empty (by having no // characters between the semicolons), in which case the first section applies // to all non-zero values. If the number to be formatted is non-zero, but // becomes zero after rounding according to the format in the first or second // section, then the resulting zero is formatted according to the third // section. // // For both standard and user-defined formatting operations on values of type // float and double, if the value being formatted is a NaN (Not // a Number) or a positive or negative infinity, then regardless of the format // string, the resulting string is given by the NaNSymbol, // PositiveInfinitySymbol, or NegativeInfinitySymbol property of // the NumberFormatInfo used to format the number. // // Parsing // // The Parse methods provided by the numeric classes are all of the form // // public static XXX Parse(String s); // public static XXX Parse(String s, int style); // public static XXX Parse(String s, int style, NumberFormatInfo info); // // where XXX is the name of the particular numeric class. The methods convert a // string to a numeric value. The optional style parameter specifies the // permitted style of the numeric string. It must be a combination of bit flags // from the NumberStyles enumeration. The optional info parameter // specifies the NumberFormatInfo instance to use when parsing the // string. If the info parameter is null or omitted, the numeric // formatting information is obtained from the current culture. // // Numeric strings produced by the Format methods using the Currency, // Decimal, Engineering, Fixed point, General, or Number standard formats // (the C, D, E, F, G, and N format specifiers) are guaranteed to be parseable // by the Parse methods if the NumberStyles.Any style is // specified. Note, however, that the Parse methods do not accept // NaNs or Infinities. // using System.Buffers; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; namespace System.Numerics { internal static class BigNumber { private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier); private struct BigNumberBuffer { public StringBuilder digits; public int precision; public int scale; public bool sign; // negative sign exists public static BigNumberBuffer Create() { BigNumberBuffer number = default; number.digits = new StringBuilder(); return number; } } internal static bool TryValidateParseStyleInteger(NumberStyles style, [NotNullWhen(false)] out ArgumentException? e) { // Check for undefined flags if ((style & InvalidNumberStyles) != 0) { e = new ArgumentException(SR.Format(SR.Argument_InvalidNumberStyles, nameof(style))); return false; } if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number if ((style & ~NumberStyles.HexNumber) != 0) { e = new ArgumentException(SR.Argument_InvalidHexStyle); return false; } } e = null; return true; } internal static bool TryParseBigInteger(string? value, NumberStyles style, NumberFormatInfo info, out BigInteger result) { if (value == null) { result = default(BigInteger); return false; } return TryParseBigInteger(value.AsSpan(), style, info, out result); } internal static bool TryParseBigInteger(ReadOnlySpan<char> value, NumberStyles style, NumberFormatInfo info, out BigInteger result) { unsafe { result = BigInteger.Zero; ArgumentException? e; if (!TryValidateParseStyleInteger(style, out e)) throw e; // TryParse still throws ArgumentException on invalid NumberStyles BigNumberBuffer bignumber = BigNumberBuffer.Create(); if (!FormatProvider.TryStringToBigInteger(value, style, info, bignumber.digits, out bignumber.precision, out bignumber.scale, out bignumber.sign)) return false; if ((style & NumberStyles.AllowHexSpecifier) != 0) { if (!HexNumberToBigInteger(ref bignumber, ref result)) { return false; } } else { if (!NumberToBigInteger(ref bignumber, ref result)) { return false; } } return true; } } internal static BigInteger ParseBigInteger(string value, NumberStyles style, NumberFormatInfo info) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return ParseBigInteger(value.AsSpan(), style, info); } internal static BigInteger ParseBigInteger(ReadOnlySpan<char> value, NumberStyles style, NumberFormatInfo info) { ArgumentException? e; if (!TryValidateParseStyleInteger(style, out e)) throw e; BigInteger result = BigInteger.Zero; if (!TryParseBigInteger(value, style, info, out result)) { throw new FormatException(SR.Overflow_ParseBigInteger); } return result; } private static unsafe bool HexNumberToBigInteger(ref BigNumberBuffer number, ref BigInteger value) { if (number.digits == null || number.digits.Length == 0) return false; int len = number.digits.Length - 1; // Ignore trailing '\0' byte[] bits = new byte[(len / 2) + (len % 2)]; bool shift = false; bool isNegative = false; int bitIndex = 0; // Parse the string into a little-endian two's complement byte array // string value : O F E B 7 \0 // string index (i) : 0 1 2 3 4 5 <-- // byte[] (bitIndex): 2 1 1 0 0 <-- // for (int i = len - 1; i > -1; i--) { char c = number.digits[i]; byte b; if (c >= '0' && c <= '9') { b = (byte)(c - '0'); } else if (c >= 'A' && c <= 'F') { b = (byte)((c - 'A') + 10); } else { Debug.Assert(c >= 'a' && c <= 'f'); b = (byte)((c - 'a') + 10); } if (i == 0 && (b & 0x08) == 0x08) isNegative = true; if (shift) { bits[bitIndex] = (byte)(bits[bitIndex] | (b << 4)); bitIndex++; } else { bits[bitIndex] = isNegative ? (byte)(b | 0xF0) : (b); } shift = !shift; } value = new BigInteger(bits); return true; } private static unsafe bool NumberToBigInteger(ref BigNumberBuffer number, ref BigInteger value) { int i = number.scale; int cur = 0; BigInteger ten = 10; value = 0; while (--i >= 0) { value *= ten; if (number.digits[cur] != '\0') { value += number.digits[cur++] - '0'; } } while (number.digits[cur] != '\0') { if (number.digits[cur++] != '0') return false; // Disallow non-zero trailing decimal places } if (number.sign) { value = -value; } return true; } // This function is consistent with VM\COMNumber.cpp!COMNumber::ParseFormatSpecifier internal static char ParseFormatSpecifier(ReadOnlySpan<char> format, out int digits) { digits = -1; if (format.Length == 0) { return 'R'; } int i = 0; char ch = format[i]; if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z') { i++; int n = -1; if (i < format.Length && format[i] >= '0' && format[i] <= '9') { n = format[i++] - '0'; while (i < format.Length && format[i] >= '0' && format[i] <= '9') { n = n * 10 + (format[i++] - '0'); if (n >= 10) break; } } if (i >= format.Length || format[i] == '\0') { digits = n; return ch; } } return (char)0; // Custom format } private static string? FormatBigIntegerToHex(bool targetSpan, BigInteger value, char format, int digits, NumberFormatInfo info, Span<char> destination, out int charsWritten, out bool spanSuccess) { Debug.Assert(format == 'x' || format == 'X'); // Get the bytes that make up the BigInteger. byte[]? arrayToReturnToPool = null; Span<byte> bits = stackalloc byte[64]; // arbitrary threshold if (!value.TryWriteOrCountBytes(bits, out int bytesWrittenOrNeeded)) { bits = arrayToReturnToPool = ArrayPool<byte>.Shared.Rent(bytesWrittenOrNeeded); bool success = value.TryWriteBytes(bits, out bytesWrittenOrNeeded); Debug.Assert(success); } bits = bits.Slice(0, bytesWrittenOrNeeded); Span<char> stackSpace = stackalloc char[128]; // each byte is typically two chars var sb = new ValueStringBuilder(stackSpace); int cur = bits.Length - 1; if (cur > -1) { // [FF..F8] drop the high F as the two's complement negative number remains clear // [F7..08] retain the high bits as the two's complement number is wrong without it // [07..00] drop the high 0 as the two's complement positive number remains clear bool clearHighF = false; byte head = bits[cur]; if (head > 0xF7) { head -= 0xF0; clearHighF = true; } if (head < 0x08 || clearHighF) { // {0xF8-0xFF} print as {8-F} // {0x00-0x07} print as {0-7} sb.Append(head < 10 ? (char)(head + '0') : format == 'X' ? (char)((head & 0xF) - 10 + 'A') : (char)((head & 0xF) - 10 + 'a')); cur--; } } if (cur > -1) { Span<char> chars = sb.AppendSpan((cur + 1) * 2); int charsPos = 0; string hexValues = format == 'x' ? "0123456789abcdef" : "0123456789ABCDEF"; while (cur > -1) { byte b = bits[cur--]; chars[charsPos++] = hexValues[b >> 4]; chars[charsPos++] = hexValues[b & 0xF]; } } if (digits > sb.Length) { // Insert leading zeros, e.g. user specified "X5" so we create "0ABCD" instead of "ABCD" sb.Insert( 0, value._sign >= 0 ? '0' : (format == 'x') ? 'f' : 'F', digits - sb.Length); } if (arrayToReturnToPool != null) { ArrayPool<byte>.Shared.Return(arrayToReturnToPool); } if (targetSpan) { spanSuccess = sb.TryCopyTo(destination, out charsWritten); return null; } else { charsWritten = 0; spanSuccess = false; return sb.ToString(); } } internal static string FormatBigInteger(BigInteger value, string? format, NumberFormatInfo info) { return FormatBigInteger(targetSpan: false, value, format, format, info, default, out _, out _)!; } internal static bool TryFormatBigInteger(BigInteger value, ReadOnlySpan<char> format, NumberFormatInfo info, Span<char> destination, out int charsWritten) { FormatBigInteger(targetSpan: true, value, null, format, info, destination, out charsWritten, out bool spanSuccess); return spanSuccess; } private static string? FormatBigInteger( bool targetSpan, BigInteger value, string? formatString, ReadOnlySpan<char> formatSpan, NumberFormatInfo info, Span<char> destination, out int charsWritten, out bool spanSuccess) { Debug.Assert(formatString == null || formatString.Length == formatSpan.Length); int digits = 0; char fmt = ParseFormatSpecifier(formatSpan, out digits); if (fmt == 'x' || fmt == 'X') { return FormatBigIntegerToHex(targetSpan, value, fmt, digits, info, destination, out charsWritten, out spanSuccess); } if (value._bits == null) { if (fmt == 'g' || fmt == 'G' || fmt == 'r' || fmt == 'R') { formatSpan = formatString = digits > 0 ? string.Format("D{0}", digits) : "D"; } if (targetSpan) { spanSuccess = value._sign.TryFormat(destination, out charsWritten, formatSpan, info); return null; } else { charsWritten = 0; spanSuccess = false; return value._sign.ToString(formatString, info); } } // First convert to base 10^9. const uint kuBase = 1000000000; // 10^9 const int kcchBase = 9; int cuSrc = value._bits.Length; int cuMax; try { cuMax = checked(cuSrc * 10 / 9 + 2); } catch (OverflowException e) { throw new FormatException(SR.Format_TooLarge, e); } uint[] rguDst = new uint[cuMax]; int cuDst = 0; for (int iuSrc = cuSrc; --iuSrc >= 0;) { uint uCarry = value._bits[iuSrc]; for (int iuDst = 0; iuDst < cuDst; iuDst++) { Debug.Assert(rguDst[iuDst] < kuBase); ulong uuRes = NumericsHelpers.MakeUlong(rguDst[iuDst], uCarry); rguDst[iuDst] = (uint)(uuRes % kuBase); uCarry = (uint)(uuRes / kuBase); } if (uCarry != 0) { rguDst[cuDst++] = uCarry % kuBase; uCarry /= kuBase; if (uCarry != 0) rguDst[cuDst++] = uCarry; } } int cchMax; try { // Each uint contributes at most 9 digits to the decimal representation. cchMax = checked(cuDst * kcchBase); } catch (OverflowException e) { throw new FormatException(SR.Format_TooLarge, e); } bool decimalFmt = (fmt == 'g' || fmt == 'G' || fmt == 'd' || fmt == 'D' || fmt == 'r' || fmt == 'R'); if (decimalFmt) { if (digits > 0 && digits > cchMax) cchMax = digits; if (value._sign < 0) { try { // Leave an extra slot for a minus sign. cchMax = checked(cchMax + info.NegativeSign.Length); } catch (OverflowException e) { throw new FormatException(SR.Format_TooLarge, e); } } } int rgchBufSize; try { // We'll pass the rgch buffer to native code, which is going to treat it like a string of digits, so it needs // to be null terminated. Let's ensure that we can allocate a buffer of that size. rgchBufSize = checked(cchMax + 1); } catch (OverflowException e) { throw new FormatException(SR.Format_TooLarge, e); } char[] rgch = new char[rgchBufSize]; int ichDst = cchMax; for (int iuDst = 0; iuDst < cuDst - 1; iuDst++) { uint uDig = rguDst[iuDst]; Debug.Assert(uDig < kuBase); for (int cch = kcchBase; --cch >= 0;) { rgch[--ichDst] = (char)('0' + uDig % 10); uDig /= 10; } } for (uint uDig = rguDst[cuDst - 1]; uDig != 0;) { rgch[--ichDst] = (char)('0' + uDig % 10); uDig /= 10; } if (!decimalFmt) { // sign = true for negative and false for 0 and positive values bool sign = (value._sign < 0); // The cut-off point to switch (G)eneral from (F)ixed-point to (E)xponential form int precision = 29; int scale = cchMax - ichDst; Span<char> stackSpace = stackalloc char[128]; // arbitrary stack cut-off var sb = new ValueStringBuilder(stackSpace); FormatProvider.FormatBigInteger(ref sb, precision, scale, sign, formatSpan, info, rgch, ichDst); if (targetSpan) { spanSuccess = sb.TryCopyTo(destination, out charsWritten); return null; } else { charsWritten = 0; spanSuccess = false; return sb.ToString(); } } // Format Round-trip decimal // This format is supported for integral types only. The number is converted to a string of // decimal digits (0-9), prefixed by a minus sign if the number is negative. The precision // specifier indicates the minimum number of digits desired in the resulting string. If required, // the number is padded with zeros to its left to produce the number of digits given by the // precision specifier. int numDigitsPrinted = cchMax - ichDst; while (digits > 0 && digits > numDigitsPrinted) { // pad leading zeros rgch[--ichDst] = '0'; digits--; } if (value._sign < 0) { string negativeSign = info.NegativeSign; for (int i = negativeSign.Length - 1; i > -1; i--) rgch[--ichDst] = negativeSign[i]; } int resultLength = cchMax - ichDst; if (!targetSpan) { charsWritten = 0; spanSuccess = false; return new string(rgch, ichDst, cchMax - ichDst); } else if (new ReadOnlySpan<char>(rgch, ichDst, cchMax - ichDst).TryCopyTo(destination)) { charsWritten = resultLength; spanSuccess = true; return null; } else { charsWritten = 0; spanSuccess = false; return null; } } } }
42.371681
203
0.580917
[ "MIT" ]
1shekhar/runtime
src/libraries/System.Runtime.Numerics/src/System/Numerics/BigNumber.cs
33,516
C#
using System; using System.Collections; using System.Globalization; using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Math; using Org.BouncyCastle.Security; using Org.BouncyCastle.Security.Certificates; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; using Org.BouncyCastle.Utilities.Date; using Org.BouncyCastle.X509; using Org.BouncyCastle.X509.Store; namespace Org.BouncyCastle.Pkix { public class Rfc3280CertPathUtilities { private static readonly PkixCrlUtilities CrlUtilities = new PkixCrlUtilities(); internal static readonly string ANY_POLICY = "2.5.29.32.0"; // key usage bits internal static readonly int KEY_CERT_SIGN = 5; internal static readonly int CRL_SIGN = 6; /** * If the complete CRL includes an issuing distribution point (IDP) CRL * extension check the following: * <p> * (i) If the distribution point name is present in the IDP CRL extension * and the distribution field is present in the DP, then verify that one of * the names in the IDP matches one of the names in the DP. If the * distribution point name is present in the IDP CRL extension and the * distribution field is omitted from the DP, then verify that one of the * names in the IDP matches one of the names in the cRLIssuer field of the * DP. * </p> * <p> * (ii) If the onlyContainsUserCerts boolean is asserted in the IDP CRL * extension, verify that the certificate does not include the basic * constraints extension with the cA boolean asserted. * </p> * <p> * (iii) If the onlyContainsCACerts boolean is asserted in the IDP CRL * extension, verify that the certificate includes the basic constraints * extension with the cA boolean asserted. * </p> * <p> * (iv) Verify that the onlyContainsAttributeCerts boolean is not asserted. * </p> * * @param dp The distribution point. * @param cert The certificate. * @param crl The CRL. * @throws AnnotatedException if one of the conditions is not met or an error occurs. */ internal static void ProcessCrlB2( DistributionPoint dp, object cert, X509Crl crl) { IssuingDistributionPoint idp = null; try { idp = IssuingDistributionPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(crl, X509Extensions.IssuingDistributionPoint)); } catch (Exception e) { throw new Exception("0 Issuing distribution point extension could not be decoded.", e); } // (b) (2) (i) // distribution point name is present if (idp != null) { if (idp.DistributionPoint != null) { // make list of names DistributionPointName dpName = IssuingDistributionPoint.GetInstance(idp).DistributionPoint; IList names = Platform.CreateArrayList(); if (dpName.PointType == DistributionPointName.FullName) { GeneralName[] genNames = GeneralNames.GetInstance(dpName.Name).GetNames(); for (int j = 0; j < genNames.Length; j++) { names.Add(genNames[j]); } } if (dpName.PointType == DistributionPointName.NameRelativeToCrlIssuer) { Asn1EncodableVector vec = new Asn1EncodableVector(); try { IEnumerator e = Asn1Sequence.GetInstance( Asn1Sequence.FromByteArray(crl.IssuerDN.GetEncoded())).GetEnumerator(); while (e.MoveNext()) { vec.Add((Asn1Encodable)e.Current); } } catch (IOException e) { throw new Exception("Could not read CRL issuer.", e); } vec.Add(dpName.Name); names.Add(new GeneralName(X509Name.GetInstance(new DerSequence(vec)))); } bool matches = false; // verify that one of the names in the IDP matches one // of the names in the DP. if (dp.DistributionPointName != null) { dpName = dp.DistributionPointName; GeneralName[] genNames = null; if (dpName.PointType == DistributionPointName.FullName) { genNames = GeneralNames.GetInstance(dpName.Name).GetNames(); } if (dpName.PointType == DistributionPointName.NameRelativeToCrlIssuer) { if (dp.CrlIssuer != null) { genNames = dp.CrlIssuer.GetNames(); } else { genNames = new GeneralName[1]; try { genNames[0] = new GeneralName( PkixCertPathValidatorUtilities.GetIssuerPrincipal(cert)); } catch (IOException e) { throw new Exception("Could not read certificate issuer.", e); } } for (int j = 0; j < genNames.Length; j++) { IEnumerator e = Asn1Sequence.GetInstance(genNames[j].Name.ToAsn1Object()).GetEnumerator(); Asn1EncodableVector vec = new Asn1EncodableVector(); while (e.MoveNext()) { vec.Add((Asn1Encodable)e.Current); } vec.Add(dpName.Name); genNames[j] = new GeneralName(X509Name.GetInstance(new DerSequence(vec))); } } if (genNames != null) { for (int j = 0; j < genNames.Length; j++) { if (names.Contains(genNames[j])) { matches = true; break; } } } if (!matches) { throw new Exception( "No match for certificate CRL issuing distribution point name to cRLIssuer CRL distribution point."); } } // verify that one of the names in // the IDP matches one of the names in the cRLIssuer field of // the DP else { if (dp.CrlIssuer == null) { throw new Exception("Either the cRLIssuer or the distributionPoint field must " + "be contained in DistributionPoint."); } GeneralName[] genNames = dp.CrlIssuer.GetNames(); for (int j = 0; j < genNames.Length; j++) { if (names.Contains(genNames[j])) { matches = true; break; } } if (!matches) { throw new Exception( "No match for certificate CRL issuing distribution point name to cRLIssuer CRL distribution point."); } } } BasicConstraints bc = null; try { bc = BasicConstraints.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue( (IX509Extension)cert, X509Extensions.BasicConstraints)); } catch (Exception e) { throw new Exception("Basic constraints extension could not be decoded.", e); } //if (cert is X509Certificate) { // (b) (2) (ii) if (idp.OnlyContainsUserCerts && ((bc != null) && bc.IsCA())) { throw new Exception("CA Cert CRL only contains user certificates."); } // (b) (2) (iii) if (idp.OnlyContainsCACerts && (bc == null || !bc.IsCA())) { throw new Exception("End CRL only contains CA certificates."); } } // (b) (2) (iv) if (idp.OnlyContainsAttributeCerts) { throw new Exception("onlyContainsAttributeCerts boolean is asserted."); } } } internal static void ProcessCertBC( PkixCertPath certPath, int index, PkixNameConstraintValidator nameConstraintValidator) //throws CertPathValidatorException { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; int n = certs.Count; // i as defined in the algorithm description int i = n - index; // // (b), (c) permitted and excluded subtree checking. // if (!(PkixCertPathValidatorUtilities.IsSelfIssued(cert) && (i < n))) { X509Name principal = cert.SubjectDN; Asn1InputStream aIn = new Asn1InputStream(principal.GetEncoded()); Asn1Sequence dns; try { dns = DerSequence.GetInstance(aIn.ReadObject()); } catch (Exception e) { throw new PkixCertPathValidatorException( "Exception extracting subject name when checking subtrees.", e, certPath, index); } try { nameConstraintValidator.CheckPermittedDN(dns); nameConstraintValidator.CheckExcludedDN(dns); } catch (PkixNameConstraintValidatorException e) { throw new PkixCertPathValidatorException( "Subtree check for certificate subject failed.", e, certPath, index); } GeneralNames altName = null; try { altName = GeneralNames.GetInstance( PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.SubjectAlternativeName)); } catch (Exception e) { throw new PkixCertPathValidatorException( "Subject alternative name extension could not be decoded.", e, certPath, index); } IList emails = X509Name.GetInstance(dns).GetValueList(X509Name.EmailAddress); foreach (string email in emails) { GeneralName emailAsGeneralName = new GeneralName(GeneralName.Rfc822Name, email); try { nameConstraintValidator.checkPermitted(emailAsGeneralName); nameConstraintValidator.checkExcluded(emailAsGeneralName); } catch (PkixNameConstraintValidatorException ex) { throw new PkixCertPathValidatorException( "Subtree check for certificate subject alternative email failed.", ex, certPath, index); } } if (altName != null) { GeneralName[] genNames = null; try { genNames = altName.GetNames(); } catch (Exception e) { throw new PkixCertPathValidatorException( "Subject alternative name contents could not be decoded.", e, certPath, index); } foreach (GeneralName genName in genNames) { try { nameConstraintValidator.checkPermitted(genName); nameConstraintValidator.checkExcluded(genName); } catch (PkixNameConstraintValidatorException e) { throw new PkixCertPathValidatorException( "Subtree check for certificate subject alternative name failed.", e, certPath, index); } } } } } internal static void PrepareNextCertA( PkixCertPath certPath, int index) //throws CertPathValidatorException { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; // // // (a) check the policy mappings // Asn1Sequence pm = null; try { pm = Asn1Sequence.GetInstance( PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.PolicyMappings)); } catch (Exception ex) { throw new PkixCertPathValidatorException( "Policy mappings extension could not be decoded.", ex, certPath, index); } if (pm != null) { Asn1Sequence mappings = pm; for (int j = 0; j < mappings.Count; j++) { DerObjectIdentifier issuerDomainPolicy = null; DerObjectIdentifier subjectDomainPolicy = null; try { Asn1Sequence mapping = DerSequence.GetInstance(mappings[j]); issuerDomainPolicy = DerObjectIdentifier.GetInstance(mapping[0]); subjectDomainPolicy = DerObjectIdentifier.GetInstance(mapping[1]); } catch (Exception e) { throw new PkixCertPathValidatorException( "Policy mappings extension contents could not be decoded.", e, certPath, index); } if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(issuerDomainPolicy.Id)) throw new PkixCertPathValidatorException( "IssuerDomainPolicy is anyPolicy", null, certPath, index); if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(subjectDomainPolicy.Id)) throw new PkixCertPathValidatorException( "SubjectDomainPolicy is anyPolicy,", null, certPath, index); } } } internal static PkixPolicyNode ProcessCertD( PkixCertPath certPath, int index, ISet acceptablePolicies, PkixPolicyNode validPolicyTree, IList[] policyNodes, int inhibitAnyPolicy) //throws CertPathValidatorException { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; int n = certs.Count; // i as defined in the algorithm description int i = n - index; // // (d) policy Information checking against initial policy and // policy mapping // Asn1Sequence certPolicies = null; try { certPolicies = DerSequence.GetInstance( PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.CertificatePolicies)); } catch (Exception e) { throw new PkixCertPathValidatorException( "Could not read certificate policies extension from certificate.", e, certPath, index); } if (certPolicies != null && validPolicyTree != null) { // // (d) (1) // ISet pols = new HashSet(); foreach (Asn1Encodable ae in certPolicies) { PolicyInformation pInfo = PolicyInformation.GetInstance(ae.ToAsn1Object()); DerObjectIdentifier pOid = pInfo.PolicyIdentifier; pols.Add(pOid.Id); if (!Rfc3280CertPathUtilities.ANY_POLICY.Equals(pOid.Id)) { ISet pq = null; try { pq = PkixCertPathValidatorUtilities.GetQualifierSet(pInfo.PolicyQualifiers); } catch (PkixCertPathValidatorException ex) { throw new PkixCertPathValidatorException( "Policy qualifier info set could not be build.", ex, certPath, index); } bool match = PkixCertPathValidatorUtilities.ProcessCertD1i(i, policyNodes, pOid, pq); if (!match) { PkixCertPathValidatorUtilities.ProcessCertD1ii(i, policyNodes, pOid, pq); } } } if (acceptablePolicies.IsEmpty || acceptablePolicies.Contains(Rfc3280CertPathUtilities.ANY_POLICY)) { acceptablePolicies.Clear(); acceptablePolicies.AddAll(pols); } else { ISet t1 = new HashSet(); foreach (object o in acceptablePolicies) { if (pols.Contains(o)) { t1.Add(o); } } acceptablePolicies.Clear(); acceptablePolicies.AddAll(t1); } // // (d) (2) // if ((inhibitAnyPolicy > 0) || ((i < n) && PkixCertPathValidatorUtilities.IsSelfIssued(cert))) { foreach (Asn1Encodable ae in certPolicies) { PolicyInformation pInfo = PolicyInformation.GetInstance(ae.ToAsn1Object()); if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(pInfo.PolicyIdentifier.Id)) { ISet _apq = PkixCertPathValidatorUtilities.GetQualifierSet(pInfo.PolicyQualifiers); IList _nodes = policyNodes[i - 1]; for (int k = 0; k < _nodes.Count; k++) { PkixPolicyNode _node = (PkixPolicyNode)_nodes[k]; IEnumerator _policySetIter = _node.ExpectedPolicies.GetEnumerator(); while (_policySetIter.MoveNext()) { object _tmp = _policySetIter.Current; string _policy; if (_tmp is string) { _policy = (string)_tmp; } else if (_tmp is DerObjectIdentifier) { _policy = ((DerObjectIdentifier)_tmp).Id; } else { continue; } bool _found = false; foreach (PkixPolicyNode _child in _node.Children) { if (_policy.Equals(_child.ValidPolicy)) { _found = true; } } if (!_found) { ISet _newChildExpectedPolicies = new HashSet(); _newChildExpectedPolicies.Add(_policy); PkixPolicyNode _newChild = new PkixPolicyNode(Platform.CreateArrayList(), i, _newChildExpectedPolicies, _node, _apq, _policy, false); _node.AddChild(_newChild); policyNodes[i].Add(_newChild); } } } break; } } } PkixPolicyNode _validPolicyTree = validPolicyTree; // // (d) (3) // for (int j = (i - 1); j >= 0; j--) { IList nodes = policyNodes[j]; for (int k = 0; k < nodes.Count; k++) { PkixPolicyNode node = (PkixPolicyNode)nodes[k]; if (!node.HasChildren) { _validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(_validPolicyTree, policyNodes, node); if (_validPolicyTree == null) { break; } } } } // // d (4) // ISet criticalExtensionOids = cert.GetCriticalExtensionOids(); if (criticalExtensionOids != null) { bool critical = criticalExtensionOids.Contains(X509Extensions.CertificatePolicies.Id); IList nodes = policyNodes[i]; for (int j = 0; j < nodes.Count; j++) { PkixPolicyNode node = (PkixPolicyNode)nodes[j]; node.IsCritical = critical; } } return _validPolicyTree; } return null; } /** * If the DP includes cRLIssuer, then verify that the issuer field in the * complete CRL matches cRLIssuer in the DP and that the complete CRL * contains an * g distribution point extension with the indirectCRL * boolean asserted. Otherwise, verify that the CRL issuer matches the * certificate issuer. * * @param dp The distribution point. * @param cert The certificate ot attribute certificate. * @param crl The CRL for <code>cert</code>. * @throws AnnotatedException if one of the above conditions does not apply or an error * occurs. */ internal static void ProcessCrlB1( DistributionPoint dp, object cert, X509Crl crl) { Asn1Object idp = PkixCertPathValidatorUtilities.GetExtensionValue( crl, X509Extensions.IssuingDistributionPoint); bool isIndirect = false; if (idp != null) { if (IssuingDistributionPoint.GetInstance(idp).IsIndirectCrl) { isIndirect = true; } } byte[] issuerBytes = crl.IssuerDN.GetEncoded(); bool matchIssuer = false; if (dp.CrlIssuer != null) { GeneralName[] genNames = dp.CrlIssuer.GetNames(); for (int j = 0; j < genNames.Length; j++) { if (genNames[j].TagNo == GeneralName.DirectoryName) { try { if (Org.BouncyCastle.Utilities.Arrays.AreEqual(genNames[j].Name.ToAsn1Object().GetEncoded(), issuerBytes)) { matchIssuer = true; } } catch (IOException e) { throw new Exception( "CRL issuer information from distribution point cannot be decoded.", e); } } } if (matchIssuer && !isIndirect) { throw new Exception("Distribution point contains cRLIssuer field but CRL is not indirect."); } if (!matchIssuer) { throw new Exception("CRL issuer of CRL does not match CRL issuer of distribution point."); } } else { if (crl.IssuerDN.Equivalent(PkixCertPathValidatorUtilities.GetIssuerPrincipal(cert), true)) { matchIssuer = true; } } if (!matchIssuer) { throw new Exception("Cannot find matching CRL issuer for certificate."); } } internal static ReasonsMask ProcessCrlD( X509Crl crl, DistributionPoint dp) //throws AnnotatedException { IssuingDistributionPoint idp = null; try { idp = IssuingDistributionPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(crl, X509Extensions.IssuingDistributionPoint)); } catch (Exception e) { throw new Exception("issuing distribution point extension could not be decoded.", e); } // (d) (1) if (idp != null && idp.OnlySomeReasons != null && dp.Reasons != null) { return new ReasonsMask(dp.Reasons.IntValue).Intersect(new ReasonsMask(idp.OnlySomeReasons .IntValue)); } // (d) (4) if ((idp == null || idp.OnlySomeReasons == null) && dp.Reasons == null) { return ReasonsMask.AllReasons; } // (d) (2) and (d)(3) ReasonsMask dpReasons = null; if (dp.Reasons == null) { dpReasons = ReasonsMask.AllReasons; } else { dpReasons = new ReasonsMask(dp.Reasons.IntValue); } ReasonsMask idpReasons = null; if (idp == null) { idpReasons = ReasonsMask.AllReasons; } else { idpReasons = new ReasonsMask(idp.OnlySomeReasons.IntValue); } return dpReasons.Intersect(idpReasons); } /** * Obtain and validate the certification path for the complete CRL issuer. * If a key usage extension is present in the CRL issuer's certificate, * verify that the cRLSign bit is set. * * @param crl CRL which contains revocation information for the certificate * <code>cert</code>. * @param cert The attribute certificate or certificate to check if it is * revoked. * @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>. * @param defaultCRLSignKey The public key of the issuer certificate * <code>defaultCRLSignCert</code>. * @param paramsPKIX paramsPKIX PKIX parameters. * @param certPathCerts The certificates on the certification path. * @return A <code>Set</code> with all keys of possible CRL issuer * certificates. * @throws AnnotatedException if the CRL is not valid or the status cannot be checked or * some error occurs. */ internal static ISet ProcessCrlF( X509Crl crl, object cert, X509Certificate defaultCRLSignCert, IAsymmetricKeyParameter defaultCRLSignKey, PkixParameters paramsPKIX, IList certPathCerts) { // (f) // get issuer from CRL X509CertStoreSelector selector = new X509CertStoreSelector(); try { selector.Subject = crl.IssuerDN; } catch (IOException e) { throw new Exception( "Subject criteria for certificate selector to find issuer certificate for CRL could not be set.", e); } // get CRL signing certs IList coll = Platform.CreateArrayList(); try { CollectionUtilities.AddRange(coll, PkixCertPathValidatorUtilities.FindCertificates(selector, paramsPKIX.GetStores())); CollectionUtilities.AddRange(coll, PkixCertPathValidatorUtilities.FindCertificates(selector, paramsPKIX.GetAdditionalStores())); } catch (Exception e) { throw new Exception("Issuer certificate for CRL cannot be searched.", e); } coll.Add(defaultCRLSignCert); IEnumerator cert_it = coll.GetEnumerator(); IList validCerts = Platform.CreateArrayList(); IList validKeys = Platform.CreateArrayList(); while (cert_it.MoveNext()) { X509Certificate signingCert = (X509Certificate)cert_it.Current; /* * CA of the certificate, for which this CRL is checked, has also * signed CRL, so skip the path validation, because is already done */ if (signingCert.Equals(defaultCRLSignCert)) { validCerts.Add(signingCert); validKeys.Add(defaultCRLSignKey); continue; } try { // CertPathBuilder builder = CertPathBuilder.GetInstance("PKIX"); PkixCertPathBuilder builder = new PkixCertPathBuilder(); selector = new X509CertStoreSelector(); selector.Certificate = signingCert; PkixParameters temp = (PkixParameters)paramsPKIX.Clone(); temp.SetTargetCertConstraints(selector); PkixBuilderParameters parameters = (PkixBuilderParameters) PkixBuilderParameters.GetInstance(temp); /* * if signingCert is placed not higher on the cert path a * dependency loop results. CRL for cert is checked, but * signingCert is needed for checking the CRL which is dependent * on checking cert because it is higher in the cert path and so * signing signingCert transitively. so, revocation is disabled, * forgery attacks of the CRL are detected in this outer loop * for all other it must be enabled to prevent forgery attacks */ if (certPathCerts.Contains(signingCert)) { parameters.IsRevocationEnabled = false; } else { parameters.IsRevocationEnabled = true; } IList certs = builder.Build(parameters).CertPath.Certificates; validCerts.Add(signingCert); validKeys.Add(PkixCertPathValidatorUtilities.GetNextWorkingKey(certs, 0)); } catch (PkixCertPathBuilderException e) { throw new Exception("Internal error.", e); } catch (PkixCertPathValidatorException e) { throw new Exception("Public key of issuer certificate of CRL could not be retrieved.", e); } //catch (Exception e) //{ // throw new Exception(e.Message); //} } ISet checkKeys = new HashSet(); Exception lastException = null; for (int i = 0; i < validCerts.Count; i++) { X509Certificate signCert = (X509Certificate)validCerts[i]; bool[] keyusage = signCert.GetKeyUsage(); if (keyusage != null && (keyusage.Length < 7 || !keyusage[CRL_SIGN])) { lastException = new Exception( "Issuer certificate key usage extension does not permit CRL signing."); } else { checkKeys.Add(validKeys[i]); } } if ((checkKeys.Count == 0) && lastException == null) { throw new Exception("Cannot find a valid issuer certificate."); } if ((checkKeys.Count == 0) && lastException != null) { throw lastException; } return checkKeys; } internal static IAsymmetricKeyParameter ProcessCrlG( X509Crl crl, ISet keys) { Exception lastException = null; foreach (IAsymmetricKeyParameter key in keys) { try { crl.Verify(key); return key; } catch (Exception e) { lastException = e; } } throw new Exception("Cannot verify CRL.", lastException); } internal static X509Crl ProcessCrlH( ISet deltaCrls, IAsymmetricKeyParameter key) { Exception lastException = null; foreach (X509Crl crl in deltaCrls) { try { crl.Verify(key); return crl; } catch (Exception e) { lastException = e; } } if (lastException != null) { throw new Exception("Cannot verify delta CRL.", lastException); } return null; } /** * Checks a distribution point for revocation information for the * certificate <code>cert</code>. * * @param dp The distribution point to consider. * @param paramsPKIX PKIX parameters. * @param cert Certificate to check if it is revoked. * @param validDate The date when the certificate revocation status should be * checked. * @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>. * @param defaultCRLSignKey The public key of the issuer certificate * <code>defaultCRLSignCert</code>. * @param certStatus The current certificate revocation status. * @param reasonMask The reasons mask which is already checked. * @param certPathCerts The certificates of the certification path. * @throws AnnotatedException if the certificate is revoked or the status cannot be checked * or some error occurs. */ private static void CheckCrl( DistributionPoint dp, PkixParameters paramsPKIX, X509Certificate cert, DateTime validDate, X509Certificate defaultCRLSignCert, IAsymmetricKeyParameter defaultCRLSignKey, CertStatus certStatus, ReasonsMask reasonMask, IList certPathCerts) //throws AnnotatedException { DateTime currentDate = DateTime.UtcNow; if (validDate.Ticks > currentDate.Ticks) { throw new Exception("Validation time is in future."); } // (a) /* * We always get timely valid CRLs, so there is no step (a) (1). * "locally cached" CRLs are assumed to be in getStore(), additional * CRLs must be enabled in the ExtendedPKIXParameters and are in * getAdditionalStore() */ ISet crls = PkixCertPathValidatorUtilities.GetCompleteCrls(dp, cert, currentDate, paramsPKIX); bool validCrlFound = false; Exception lastException = null; IEnumerator crl_iter = crls.GetEnumerator(); while (crl_iter.MoveNext() && certStatus.Status == CertStatus.Unrevoked && !reasonMask.IsAllReasons) { try { X509Crl crl = (X509Crl)crl_iter.Current; // (d) ReasonsMask interimReasonsMask = Rfc3280CertPathUtilities.ProcessCrlD(crl, dp); // (e) /* * The reasons mask is updated at the end, so only valid CRLs * can update it. If this CRL does not contain new reasons it * must be ignored. */ if (!interimReasonsMask.HasNewReasons(reasonMask)) { continue; } // (f) ISet keys = Rfc3280CertPathUtilities.ProcessCrlF(crl, cert, defaultCRLSignCert, defaultCRLSignKey, paramsPKIX, certPathCerts); // (g) IAsymmetricKeyParameter key = Rfc3280CertPathUtilities.ProcessCrlG(crl, keys); X509Crl deltaCRL = null; if (paramsPKIX.IsUseDeltasEnabled) { // get delta CRLs ISet deltaCRLs = PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl); // we only want one valid delta CRL // (h) deltaCRL = Rfc3280CertPathUtilities.ProcessCrlH(deltaCRLs, key); } /* * CRL must be be valid at the current time, not the validation * time. If a certificate is revoked with reason keyCompromise, * cACompromise, it can be used for forgery, also for the past. * This reason may not be contained in older CRLs. */ /* * in the chain model signatures stay valid also after the * certificate has been expired, so they do not have to be in * the CRL validity time */ if (paramsPKIX.ValidityModel != PkixParameters.ChainValidityModel) { /* * if a certificate has expired, but was revoked, it is not * more in the CRL, so it would be regarded as valid if the * first check is not done */ if (cert.NotAfter.Ticks < crl.ThisUpdate.Ticks) { throw new Exception("No valid CRL for current time found."); } } Rfc3280CertPathUtilities.ProcessCrlB1(dp, cert, crl); // (b) (2) Rfc3280CertPathUtilities.ProcessCrlB2(dp, cert, crl); // (c) Rfc3280CertPathUtilities.ProcessCrlC(deltaCRL, crl, paramsPKIX); // (i) Rfc3280CertPathUtilities.ProcessCrlI(validDate, deltaCRL, cert, certStatus, paramsPKIX); // (j) Rfc3280CertPathUtilities.ProcessCrlJ(validDate, crl, cert, certStatus); // (k) if (certStatus.Status == CrlReason.RemoveFromCrl) { certStatus.Status = CertStatus.Unrevoked; } // update reasons mask reasonMask.AddReasons(interimReasonsMask); ISet criticalExtensions = crl.GetCriticalExtensionOids(); if (criticalExtensions != null) { criticalExtensions = new HashSet(criticalExtensions); criticalExtensions.Remove(X509Extensions.IssuingDistributionPoint.Id); criticalExtensions.Remove(X509Extensions.DeltaCrlIndicator.Id); if (!criticalExtensions.IsEmpty) throw new Exception("CRL contains unsupported critical extensions."); } if (deltaCRL != null) { criticalExtensions = deltaCRL.GetCriticalExtensionOids(); if (criticalExtensions != null) { criticalExtensions = new HashSet(criticalExtensions); criticalExtensions.Remove(X509Extensions.IssuingDistributionPoint.Id); criticalExtensions.Remove(X509Extensions.DeltaCrlIndicator.Id); if (!criticalExtensions.IsEmpty) throw new Exception("Delta CRL contains unsupported critical extension."); } } validCrlFound = true; } catch (Exception e) { lastException = e; } } if (!validCrlFound) { throw lastException; } } /** * Checks a certificate if it is revoked. * * @param paramsPKIX PKIX parameters. * @param cert Certificate to check if it is revoked. * @param validDate The date when the certificate revocation status should be * checked. * @param sign The issuer certificate of the certificate <code>cert</code>. * @param workingPublicKey The public key of the issuer certificate <code>sign</code>. * @param certPathCerts The certificates of the certification path. * @throws AnnotatedException if the certificate is revoked or the status cannot be checked * or some error occurs. */ protected static void CheckCrls( PkixParameters paramsPKIX, X509Certificate cert, DateTime validDate, X509Certificate sign, IAsymmetricKeyParameter workingPublicKey, IList certPathCerts) { Exception lastException = null; CrlDistPoint crldp = null; try { crldp = CrlDistPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.CrlDistributionPoints)); } catch (Exception e) { throw new Exception("CRL distribution point extension could not be read.", e); } try { PkixCertPathValidatorUtilities.AddAdditionalStoresFromCrlDistributionPoint(crldp, paramsPKIX); } catch (Exception e) { throw new Exception( "No additional CRL locations could be decoded from CRL distribution point extension.", e); } CertStatus certStatus = new CertStatus(); ReasonsMask reasonsMask = new ReasonsMask(); bool validCrlFound = false; // for each distribution point if (crldp != null) { DistributionPoint[] dps = null; try { dps = crldp.GetDistributionPoints(); } catch (Exception e) { throw new Exception("Distribution points could not be read.", e); } if (dps != null) { for (int i = 0; i < dps.Length && certStatus.Status == CertStatus.Unrevoked && !reasonsMask.IsAllReasons; i++) { PkixParameters paramsPKIXClone = (PkixParameters)paramsPKIX.Clone(); try { CheckCrl(dps[i], paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask, certPathCerts); validCrlFound = true; } catch (Exception e) { lastException = e; } } } } /* * If the revocation status has not been determined, repeat the process * above with any available CRLs not specified in a distribution point * but issued by the certificate issuer. */ if (certStatus.Status == CertStatus.Unrevoked && !reasonsMask.IsAllReasons) { try { /* * assume a DP with both the reasons and the cRLIssuer fields * omitted and a distribution point name of the certificate * issuer. */ Asn1Object issuer = null; try { issuer = new Asn1InputStream(cert.IssuerDN.GetEncoded()).ReadObject(); } catch (Exception e) { throw new Exception("Issuer from certificate for CRL could not be reencoded.", e); } DistributionPoint dp = new DistributionPoint(new DistributionPointName(0, new GeneralNames( new GeneralName(GeneralName.DirectoryName, issuer))), null, null); PkixParameters paramsPKIXClone = (PkixParameters)paramsPKIX.Clone(); CheckCrl(dp, paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask, certPathCerts); validCrlFound = true; } catch (Exception e) { lastException = e; } } if (!validCrlFound) { throw lastException; } if (certStatus.Status != CertStatus.Unrevoked) { // TODO This format is forced by the NistCertPath tests string formattedDate = certStatus.RevocationDate.Value.ToString( "G", new CultureInfo("en-us")); string message = "Certificate revocation after " + formattedDate; message += ", reason: " + CrlReasons[certStatus.Status]; throw new Exception(message); } if (!reasonsMask.IsAllReasons && certStatus.Status == CertStatus.Unrevoked) { certStatus.Status = CertStatus.Undetermined; } if (certStatus.Status == CertStatus.Undetermined) { throw new Exception("Certificate status could not be determined."); } } internal static PkixPolicyNode PrepareCertB( PkixCertPath certPath, int index, IList[] policyNodes, PkixPolicyNode validPolicyTree, int policyMapping) //throws CertPathValidatorException { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; int n = certs.Count; // i as defined in the algorithm description int i = n - index; // (b) // Asn1Sequence pm = null; try { pm = (Asn1Sequence)Asn1Sequence.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.PolicyMappings)); } catch (Exception ex) { throw new PkixCertPathValidatorException( "Policy mappings extension could not be decoded.", ex, certPath, index); } PkixPolicyNode _validPolicyTree = validPolicyTree; if (pm != null) { Asn1Sequence mappings = (Asn1Sequence)pm; IDictionary m_idp = Platform.CreateHashtable(); ISet s_idp = new HashSet(); for (int j = 0; j < mappings.Count; j++) { Asn1Sequence mapping = (Asn1Sequence) mappings[j]; string id_p = ((DerObjectIdentifier) mapping[0]).Id; string sd_p = ((DerObjectIdentifier) mapping[1]).Id; ISet tmp; if (!m_idp.Contains(id_p)) { tmp = new HashSet(); tmp.Add(sd_p); m_idp[id_p] = tmp; s_idp.Add(id_p); } else { tmp = (ISet)m_idp[id_p]; tmp.Add(sd_p); } } IEnumerator it_idp = s_idp.GetEnumerator(); while (it_idp.MoveNext()) { string id_p = (string)it_idp.Current; // // (1) // if (policyMapping > 0) { bool idp_found = false; IEnumerator nodes_i = policyNodes[i].GetEnumerator(); while (nodes_i.MoveNext()) { PkixPolicyNode node = (PkixPolicyNode)nodes_i.Current; if (node.ValidPolicy.Equals(id_p)) { idp_found = true; node.ExpectedPolicies = (ISet)m_idp[id_p]; break; } } if (!idp_found) { nodes_i = policyNodes[i].GetEnumerator(); while (nodes_i.MoveNext()) { PkixPolicyNode node = (PkixPolicyNode)nodes_i.Current; if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(node.ValidPolicy)) { ISet pq = null; Asn1Sequence policies = null; try { policies = (Asn1Sequence)PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.CertificatePolicies); } catch (Exception e) { throw new PkixCertPathValidatorException( "Certificate policies extension could not be decoded.", e, certPath, index); } foreach (Asn1Encodable ae in policies) { PolicyInformation pinfo = null; try { pinfo = PolicyInformation.GetInstance(ae.ToAsn1Object()); } catch (Exception ex) { throw new PkixCertPathValidatorException( "Policy information could not be decoded.", ex, certPath, index); } if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(pinfo.PolicyIdentifier.Id)) { try { pq = PkixCertPathValidatorUtilities .GetQualifierSet(pinfo.PolicyQualifiers); } catch (PkixCertPathValidatorException ex) { throw new PkixCertPathValidatorException( "Policy qualifier info set could not be decoded.", ex, certPath, index); } break; } } bool ci = false; ISet critExtOids = cert.GetCriticalExtensionOids(); if (critExtOids != null) { ci = critExtOids.Contains(X509Extensions.CertificatePolicies.Id); } PkixPolicyNode p_node = (PkixPolicyNode)node.Parent; if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(p_node.ValidPolicy)) { PkixPolicyNode c_node = new PkixPolicyNode(Platform.CreateArrayList(), i, (ISet)m_idp[id_p], p_node, pq, id_p, ci); p_node.AddChild(c_node); policyNodes[i].Add(c_node); } break; } } } // // (2) // } else if (policyMapping <= 0) { foreach (PkixPolicyNode node in Platform.CreateArrayList(policyNodes[i])) { if (node.ValidPolicy.Equals(id_p)) { node.Parent.RemoveChild(node); for (int k = i - 1; k >= 0; k--) { foreach (PkixPolicyNode node2 in Platform.CreateArrayList(policyNodes[k])) { if (!node2.HasChildren) { _validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode( _validPolicyTree, policyNodes, node2); if (_validPolicyTree == null) break; } } } } } } } } return _validPolicyTree; } internal static ISet[] ProcessCrlA1ii( DateTime currentDate, PkixParameters paramsPKIX, X509Certificate cert, X509Crl crl) { ISet deltaSet = new HashSet(); X509CrlStoreSelector crlselect = new X509CrlStoreSelector(); crlselect.CertificateChecking = cert; try { IList issuer = Platform.CreateArrayList(); issuer.Add(crl.IssuerDN); crlselect.Issuers = issuer; } catch (IOException e) { throw new Exception("Cannot extract issuer from CRL." + e, e); } crlselect.CompleteCrlEnabled = true; ISet completeSet = CrlUtilities.FindCrls(crlselect, paramsPKIX, currentDate); if (paramsPKIX.IsUseDeltasEnabled) { // get delta CRL(s) try { deltaSet.AddAll(PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl)); } catch (Exception e) { throw new Exception("Exception obtaining delta CRLs.", e); } } return new ISet[]{ completeSet, deltaSet }; } internal static ISet ProcessCrlA1i( DateTime currentDate, PkixParameters paramsPKIX, X509Certificate cert, X509Crl crl) { ISet deltaSet = new HashSet(); if (paramsPKIX.IsUseDeltasEnabled) { CrlDistPoint freshestCRL = null; try { freshestCRL = CrlDistPoint.GetInstance( PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.FreshestCrl)); } catch (Exception e) { throw new Exception("Freshest CRL extension could not be decoded from certificate.", e); } if (freshestCRL == null) { try { freshestCRL = CrlDistPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(crl, X509Extensions.FreshestCrl)); } catch (Exception e) { throw new Exception("Freshest CRL extension could not be decoded from CRL.", e); } } if (freshestCRL != null) { try { PkixCertPathValidatorUtilities.AddAdditionalStoresFromCrlDistributionPoint(freshestCRL, paramsPKIX); } catch (Exception e) { throw new Exception( "No new delta CRL locations could be added from Freshest CRL extension.", e); } // get delta CRL(s) try { deltaSet.AddAll(PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl)); } catch (Exception e) { throw new Exception("Exception obtaining delta CRLs.", e); } } } return deltaSet; } internal static void ProcessCertF( PkixCertPath certPath, int index, PkixPolicyNode validPolicyTree, int explicitPolicy) { // // (f) // if (explicitPolicy <= 0 && validPolicyTree == null) { throw new PkixCertPathValidatorException( "No valid policy tree found when one expected.", null, certPath, index); } } internal static void ProcessCertA( PkixCertPath certPath, PkixParameters paramsPKIX, int index, IAsymmetricKeyParameter workingPublicKey, X509Name workingIssuerName, X509Certificate sign) { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; // // (a) verify // try { // (a) (1) // cert.Verify(workingPublicKey); } catch (GeneralSecurityException e) { throw new PkixCertPathValidatorException("Could not validate certificate signature.", e, certPath, index); } try { // (a) (2) // cert.CheckValidity(PkixCertPathValidatorUtilities .GetValidCertDateFromValidityModel(paramsPKIX, certPath, index)); } catch (CertificateExpiredException e) { throw new PkixCertPathValidatorException("Could not validate certificate: " + e.Message, e, certPath, index); } catch (CertificateNotYetValidException e) { throw new PkixCertPathValidatorException("Could not validate certificate: " + e.Message, e, certPath, index); } catch (Exception e) { throw new PkixCertPathValidatorException("Could not validate time of certificate.", e, certPath, index); } // // (a) (3) // if (paramsPKIX.IsRevocationEnabled) { try { CheckCrls(paramsPKIX, cert, PkixCertPathValidatorUtilities.GetValidCertDateFromValidityModel(paramsPKIX, certPath, index), sign, workingPublicKey, certs); } catch (Exception e) { Exception cause = e.InnerException; if (cause == null) { cause = e; } throw new PkixCertPathValidatorException(e.Message, cause, certPath, index); } } // // (a) (4) name chaining // X509Name issuer = PkixCertPathValidatorUtilities.GetIssuerPrincipal(cert); if (!issuer.Equivalent(workingIssuerName, true)) { throw new PkixCertPathValidatorException("IssuerName(" + issuer + ") does not match SubjectName(" + workingIssuerName + ") of signing certificate.", null, certPath, index); } } internal static int PrepareNextCertI1( PkixCertPath certPath, int index, int explicitPolicy) { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; // // (i) // Asn1Sequence pc = null; try { pc = DerSequence.GetInstance( PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.PolicyConstraints)); } catch (Exception e) { throw new PkixCertPathValidatorException( "Policy constraints extension cannot be decoded.", e, certPath, index); } int tmpInt; if (pc != null) { IEnumerator policyConstraints = pc.GetEnumerator(); while (policyConstraints.MoveNext()) { try { Asn1TaggedObject constraint = Asn1TaggedObject.GetInstance(policyConstraints.Current); if (constraint.TagNo == 0) { tmpInt = DerInteger.GetInstance(constraint, false).Value.IntValue; if (tmpInt < explicitPolicy) { return tmpInt; } break; } } catch (ArgumentException e) { throw new PkixCertPathValidatorException( "Policy constraints extension contents cannot be decoded.", e, certPath, index); } } } return explicitPolicy; } internal static int PrepareNextCertI2( PkixCertPath certPath, int index, int policyMapping) //throws CertPathValidatorException { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; // // (i) // Asn1Sequence pc = null; try { pc = DerSequence.GetInstance( PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.PolicyConstraints)); } catch (Exception e) { throw new PkixCertPathValidatorException( "Policy constraints extension cannot be decoded.", e, certPath, index); } int tmpInt; if (pc != null) { IEnumerator policyConstraints = pc.GetEnumerator(); while (policyConstraints.MoveNext()) { try { Asn1TaggedObject constraint = Asn1TaggedObject.GetInstance(policyConstraints.Current); if (constraint.TagNo == 1) { tmpInt = DerInteger.GetInstance(constraint, false).Value.IntValue; if (tmpInt < policyMapping) { return tmpInt; } break; } } catch (ArgumentException e) { throw new PkixCertPathValidatorException( "Policy constraints extension contents cannot be decoded.", e, certPath, index); } } } return policyMapping; } internal static void PrepareNextCertG( PkixCertPath certPath, int index, PkixNameConstraintValidator nameConstraintValidator) //throws CertPathValidatorException { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; // // (g) handle the name constraints extension // NameConstraints nc = null; try { Asn1Sequence ncSeq = DerSequence.GetInstance( PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.NameConstraints)); if (ncSeq != null) { nc = new NameConstraints(ncSeq); } } catch (Exception e) { throw new PkixCertPathValidatorException( "Name constraints extension could not be decoded.", e, certPath, index); } if (nc != null) { // // (g) (1) permitted subtrees // Asn1Sequence permitted = nc.PermittedSubtrees; if (permitted != null) { try { nameConstraintValidator.IntersectPermittedSubtree(permitted); } catch (Exception ex) { throw new PkixCertPathValidatorException( "Permitted subtrees cannot be build from name constraints extension.", ex, certPath, index); } } // // (g) (2) excluded subtrees // Asn1Sequence excluded = nc.ExcludedSubtrees; if (excluded != null) { IEnumerator e = excluded.GetEnumerator(); try { while (e.MoveNext()) { GeneralSubtree subtree = GeneralSubtree.GetInstance(e.Current); nameConstraintValidator.AddExcludedSubtree(subtree); } } catch (Exception ex) { throw new PkixCertPathValidatorException( "Excluded subtrees cannot be build from name constraints extension.", ex, certPath, index); } } } } internal static int PrepareNextCertJ( PkixCertPath certPath, int index, int inhibitAnyPolicy) //throws CertPathValidatorException { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; // // (j) // DerInteger iap = null; try { iap = DerInteger.GetInstance( PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.InhibitAnyPolicy)); } catch (Exception e) { throw new PkixCertPathValidatorException( "Inhibit any-policy extension cannot be decoded.", e, certPath, index); } if (iap != null) { int _inhibitAnyPolicy = iap.Value.IntValue; if (_inhibitAnyPolicy < inhibitAnyPolicy) return _inhibitAnyPolicy; } return inhibitAnyPolicy; } internal static void PrepareNextCertK( PkixCertPath certPath, int index) //throws CertPathValidatorException { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; // // (k) // BasicConstraints bc = null; try { bc = BasicConstraints.GetInstance( PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.BasicConstraints)); } catch (Exception e) { throw new PkixCertPathValidatorException("Basic constraints extension cannot be decoded.", e, certPath, index); } if (bc != null) { if (!(bc.IsCA())) throw new PkixCertPathValidatorException("Not a CA certificate"); } else { throw new PkixCertPathValidatorException("Intermediate certificate lacks BasicConstraints"); } } internal static int PrepareNextCertL( PkixCertPath certPath, int index, int maxPathLength) //throws CertPathValidatorException { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; // // (l) // if (!PkixCertPathValidatorUtilities.IsSelfIssued(cert)) { if (maxPathLength <= 0) { throw new PkixCertPathValidatorException("Max path length not greater than zero", null, certPath, index); } return maxPathLength - 1; } return maxPathLength; } internal static int PrepareNextCertM( PkixCertPath certPath, int index, int maxPathLength) //throws CertPathValidatorException { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; // // (m) // BasicConstraints bc = null; try { bc = BasicConstraints.GetInstance( PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.BasicConstraints)); } catch (Exception e) { throw new PkixCertPathValidatorException("Basic constraints extension cannot be decoded.", e, certPath, index); } if (bc != null) { IBigInteger _pathLengthConstraint = bc.PathLenConstraint; if (_pathLengthConstraint != null) { int _plc = _pathLengthConstraint.IntValue; if (_plc < maxPathLength) { return _plc; } } } return maxPathLength; } internal static void PrepareNextCertN( PkixCertPath certPath, int index) //throws CertPathValidatorException { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; // // (n) // bool[] _usage = cert.GetKeyUsage(); if ((_usage != null) && !_usage[Rfc3280CertPathUtilities.KEY_CERT_SIGN]) { throw new PkixCertPathValidatorException( "Issuer certificate keyusage extension is critical and does not permit key signing.", null, certPath, index); } } internal static void PrepareNextCertO( PkixCertPath certPath, int index, ISet criticalExtensions, IList pathCheckers) //throws CertPathValidatorException { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; // // (o) // IEnumerator tmpIter = pathCheckers.GetEnumerator(); while (tmpIter.MoveNext()) { try { ((PkixCertPathChecker)tmpIter.Current).Check(cert, criticalExtensions); } catch (PkixCertPathValidatorException e) { throw new PkixCertPathValidatorException(e.Message, e.InnerException, certPath, index); } } if (!criticalExtensions.IsEmpty) { throw new PkixCertPathValidatorException("Certificate has unsupported critical extension.", null, certPath, index); } } internal static int PrepareNextCertH1( PkixCertPath certPath, int index, int explicitPolicy) { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; // // (h) // if (!PkixCertPathValidatorUtilities.IsSelfIssued(cert)) { // // (1) // if (explicitPolicy != 0) return explicitPolicy - 1; } return explicitPolicy; } internal static int PrepareNextCertH2( PkixCertPath certPath, int index, int policyMapping) { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; // // (h) // if (!PkixCertPathValidatorUtilities.IsSelfIssued(cert)) { // // (2) // if (policyMapping != 0) return policyMapping - 1; } return policyMapping; } internal static int PrepareNextCertH3( PkixCertPath certPath, int index, int inhibitAnyPolicy) { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; // // (h) // if (!PkixCertPathValidatorUtilities.IsSelfIssued(cert)) { // // (3) // if (inhibitAnyPolicy != 0) return inhibitAnyPolicy - 1; } return inhibitAnyPolicy; } internal static int WrapupCertA( int explicitPolicy, X509Certificate cert) { // // (a) // if (!PkixCertPathValidatorUtilities.IsSelfIssued(cert) && (explicitPolicy != 0)) { explicitPolicy--; } return explicitPolicy; } internal static int WrapupCertB( PkixCertPath certPath, int index, int explicitPolicy) //throws CertPathValidatorException { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; // // (b) // int tmpInt; Asn1Sequence pc = null; try { pc = DerSequence.GetInstance( PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.PolicyConstraints)); } catch (Exception e) { throw new PkixCertPathValidatorException("Policy constraints could not be decoded.", e, certPath, index); } if (pc != null) { IEnumerator policyConstraints = pc.GetEnumerator(); while (policyConstraints.MoveNext()) { Asn1TaggedObject constraint = (Asn1TaggedObject)policyConstraints.Current; switch (constraint.TagNo) { case 0: try { tmpInt = DerInteger.GetInstance(constraint, false).Value.IntValue; } catch (Exception e) { throw new PkixCertPathValidatorException( "Policy constraints requireExplicitPolicy field could not be decoded.", e, certPath, index); } if (tmpInt == 0) { return 0; } break; } } } return explicitPolicy; } internal static void WrapupCertF( PkixCertPath certPath, int index, IList pathCheckers, ISet criticalExtensions) //throws CertPathValidatorException { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; IEnumerator tmpIter = pathCheckers.GetEnumerator(); while (tmpIter.MoveNext()) { try { ((PkixCertPathChecker)tmpIter.Current).Check(cert, criticalExtensions); } catch (PkixCertPathValidatorException e) { throw new PkixCertPathValidatorException("Additional certificate path checker failed.", e, certPath, index); } } if (!criticalExtensions.IsEmpty) { throw new PkixCertPathValidatorException("Certificate has unsupported critical extension", null, certPath, index); } } internal static PkixPolicyNode WrapupCertG( PkixCertPath certPath, PkixParameters paramsPKIX, ISet userInitialPolicySet, int index, IList[] policyNodes, PkixPolicyNode validPolicyTree, ISet acceptablePolicies) { int n = certPath.Certificates.Count; // // (g) // PkixPolicyNode intersection; // // (g) (i) // if (validPolicyTree == null) { if (paramsPKIX.IsExplicitPolicyRequired) { throw new PkixCertPathValidatorException( "Explicit policy requested but none available.", null, certPath, index); } intersection = null; } else if (PkixCertPathValidatorUtilities.IsAnyPolicy(userInitialPolicySet)) // (g) // (ii) { if (paramsPKIX.IsExplicitPolicyRequired) { if (acceptablePolicies.IsEmpty) { throw new PkixCertPathValidatorException( "Explicit policy requested but none available.", null, certPath, index); } else { ISet _validPolicyNodeSet = new HashSet(); for (int j = 0; j < policyNodes.Length; j++) { IList _nodeDepth = policyNodes[j]; for (int k = 0; k < _nodeDepth.Count; k++) { PkixPolicyNode _node = (PkixPolicyNode)_nodeDepth[k]; if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(_node.ValidPolicy)) { foreach (object o in _node.Children) { _validPolicyNodeSet.Add(o); } } } } foreach (PkixPolicyNode _node in _validPolicyNodeSet) { string _validPolicy = _node.ValidPolicy; if (!acceptablePolicies.Contains(_validPolicy)) { // TODO? // validPolicyTree = // removePolicyNode(validPolicyTree, policyNodes, // _node); } } if (validPolicyTree != null) { for (int j = (n - 1); j >= 0; j--) { IList nodes = policyNodes[j]; for (int k = 0; k < nodes.Count; k++) { PkixPolicyNode node = (PkixPolicyNode)nodes[k]; if (!node.HasChildren) { validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(validPolicyTree, policyNodes, node); } } } } } } intersection = validPolicyTree; } else { // // (g) (iii) // // This implementation is not exactly same as the one described in // RFC3280. // However, as far as the validation result is concerned, both // produce // adequate result. The only difference is whether AnyPolicy is // remain // in the policy tree or not. // // (g) (iii) 1 // ISet _validPolicyNodeSet = new HashSet(); for (int j = 0; j < policyNodes.Length; j++) { IList _nodeDepth = policyNodes[j]; for (int k = 0; k < _nodeDepth.Count; k++) { PkixPolicyNode _node = (PkixPolicyNode)_nodeDepth[k]; if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(_node.ValidPolicy)) { foreach (PkixPolicyNode _c_node in _node.Children) { if (!Rfc3280CertPathUtilities.ANY_POLICY.Equals(_c_node.ValidPolicy)) { _validPolicyNodeSet.Add(_c_node); } } } } } // // (g) (iii) 2 // IEnumerator _vpnsIter = _validPolicyNodeSet.GetEnumerator(); while (_vpnsIter.MoveNext()) { PkixPolicyNode _node = (PkixPolicyNode)_vpnsIter.Current; string _validPolicy = _node.ValidPolicy; if (!userInitialPolicySet.Contains(_validPolicy)) { validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(validPolicyTree, policyNodes, _node); } } // // (g) (iii) 4 // if (validPolicyTree != null) { for (int j = (n - 1); j >= 0; j--) { IList nodes = policyNodes[j]; for (int k = 0; k < nodes.Count; k++) { PkixPolicyNode node = (PkixPolicyNode)nodes[k]; if (!node.HasChildren) { validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(validPolicyTree, policyNodes, node); } } } } intersection = validPolicyTree; } return intersection; } /** * If use-deltas is set, verify the issuer and scope of the delta CRL. * * @param deltaCRL The delta CRL. * @param completeCRL The complete CRL. * @param pkixParams The PKIX paramaters. * @throws AnnotatedException if an exception occurs. */ internal static void ProcessCrlC( X509Crl deltaCRL, X509Crl completeCRL, PkixParameters pkixParams) { if (deltaCRL == null) return; IssuingDistributionPoint completeidp = null; try { completeidp = IssuingDistributionPoint.GetInstance( PkixCertPathValidatorUtilities.GetExtensionValue(completeCRL, X509Extensions.IssuingDistributionPoint)); } catch (Exception e) { throw new Exception("000 Issuing distribution point extension could not be decoded.", e); } if (pkixParams.IsUseDeltasEnabled) { // (c) (1) if (!deltaCRL.IssuerDN.Equivalent(completeCRL.IssuerDN, true)) throw new Exception("Complete CRL issuer does not match delta CRL issuer."); // (c) (2) IssuingDistributionPoint deltaidp = null; try { deltaidp = IssuingDistributionPoint.GetInstance( PkixCertPathValidatorUtilities.GetExtensionValue(deltaCRL, X509Extensions.IssuingDistributionPoint)); } catch (Exception e) { throw new Exception( "Issuing distribution point extension from delta CRL could not be decoded.", e); } if (!Platform.Equals(completeidp, deltaidp)) { throw new Exception( "Issuing distribution point extension from delta CRL and complete CRL does not match."); } // (c) (3) Asn1Object completeKeyIdentifier = null; try { completeKeyIdentifier = PkixCertPathValidatorUtilities.GetExtensionValue( completeCRL, X509Extensions.AuthorityKeyIdentifier); } catch (Exception e) { throw new Exception( "Authority key identifier extension could not be extracted from complete CRL.", e); } Asn1Object deltaKeyIdentifier = null; try { deltaKeyIdentifier = PkixCertPathValidatorUtilities.GetExtensionValue( deltaCRL, X509Extensions.AuthorityKeyIdentifier); } catch (Exception e) { throw new Exception( "Authority key identifier extension could not be extracted from delta CRL.", e); } if (completeKeyIdentifier == null) throw new Exception("CRL authority key identifier is null."); if (deltaKeyIdentifier == null) throw new Exception("Delta CRL authority key identifier is null."); if (!completeKeyIdentifier.Equals(deltaKeyIdentifier)) { throw new Exception( "Delta CRL authority key identifier does not match complete CRL authority key identifier."); } } } internal static void ProcessCrlI( DateTime validDate, X509Crl deltacrl, object cert, CertStatus certStatus, PkixParameters pkixParams) { if (pkixParams.IsUseDeltasEnabled && deltacrl != null) { PkixCertPathValidatorUtilities.GetCertStatus(validDate, deltacrl, cert, certStatus); } } internal static void ProcessCrlJ( DateTime validDate, X509Crl completecrl, object cert, CertStatus certStatus) { if (certStatus.Status == CertStatus.Unrevoked) { PkixCertPathValidatorUtilities.GetCertStatus(validDate, completecrl, cert, certStatus); } } internal static PkixPolicyNode ProcessCertE( PkixCertPath certPath, int index, PkixPolicyNode validPolicyTree) { IList certs = certPath.Certificates; X509Certificate cert = (X509Certificate)certs[index]; // // (e) // Asn1Sequence certPolicies = null; try { certPolicies = DerSequence.GetInstance( PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.CertificatePolicies)); } catch (Exception e) { throw new PkixCertPathValidatorException("Could not read certificate policies extension from certificate.", e, certPath, index); } if (certPolicies == null) { validPolicyTree = null; } return validPolicyTree; } internal static readonly string[] CrlReasons = new string[] { "unspecified", "keyCompromise", "cACompromise", "affiliationChanged", "superseded", "cessationOfOperation", "certificateHold", "unknown", "removeFromCRL", "privilegeWithdrawn", "aACompromise" }; } }
27.272356
144
0.646729
[ "MIT" ]
SchmooseSA/Schmoose-BouncyCastle
Crypto/pkix/Rfc3280CertPathUtilities.cs
66,790
C#
using System; namespace VoxCharger { public abstract partial class Event { public class Stop : Event { public int Duration { get; set; } public Stop(Time time) : base(time) { } public Stop(Time time, int duration) : base(time) { Duration = duration; } } } }
17.916667
48
0.425581
[ "MIT" ]
SirusDoma/VoxCharger
Sources/Events/Stop.cs
432
C#
using System; using System.Collections.Generic; using System.Collections.Concurrent; namespace NewSharp.Extensions { public static class DictionaryExtensions { public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue newValue) { if (dict.TryGetValue(key, out var value)) return value; dict.Add(key, newValue); return newValue; } public static TValue GetOrAddLazy<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, Func<TValue> newValue) { if (dict.TryGetValue(key, out var value)) return value; var calculatedValue = newValue(); dict.Add(key, calculatedValue); return calculatedValue; } public static TValue GetOrAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue newValue) { if (dict.TryGetValue(key, out var value)) return value; dict.Add(key, newValue); return newValue; } public static TValue GetOrAddLazy<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, Func<TValue> newValue) { if (dict.TryGetValue(key, out var value)) return value; var calculatedValue = newValue(); dict.Add(key, calculatedValue); return calculatedValue; } public static TValue GetOrAddDefault<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key) { if (dict.TryGetValue(key, out var value)) return value; dict.Add(key, default); return default; } public static TValue GetOrAddDefault<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key) { if (dict.TryGetValue(key, out var value)) return value; dict.Add(key, default); return default; } public static TValue GetOrAddDefault<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, TKey key) { return dict.GetOrAdd(key, default(TValue)); } } }
29.144737
125
0.583747
[ "BSD-3-Clause" ]
napen123/NewSharp
NewSharp/Extensions/Dictionary.Extensions.cs
2,217
C#
using UnityEngine; using Unity.Entities; [DisallowMultipleComponent] [AddComponentMenu("DOTS/NetworkObjectDestroyComponentProxy")] public class NetworkObjectDestroyComponentProxy : ComponentDataProxy<NetworkObjectDestroyComponent> { }
29.625
101
0.864979
[ "MIT" ]
k77torpedo/ForgeECS
Assets/ForgeECS/ComponentProxies/NetworkObjectDestroyComponentProxy.cs
239
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AnswerButton : MonoBehaviour { public uint AnswerIndex = 0; public void Answer() { ConversationUIManager.Instance().AnswerQuestion(AnswerIndex); } }
18.714286
62
0.744275
[ "MIT" ]
warddav16/ProDev
ProDev/Assets/Scripts/AnswerButton.cs
264
C#
using System.Threading.Tasks; namespace Stl.Security { public class PrefixScopedKeyVault : IKeyVault { protected IKeyVault KeyVault { get; } protected string Prefix { get; } public PrefixScopedKeyVault(IKeyVault keyVault, string prefix) { KeyVault = keyVault; Prefix = prefix; } public string? TryGetSecret(string key) => KeyVault.TryGetSecret(Prefix + key); public ValueTask<string?> TryGetSecretAsync(string key) => KeyVault.TryGetSecretAsync(Prefix + key); } }
26.5
70
0.624357
[ "MIT" ]
servicetitan/Stl.Extras
src/Stl.Experimental/Security/PrefixScopedKeyVault.cs
583
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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("AWSSDK.XRay")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS X-Ray. AWS X-Ray helps developers analyze and debug distributed applications. With X-Ray, you can understand how your application and its underlying services are performing to identify and troubleshoot the root cause of performance issues and errors.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS X-Ray. AWS X-Ray helps developers analyze and debug distributed applications. With X-Ray, you can understand how your application and its underlying services are performing to identify and troubleshoot the root cause of performance issues and errors.")] #elif PCL [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - AWS X-Ray. AWS X-Ray helps developers analyze and debug distributed applications. With X-Ray, you can understand how your application and its underlying services are performing to identify and troubleshoot the root cause of performance issues and errors.")] #elif UNITY [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - AWS X-Ray. AWS X-Ray helps developers analyze and debug distributed applications. With X-Ray, you can understand how your application and its underlying services are performing to identify and troubleshoot the root cause of performance issues and errors.")] #elif NETSTANDARD13 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- AWS X-Ray. AWS X-Ray helps developers analyze and debug distributed applications. With X-Ray, you can understand how your application and its underlying services are performing to identify and troubleshoot the root cause of performance issues and errors.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- AWS X-Ray. AWS X-Ray helps developers analyze and debug distributed applications. With X-Ray, you can understand how your application and its underlying services are performing to identify and troubleshoot the root cause of performance issues and errors.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.3.102.68")] #if WINDOWS_PHONE || UNITY [assembly: System.CLSCompliant(false)] # else [assembly: System.CLSCompliant(true)] #endif #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
63.118644
345
0.783835
[ "Apache-2.0" ]
alefranz/aws-sdk-net
sdk/src/Services/XRay/Properties/AssemblyInfo.cs
3,724
C#
//------------------------------------------------------------------------------ // <copyright file="FontInfo.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System.Web.UI; using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; using System.Drawing.Design; using System.Security.Permissions; namespace System.Web.UI.MobileControls { /* * FontInfo class. * Encapsulates all of the Style font properties into a single class. */ [ TypeConverterAttribute(typeof(ExpandableObjectConverter)) ] [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] public class FontInfo { private Style _style; // TODO: At some point, consider not having FontInfo delegate to a // Style. Not as easy as it looks, though, since we rely on the Style // for its persistence and inheritance. internal FontInfo(Style style) { _style = style; } [ Bindable(true), DefaultValue(""), Editor(typeof(System.Drawing.Design.FontNameEditor), typeof(UITypeEditor)), MobileCategory(SR.Category_Appearance), MobileSysDescription(SR.FontInfo_Name), NotifyParentProperty(true), TypeConverter(typeof(System.Web.UI.Design.MobileControls.Converters.FontNameConverter)), ] public String Name { get { return _style.FontName; } set { _style.FontName = value; } } [ Bindable(true), DefaultValue(BooleanOption.NotSet), MobileCategory(SR.Category_Appearance), MobileSysDescription(SR.FontInfo_Bold), NotifyParentProperty(true) ] public BooleanOption Bold { get { return _style.Bold; } set { _style.Bold = value; } } [ Bindable(true), DefaultValue(BooleanOption.NotSet), MobileCategory(SR.Category_Appearance), MobileSysDescription(SR.FontInfo_Italic), NotifyParentProperty(true) ] public BooleanOption Italic { get { return _style.Italic; } set { _style.Italic = value; } } [ Bindable(true), DefaultValue(FontSize.NotSet), MobileCategory(SR.Category_Appearance), MobileSysDescription(SR.FontInfo_Size), NotifyParentProperty(true) ] public FontSize Size { get { return _style.FontSize; } set { _style.FontSize = value; } } /// <summary> /// </summary> public override String ToString() { String size = (this.Size.Equals(FontSize.NotSet) ? null : Enum.GetName(typeof(FontSize), this.Size)); String s = this.Name; if (size != null) { if (s.Length != 0) { s += ", " + size; } else { s = size; } } return s; } } }
28.92029
114
0.468554
[ "Unlicense" ]
bestbat/Windows-Server
com/netfx/src/framework/mit/system/web/ui/mobilecontrols/fontinfo.cs
3,991
C#
#pragma checksum "/Users/christian/Desktop/repos/OSX .Net Core App/Views/Shared/_ValidationScriptsPartial.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "e436fc5a2b064bf206039538d1b6626723aa657b" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared__ValidationScriptsPartial), @"mvc.1.0.view", @"/Views/Shared/_ValidationScriptsPartial.cshtml")] [assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Shared/_ValidationScriptsPartial.cshtml", typeof(AspNetCore.Views_Shared__ValidationScriptsPartial))] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #line 1 "/Users/christian/Desktop/repos/OSX .Net Core App/Views/_ViewImports.cshtml" using OSX_.Net_Core_App; #line default #line hidden #line 2 "/Users/christian/Desktop/repos/OSX .Net Core App/Views/_ViewImports.cshtml" using OSX_.Net_Core_App.Models; #line default #line hidden [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"e436fc5a2b064bf206039538d1b6626723aa657b", @"/Views/Shared/_ValidationScriptsPartial.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"71adc358eb37d62b8408b25763e94e2e7e72366f", @"/Views/_ViewImports.cshtml")] public class Views_Shared__ValidationScriptsPartial : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/jquery-validation/dist/jquery.validate.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("include", "Development", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "https://ajax.aspnetcdn.com/ajax/jquery.validate/1.17.0/jquery.validate.min.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-src", "~/lib/jquery-validation/dist/jquery.validate.min.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-test", "window.jQuery && window.jQuery.validator", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("crossorigin", new global::Microsoft.AspNetCore.Html.HtmlString("anonymous"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("integrity", new global::Microsoft.AspNetCore.Html.HtmlString("sha384-rZfj/ogBloos6wzLGpPkkOr/gpkBNLZ6b6yLy4o+ok+t/SAKlL5mvXLr0OXNi1Hp"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.9/jquery.validate.unobtrusive.min.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_9 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-src", "~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_10 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-test", "window.jQuery && window.jQuery.validator && window.jQuery.validator.unobtrusive", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_11 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("integrity", new global::Microsoft.AspNetCore.Html.HtmlString("sha384-ifv0TYDWxBHzvAk2Z0n8R434FL1Rlv/Av18DXE43N/1rvHyOG4izKst0f2iSLdds"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_12 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("exclude", "Development", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.EnvironmentTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper; private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { BeginContext(0, 224, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("environment", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "94c92140565d4d7992fa3cebaa381e98", async() => { BeginContext(35, 6, true); WriteLiteral("\r\n "); EndContext(); BeginContext(41, 71, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "0a6bc9b0b1a44380b9b3cccac1b9764a", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(112, 6, true); WriteLiteral("\r\n "); EndContext(); BeginContext(118, 90, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "4244dcf426d84b968700a7ef20223164", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(208, 2, true); WriteLiteral("\r\n"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.EnvironmentTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper.Include = (string)__tagHelperAttribute_2.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(224, 2, true); WriteLiteral("\r\n"); EndContext(); BeginContext(226, 944, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("environment", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "73702fe5a84c4dc9b1b003a30162d02b", async() => { BeginContext(261, 6, true); WriteLiteral("\r\n "); EndContext(); BeginContext(267, 399, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "8808db4914934967a6a5a364351e7d29", async() => { BeginContext(651, 6, true); WriteLiteral("\r\n "); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_3.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.FallbackSrc = (string)__tagHelperAttribute_4.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.FallbackTestExpression = (string)__tagHelperAttribute_5.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(666, 6, true); WriteLiteral("\r\n "); EndContext(); BeginContext(672, 482, false); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "6686bde38fd64538a71b82a6442bcf68", async() => { BeginContext(1139, 6, true); WriteLiteral("\r\n "); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_8.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_8); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.FallbackSrc = (string)__tagHelperAttribute_9.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_9); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.FallbackTestExpression = (string)__tagHelperAttribute_10.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_10); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_11); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1154, 2, true); WriteLiteral("\r\n"); EndContext(); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.EnvironmentTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper.Exclude = (string)__tagHelperAttribute_12.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_12); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); EndContext(); BeginContext(1170, 2, true); WriteLiteral("\r\n"); EndContext(); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
84.325688
414
0.738508
[ "MIT" ]
chris-cata/dotnet-lab
src/obj/Debug/netcoreapp2.1/Razor/Views/Shared/_ValidationScriptsPartial.g.cshtml.cs
18,383
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("OnlineMessenger.TestUtils")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("OnlineMessenger.TestUtils")] [assembly: AssemblyCopyright("Copyright © Microsoft 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("520081de-b14a-4ed3-a1aa-bc4c50dc98a0")] // 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.945946
84
0.751561
[ "BSD-2-Clause" ]
andreialex007/OnlineMessenger
application/master/OnlineMessenger.TestUtils/Properties/AssemblyInfo.cs
1,444
C#
 namespace SampleApp { public class SampleMessageStore : SmtpServer.Storage.MessageStore { protected readonly System.IO.TextWriter m_writer; public SampleMessageStore(System.IO.TextWriter writer) { this.m_writer = writer; } /// <summary> /// Save the given message to the underlying storage system. /// </summary> /// <param name="context">The session context.</param> /// <param name="transaction">The SMTP message transaction to store.</param> /// <param name="buffer">The buffer that contains the message content.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A unique identifier that represents this message in the underlying message store.</returns> public override async System.Threading.Tasks.Task<SmtpServer.Protocol.SmtpResponse> SaveAsync( SmtpServer.ISessionContext context, SmtpServer.IMessageTransaction transaction, System.Buffers.ReadOnlySequence<byte> buffer, System.Threading.CancellationToken cancellationToken) { MimeKit.MimeMessage message = null; byte[] msg = null; using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { System.SequencePosition position = buffer.GetPosition(0); while (buffer.TryGet(ref position, out System.ReadOnlyMemory<byte> memory)) { // stream.Write(memory.Span); await stream.WriteAsync(memory, cancellationToken); } stream.Position = 0; msg = stream.ToArray(); // string str = System.Text.Encoding.UTF8.GetString(msg); // System.Console.WriteLine(str); message = await MimeKit.MimeMessage.LoadAsync(stream, cancellationToken); string fileName = message.MessageId + ".eml"; string messagePath = System.IO.Path.Combine(@"E:\", fileName); message.WriteTo(messagePath); } if (message != null) { this.m_writer.WriteLine("Subject={0}", message.Subject); this.m_writer.WriteLine("Body={0}", message.Body); } // End if (message != null) return SmtpServer.Protocol.SmtpResponse.Ok; } // End Task SaveAsync } // End Class } // End Namespace
33.786667
112
0.588003
[ "MIT" ]
ststeiger/SmtpServer
Examples/SampleApp/SampleMessageStore.cs
2,536
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ResTB.DB.Models { /// <summary> /// Resilience factor for mapped objects, depending on object parameters. language dependent! /// </summary> public class ResilienceFactor { public string ID { get; set; } public string Preparedness { get; set; } public virtual List<ResilienceWeight> ResilienceWeights { get; set; } public List<Objectparameter> Objectparameters { get; set; } } }
26.85
97
0.672253
[ "Apache-2.0" ]
GEOTEST-AG/MiResiliencia
DB/Models/ResilienceFactor.cs
539
C#
// <auto-generated /> using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using ToDoList.Models; namespace ToDoList.Migrations { [DbContext(typeof(ToDoListContext))] [Migration("20200121164101_Initial")] partial class Initial { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.6-servicing-10079") .HasAnnotation("Relational:MaxIdentifierLength", 64); modelBuilder.Entity("ToDoList.Models.Category", b => { b.Property<int>("CategoryId") .ValueGeneratedOnAdd(); b.Property<string>("Name"); b.HasKey("CategoryId"); b.ToTable("Categories"); }); modelBuilder.Entity("ToDoList.Models.CategoryItem", b => { b.Property<int>("CategoryItemId") .ValueGeneratedOnAdd(); b.Property<int>("CategoryId"); b.Property<int>("ItemId"); b.HasKey("CategoryItemId"); b.HasIndex("CategoryId"); b.HasIndex("ItemId"); b.ToTable("CategoryItem"); }); modelBuilder.Entity("ToDoList.Models.Item", b => { b.Property<int>("ItemId") .ValueGeneratedOnAdd(); b.Property<string>("Description"); b.HasKey("ItemId"); b.ToTable("Items"); }); modelBuilder.Entity("ToDoList.Models.CategoryItem", b => { b.HasOne("ToDoList.Models.Category", "Category") .WithMany("Items") .HasForeignKey("CategoryId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("ToDoList.Models.Item", "Item") .WithMany("Categories") .HasForeignKey("ItemId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
31.037975
75
0.505302
[ "MIT" ]
JakeAsh22/ToDoListLogin
ToDoList/Migrations/20200121164101_Initial.Designer.cs
2,454
C#
 using MiniDDD; using System; namespace DDD.CQRS.Domain.Events { public class UserCreated : DomainEvent<Guid> { public UserCreated(Guid aggregateRootKey, string name, string email) : base(aggregateRootKey) { Name = name; Email = email; } public string Name { get; set; } public string Email { get; set; } } }
21.5
101
0.591731
[ "MIT" ]
861191244/miniDDD
src/Sample/CQRS/Domain/Events/UserCreated.cs
389
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("PipeToPeer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PipeToPeer")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、このアセンブリ内の型は COM コンポーネントから // 参照できなくなります。COM からこのアセンブリ内の型にアクセスする必要がある場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("2293da2f-27dd-4016-bd9f-e473a0e5e884")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、次を使用してビルド番号とリビジョン番号を既定に設定できます // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
29.162162
56
0.750695
[ "Unlicense" ]
RyuumaKishita/DemoP2P.Net
UnityDemo/Lib/PipeToPeer/Properties/AssemblyInfo.cs
1,666
C#
using System.Collections.Generic; using System.Linq; using Expansions.Missions; using KSPAchievements; using UnityEngine; namespace Bureaucracy { public class CrewMember { private double bonusAwaitingPayment; private ProtoCrewMember crewRef; public readonly int MaxStrikes; public readonly List<CrewUnhappiness> UnhappinessEvents = new List<CrewUnhappiness>(); public bool Unhappy; public float WageModifier = 1.0f; //private bool onVacation; public double retirementDate; public bool aboutToRetire = false; public string Name { get; private set; } public double Wage { get { float experienceLevel = crewRef.experienceLevel; // ReSharper disable once CompareOfFloatsByEqualityOperator if (experienceLevel == 0) experienceLevel = 0.5f; return experienceLevel * SettingsClass.Instance.KerbalBaseWage*WageModifier; } } public CrewMember(string kerbalName) { Name = kerbalName; MaxStrikes = (int)(SettingsClass.Instance.BaseStrikesToQuit * CrewReference().stupidity); if (SettingsClass.Instance.RetirementEnabled) { int minTerm = SettingsClass.Instance.MinimumTerm; int maxTerm = SettingsClass.Instance.MaximumTerm; if (SettingsClass.Instance.RetirementEnabled) retirementDate = Utilities.Instance.Randomise.Next(minTerm, maxTerm) * FlightGlobals.GetHomeBody().orbit.period + Planetarium.GetUniversalTime(); else retirementDate = -1; } Debug.Log("[Bureaucracy]: New CrewMember setup: "+kerbalName); } public void AllocateBonus(double timeOnMission) { KeyValuePair<int, string> kvp = Utilities.Instance.ConvertUtToRealTime(timeOnMission); double payout; if (kvp.Value == "years") payout = kvp.Key * SettingsClass.Instance.LongTermBonusYears; else payout = kvp.Key * SettingsClass.Instance.LongTermBonusDays; bonusAwaitingPayment += payout; Debug.Log("[Bureaucracy]: Assigned Bonus of "+(int)payout+" to "+Name); } public ProtoCrewMember CrewReference() { List<ProtoCrewMember> crew = HighLogic.CurrentGame.CrewRoster.Crew.ToList(); for (int i = 0; i < crew.Count; i++) { ProtoCrewMember p = crew.ElementAt(i); if (p.name != Name) continue; crewRef = p; break; } //Newly hired crew members aren't actually in the crew yet, so we need to check the Applicants too. if (crewRef == null) { // ReSharper disable once Unity.PerformanceCriticalCodeInvocation Debug.Log("[Bureaucracy]: Couldn't find " + Name + " in the crew list. Checking Applicants"); crew = HighLogic.CurrentGame.CrewRoster.Applicants.ToList(); for (int i = 0; i < crew.Count; i++) { ProtoCrewMember p = crew.ElementAt(i); if (p.name != Name) continue; crewRef = p; break; } } // ReSharper disable once Unity.PerformanceCriticalCodeInvocation if (crewRef == null) Debug.Log("[Bureaucracy]: Couldn't find a crew ref for " + Name); return crewRef; } public void Train() { int newLevel = CrewReference().experienceLevel + 1; KerbalRoster.SetExperienceLevel(CrewReference(), newLevel); double trainingTime = newLevel * Utilities.Instance.GetMonthLength(); CrewReference().SetInactive(trainingTime); Utilities.Instance.NewStockAlarm(Name+" - Training", Name+" has completed their training",Planetarium.GetUniversalTime()+trainingTime); Debug.Log("[Bureaucracy]: "+Name+" entered training for "+trainingTime+", new Level: "+newLevel); } public int GetBonus(bool clearBonus) { double payment = bonusAwaitingPayment; if(clearBonus) bonusAwaitingPayment = 0; return (int)payment; } public void OnSave(ConfigNode crewManagerNode) { ConfigNode crewNode = new ConfigNode("CREW_MEMBER"); crewNode.SetValue("Name", Name, true); crewNode.SetValue("Bonus", bonusAwaitingPayment, true); crewNode.SetValue("WageModifier", WageModifier, true); crewNode.SetValue("RetirementDate", retirementDate, true); for (int i = 0; i < UnhappinessEvents.Count; i++) { CrewUnhappiness cu = UnhappinessEvents.ElementAt(i); cu.OnSave(crewNode); } crewManagerNode.AddNode(crewNode); } public void OnLoad(ConfigNode crewConfig) { Name = crewConfig.GetValue("Name"); double.TryParse(crewConfig.GetValue("Bonus"), out bonusAwaitingPayment); double.TryParse(crewConfig.GetValue("RetirementDate"), out retirementDate); if(retirementDate == -1 && SettingsClass.Instance.RetirementEnabled) retirementDate = Utilities.Instance.Randomise.Next(SettingsClass.Instance.MinimumTerm, SettingsClass.Instance.MaximumTerm) * FlightGlobals.GetHomeBody().orbit.period + Planetarium.GetUniversalTime(); else if (!SettingsClass.Instance.RetirementEnabled) retirementDate = -1; if (!crewConfig.TryGetValue("WageModifier", ref WageModifier)) WageModifier = 1.0f; ConfigNode[] unhappyNodes = crewConfig.GetNodes("UNHAPPINESS"); for (int i = 0; i < unhappyNodes.Length; i++) { CrewUnhappiness cu = new CrewUnhappiness("loading", this); cu.OnLoad(unhappyNodes.ElementAt(i)); UnhappinessEvents.Add(cu); Unhappy = true; } } public string UnhappyOutcome() { if (CrewReference().rosterStatus == ProtoCrewMember.RosterStatus.Assigned) return " is not happy but will continue for the sake of the mission"; if(UnhappinessEvents.Count >= MaxStrikes) return " Quit the space program due to "+UnhappinessEvents.Last().Reason; return "is not happy due to " + UnhappinessEvents.Last().Reason; } public void MonthWithoutIncident() { for (int i = UnhappinessEvents.Count-1; i >= 0; i--) { CrewUnhappiness cu = UnhappinessEvents.ElementAt(i); if (cu.ClearStrike()) UnhappinessEvents.Remove(cu); } } public void AddUnhappiness(string reason) { UnhappinessEvents.Add(new CrewUnhappiness(reason, this)); Unhappy = true; } public void ExtendRetirementAge(double extension) { retirementDate += extension; } } }
43.012048
280
0.6
[ "MIT" ]
Gordon-Dry/Bureaucracy
Bureaucracy/Crew/CrewMember.cs
7,140
C#
using GitTrends.Mobile.Shared; using ImageCircle.Forms.Plugin.Abstractions; using Xamarin.Forms; namespace GitTrends { public class GitHubSettingsView : ContentView { public GitHubSettingsView() { var gitHubAvatarImage = new CircleImage { AutomationId = SettingsPageAutomationIds.GitHubAvatarImage, HeightRequest = 200, WidthRequest = 200, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center, Aspect = Aspect.AspectFill }; gitHubAvatarImage.SetBinding(CircleImage.SourceProperty, nameof(SettingsViewModel.GitHubAvatarImageSource)); var gitHubAliasLabel = new Label { HorizontalTextAlignment = TextAlignment.Center, AutomationId = SettingsPageAutomationIds.GitHubAliasLabel, }; gitHubAliasLabel.SetBinding(Label.TextProperty, nameof(SettingsViewModel.GitHubAliasLabelText)); var gitHubLoginButton = new FontAwesomeButton { AutomationId = SettingsPageAutomationIds.GitHubLoginButton, TextColor = Color.White, FontSize = 24, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center, Padding = new Thickness(10), Margin = new Thickness(0, 25, 0, 5) }; gitHubLoginButton.SetDynamicResource(BackgroundColorProperty, nameof(BaseTheme.ButtonBackgroundColor)); gitHubLoginButton.SetBinding(Button.TextProperty, nameof(SettingsViewModel.LoginButtonText)); gitHubLoginButton.SetBinding(Button.CommandProperty, nameof(SettingsViewModel.LoginButtonCommand)); var activityIndicator = new ActivityIndicator { AutomationId = SettingsPageAutomationIds.GitHubSettingsViewActivityIndicator, VerticalOptions = LayoutOptions.Start }; activityIndicator.SetDynamicResource(ActivityIndicator.ColorProperty, nameof(BaseTheme.RefreshControlColor)); activityIndicator.SetBinding(IsVisibleProperty, nameof(SettingsViewModel.IsAuthenticating)); activityIndicator.SetBinding(ActivityIndicator.IsRunningProperty, nameof(SettingsViewModel.IsAuthenticating)); var grid = new Grid { RowDefinitions = { new RowDefinition { Height = new GridLength(7, GridUnitType.Star) }, new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) }, new RowDefinition { Height = new GridLength(20, GridUnitType.Absolute) } }, ColumnDefinitions = { new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) } } }; grid.Children.Add(gitHubAvatarImage, 0, 0); grid.Children.Add(gitHubLoginButton, 0, 1); grid.Children.Add(activityIndicator, 0, 2); Content = grid; } } }
43.310811
122
0.619033
[ "MIT" ]
GitTrends/GitTrends
GitTrends/Views/Settings/GitHubSettingsView.cs
3,207
C#
using System.Windows; namespace WPFCalc { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
15.666667
43
0.56383
[ "MIT" ]
fossabot/WPFCalc
App.xaml.cs
190
C#
namespace AssistiveRobot.Web.Service.Models.Request { public class GoalRequest { public string Status { get; set; } = null; } }
21
51
0.653061
[ "MIT" ]
chatreejs/assistiverobot-web-service
Assistiverobot.Web.Service/Models/Request/GoalRequest.cs
147
C#
using System; using System.Collections.Generic; using System.Linq; using Enterspeed.Source.Sdk.Api.Models.Properties; using Enterspeed.Source.SitecoreCms.V8.Models.Configuration; using HtmlAgilityPack; using Sitecore.Data.Fields; using Sitecore.Data.Items; using Sitecore.Web.UI.WebControls; namespace Enterspeed.Source.SitecoreCms.V8.Services.DataProperties.DefaultFieldConverters { public class DefaultRichTextFieldValueConverter : IEnterspeedFieldValueConverter { private readonly IEnterspeedSitecoreFieldService _fieldService; public DefaultRichTextFieldValueConverter( IEnterspeedSitecoreFieldService fieldService) { _fieldService = fieldService; } public bool CanConvert(Field field) { return field != null && field.TypeKey.Equals("rich text", StringComparison.OrdinalIgnoreCase); } public IEnterspeedProperty Convert(Item item, Field field, EnterspeedSiteInfo siteInfo, List<IEnterspeedFieldValueConverter> fieldValueConverters, EnterspeedSitecoreConfiguration configuration) { string value = FieldRenderer.Render(item, field.Name); if (siteInfo != null) { value = PrefixRelativeImagesWithDomain(value, siteInfo.BaseUrl); value = PrefixRelativeLinksWithDomain(value, siteInfo.BaseUrl); } return new StringEnterspeedProperty(_fieldService.GetFieldName(field), value); } private static string PrefixRelativeImagesWithDomain(string html, string baseUrl) { if (string.IsNullOrWhiteSpace(html) || string.IsNullOrWhiteSpace(baseUrl)) { return html; } var htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(html); var imageNodes = htmlDocument.DocumentNode.SelectNodes("//img"); if (imageNodes == null || !imageNodes.Any()) { return html; } var baseUri = new Uri(baseUrl, UriKind.Absolute); foreach (var imageNode in imageNodes) { var src = imageNode.GetAttributeValue("src", string.Empty); if (src.StartsWith("-/media/") || src.StartsWith("~/media/")) { imageNode.SetAttributeValue("src", new Uri(baseUri, src).ToString()); } } return htmlDocument.DocumentNode.InnerHtml; } private static string PrefixRelativeLinksWithDomain(string html, string baseUrl) { if (string.IsNullOrWhiteSpace(html) || string.IsNullOrWhiteSpace(baseUrl)) { return html; } var htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(html); var anchorNodes = htmlDocument.DocumentNode.SelectNodes("//a"); if (anchorNodes == null || !anchorNodes.Any()) { return html; } var baseUri = new Uri(baseUrl, UriKind.Absolute); foreach (var anchorNode in anchorNodes) { var href = anchorNode.GetAttributeValue("href", string.Empty); if (string.IsNullOrEmpty(href)) { continue; } if (!Uri.TryCreate(href, UriKind.RelativeOrAbsolute, out var uri)) { continue; } if (!uri.IsAbsoluteUri || href.StartsWith("/")) { anchorNode.SetAttributeValue("href", new Uri(baseUri, href).ToString()); } } return htmlDocument.DocumentNode.InnerHtml; } } }
34.232143
201
0.584246
[ "MIT" ]
MHove89/enterspeed-source-sitecore-cms
src/Enterspeed.Source.SitecoreCms.V8/Services/DataProperties/DefaultFieldConverters/DefaultRichTextFieldValueConverter.cs
3,836
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager; using Azure.ResourceManager.Cdn.Models; using Azure.ResourceManager.Resources; namespace Azure.ResourceManager.Cdn { /// <summary> /// A Class representing a CdnWebApplicationFirewallPolicy along with the instance operations that can be performed on it. /// If you have a <see cref="ResourceIdentifier" /> you can construct a <see cref="CdnWebApplicationFirewallPolicyResource" /> /// from an instance of <see cref="ArmClient" /> using the GetCdnWebApplicationFirewallPolicyResource method. /// Otherwise you can get one from its parent resource <see cref="ResourceGroupResource" /> using the GetCdnWebApplicationFirewallPolicy method. /// </summary> public partial class CdnWebApplicationFirewallPolicyResource : ArmResource { /// <summary> Generate the resource identifier of a <see cref="CdnWebApplicationFirewallPolicyResource"/> instance. </summary> public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string policyName) { var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName}"; return new ResourceIdentifier(resourceId); } private readonly ClientDiagnostics _cdnWebApplicationFirewallPolicyPoliciesClientDiagnostics; private readonly PoliciesRestOperations _cdnWebApplicationFirewallPolicyPoliciesRestClient; private readonly CdnWebApplicationFirewallPolicyData _data; /// <summary> Initializes a new instance of the <see cref="CdnWebApplicationFirewallPolicyResource"/> class for mocking. </summary> protected CdnWebApplicationFirewallPolicyResource() { } /// <summary> Initializes a new instance of the <see cref = "CdnWebApplicationFirewallPolicyResource"/> class. </summary> /// <param name="client"> The client parameters to use in these operations. </param> /// <param name="data"> The resource that is the target of operations. </param> internal CdnWebApplicationFirewallPolicyResource(ArmClient client, CdnWebApplicationFirewallPolicyData data) : this(client, data.Id) { HasData = true; _data = data; } /// <summary> Initializes a new instance of the <see cref="CdnWebApplicationFirewallPolicyResource"/> class. </summary> /// <param name="client"> The client parameters to use in these operations. </param> /// <param name="id"> The identifier of the resource that is the target of operations. </param> internal CdnWebApplicationFirewallPolicyResource(ArmClient client, ResourceIdentifier id) : base(client, id) { _cdnWebApplicationFirewallPolicyPoliciesClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Cdn", ResourceType.Namespace, Diagnostics); TryGetApiVersion(ResourceType, out string cdnWebApplicationFirewallPolicyPoliciesApiVersion); _cdnWebApplicationFirewallPolicyPoliciesRestClient = new PoliciesRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, cdnWebApplicationFirewallPolicyPoliciesApiVersion); #if DEBUG ValidateResourceId(Id); #endif } /// <summary> Gets the resource type for the operations. </summary> public static readonly ResourceType ResourceType = "Microsoft.Cdn/cdnWebApplicationFirewallPolicies"; /// <summary> Gets whether or not the current instance has data. </summary> public virtual bool HasData { get; } /// <summary> Gets the data representing this Feature. </summary> /// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception> public virtual CdnWebApplicationFirewallPolicyData Data { get { if (!HasData) throw new InvalidOperationException("The current instance does not have data, you must call Get first."); return _data; } } internal static void ValidateResourceId(ResourceIdentifier id) { if (id.ResourceType != ResourceType) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id)); } /// <summary> /// Retrieve protection policy with specified name within a resource group. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName} /// Operation Id: Policies_Get /// </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<CdnWebApplicationFirewallPolicyResource>> GetAsync(CancellationToken cancellationToken = default) { using var scope = _cdnWebApplicationFirewallPolicyPoliciesClientDiagnostics.CreateScope("CdnWebApplicationFirewallPolicyResource.Get"); scope.Start(); try { var response = await _cdnWebApplicationFirewallPolicyPoliciesRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); if (response.Value == null) throw new RequestFailedException(response.GetRawResponse()); return Response.FromValue(new CdnWebApplicationFirewallPolicyResource(Client, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Retrieve protection policy with specified name within a resource group. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName} /// Operation Id: Policies_Get /// </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<CdnWebApplicationFirewallPolicyResource> Get(CancellationToken cancellationToken = default) { using var scope = _cdnWebApplicationFirewallPolicyPoliciesClientDiagnostics.CreateScope("CdnWebApplicationFirewallPolicyResource.Get"); scope.Start(); try { var response = _cdnWebApplicationFirewallPolicyPoliciesRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); if (response.Value == null) throw new RequestFailedException(response.GetRawResponse()); return Response.FromValue(new CdnWebApplicationFirewallPolicyResource(Client, response.Value), response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Deletes Policy /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName} /// Operation Id: Policies_Delete /// </summary> /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<ArmOperation> DeleteAsync(WaitUntil waitUntil, CancellationToken cancellationToken = default) { using var scope = _cdnWebApplicationFirewallPolicyPoliciesClientDiagnostics.CreateScope("CdnWebApplicationFirewallPolicyResource.Delete"); scope.Start(); try { var response = await _cdnWebApplicationFirewallPolicyPoliciesRestClient.DeleteAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); var operation = new CdnArmOperation(response); if (waitUntil == WaitUntil.Completed) await operation.WaitForCompletionResponseAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Deletes Policy /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName} /// Operation Id: Policies_Delete /// </summary> /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual ArmOperation Delete(WaitUntil waitUntil, CancellationToken cancellationToken = default) { using var scope = _cdnWebApplicationFirewallPolicyPoliciesClientDiagnostics.CreateScope("CdnWebApplicationFirewallPolicyResource.Delete"); scope.Start(); try { var response = _cdnWebApplicationFirewallPolicyPoliciesRestClient.Delete(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); var operation = new CdnArmOperation(response); if (waitUntil == WaitUntil.Completed) operation.WaitForCompletionResponse(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Update an existing CdnWebApplicationFirewallPolicy with the specified policy name under the specified subscription and resource group /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName} /// Operation Id: Policies_Update /// </summary> /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param> /// <param name="patch"> CdnWebApplicationFirewallPolicy parameters to be patched. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="patch"/> is null. </exception> public virtual async Task<ArmOperation<CdnWebApplicationFirewallPolicyResource>> UpdateAsync(WaitUntil waitUntil, CdnWebApplicationFirewallPolicyPatch patch, CancellationToken cancellationToken = default) { Argument.AssertNotNull(patch, nameof(patch)); using var scope = _cdnWebApplicationFirewallPolicyPoliciesClientDiagnostics.CreateScope("CdnWebApplicationFirewallPolicyResource.Update"); scope.Start(); try { var response = await _cdnWebApplicationFirewallPolicyPoliciesRestClient.UpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, patch, cancellationToken).ConfigureAwait(false); var operation = new CdnArmOperation<CdnWebApplicationFirewallPolicyResource>(new CdnWebApplicationFirewallPolicyOperationSource(Client), _cdnWebApplicationFirewallPolicyPoliciesClientDiagnostics, Pipeline, _cdnWebApplicationFirewallPolicyPoliciesRestClient.CreateUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, patch).Request, response, OperationFinalStateVia.Location); if (waitUntil == WaitUntil.Completed) await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Update an existing CdnWebApplicationFirewallPolicy with the specified policy name under the specified subscription and resource group /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName} /// Operation Id: Policies_Update /// </summary> /// <param name="waitUntil"> <see cref="WaitUntil.Completed"/> if the method should wait to return until the long-running operation has completed on the service; <see cref="WaitUntil.Started"/> if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param> /// <param name="patch"> CdnWebApplicationFirewallPolicy parameters to be patched. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="patch"/> is null. </exception> public virtual ArmOperation<CdnWebApplicationFirewallPolicyResource> Update(WaitUntil waitUntil, CdnWebApplicationFirewallPolicyPatch patch, CancellationToken cancellationToken = default) { Argument.AssertNotNull(patch, nameof(patch)); using var scope = _cdnWebApplicationFirewallPolicyPoliciesClientDiagnostics.CreateScope("CdnWebApplicationFirewallPolicyResource.Update"); scope.Start(); try { var response = _cdnWebApplicationFirewallPolicyPoliciesRestClient.Update(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, patch, cancellationToken); var operation = new CdnArmOperation<CdnWebApplicationFirewallPolicyResource>(new CdnWebApplicationFirewallPolicyOperationSource(Client), _cdnWebApplicationFirewallPolicyPoliciesClientDiagnostics, Pipeline, _cdnWebApplicationFirewallPolicyPoliciesRestClient.CreateUpdateRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, patch).Request, response, OperationFinalStateVia.Location); if (waitUntil == WaitUntil.Completed) operation.WaitForCompletion(cancellationToken); return operation; } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Add a tag to the current resource. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName} /// Operation Id: Policies_Get /// </summary> /// <param name="key"> The key for the tag. </param> /// <param name="value"> The value for the tag. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="key"/> or <paramref name="value"/> is null. </exception> public virtual async Task<Response<CdnWebApplicationFirewallPolicyResource>> AddTagAsync(string key, string value, CancellationToken cancellationToken = default) { Argument.AssertNotNull(key, nameof(key)); Argument.AssertNotNull(value, nameof(value)); using var scope = _cdnWebApplicationFirewallPolicyPoliciesClientDiagnostics.CreateScope("CdnWebApplicationFirewallPolicyResource.AddTag"); scope.Start(); try { var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false); originalTags.Value.Data.TagValues[key] = value; await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false); var originalResponse = await _cdnWebApplicationFirewallPolicyPoliciesRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); return Response.FromValue(new CdnWebApplicationFirewallPolicyResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Add a tag to the current resource. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName} /// Operation Id: Policies_Get /// </summary> /// <param name="key"> The key for the tag. </param> /// <param name="value"> The value for the tag. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="key"/> or <paramref name="value"/> is null. </exception> public virtual Response<CdnWebApplicationFirewallPolicyResource> AddTag(string key, string value, CancellationToken cancellationToken = default) { Argument.AssertNotNull(key, nameof(key)); Argument.AssertNotNull(value, nameof(value)); using var scope = _cdnWebApplicationFirewallPolicyPoliciesClientDiagnostics.CreateScope("CdnWebApplicationFirewallPolicyResource.AddTag"); scope.Start(); try { var originalTags = GetTagResource().Get(cancellationToken); originalTags.Value.Data.TagValues[key] = value; GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken); var originalResponse = _cdnWebApplicationFirewallPolicyPoliciesRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); return Response.FromValue(new CdnWebApplicationFirewallPolicyResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Replace the tags on the resource with the given set. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName} /// Operation Id: Policies_Get /// </summary> /// <param name="tags"> The set of tags to use as replacement. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="tags"/> is null. </exception> public virtual async Task<Response<CdnWebApplicationFirewallPolicyResource>> SetTagsAsync(IDictionary<string, string> tags, CancellationToken cancellationToken = default) { Argument.AssertNotNull(tags, nameof(tags)); using var scope = _cdnWebApplicationFirewallPolicyPoliciesClientDiagnostics.CreateScope("CdnWebApplicationFirewallPolicyResource.SetTags"); scope.Start(); try { await GetTagResource().DeleteAsync(WaitUntil.Completed, cancellationToken: cancellationToken).ConfigureAwait(false); var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false); originalTags.Value.Data.TagValues.ReplaceWith(tags); await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false); var originalResponse = await _cdnWebApplicationFirewallPolicyPoliciesRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); return Response.FromValue(new CdnWebApplicationFirewallPolicyResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Replace the tags on the resource with the given set. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName} /// Operation Id: Policies_Get /// </summary> /// <param name="tags"> The set of tags to use as replacement. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="tags"/> is null. </exception> public virtual Response<CdnWebApplicationFirewallPolicyResource> SetTags(IDictionary<string, string> tags, CancellationToken cancellationToken = default) { Argument.AssertNotNull(tags, nameof(tags)); using var scope = _cdnWebApplicationFirewallPolicyPoliciesClientDiagnostics.CreateScope("CdnWebApplicationFirewallPolicyResource.SetTags"); scope.Start(); try { GetTagResource().Delete(WaitUntil.Completed, cancellationToken: cancellationToken); var originalTags = GetTagResource().Get(cancellationToken); originalTags.Value.Data.TagValues.ReplaceWith(tags); GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken); var originalResponse = _cdnWebApplicationFirewallPolicyPoliciesRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); return Response.FromValue(new CdnWebApplicationFirewallPolicyResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Removes a tag by key from the resource. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName} /// Operation Id: Policies_Get /// </summary> /// <param name="key"> The key for the tag. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="key"/> is null. </exception> public virtual async Task<Response<CdnWebApplicationFirewallPolicyResource>> RemoveTagAsync(string key, CancellationToken cancellationToken = default) { Argument.AssertNotNull(key, nameof(key)); using var scope = _cdnWebApplicationFirewallPolicyPoliciesClientDiagnostics.CreateScope("CdnWebApplicationFirewallPolicyResource.RemoveTag"); scope.Start(); try { var originalTags = await GetTagResource().GetAsync(cancellationToken).ConfigureAwait(false); originalTags.Value.Data.TagValues.Remove(key); await GetTagResource().CreateOrUpdateAsync(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken).ConfigureAwait(false); var originalResponse = await _cdnWebApplicationFirewallPolicyPoliciesRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken).ConfigureAwait(false); return Response.FromValue(new CdnWebApplicationFirewallPolicyResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> /// Removes a tag by key from the resource. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/cdnWebApplicationFirewallPolicies/{policyName} /// Operation Id: Policies_Get /// </summary> /// <param name="key"> The key for the tag. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="key"/> is null. </exception> public virtual Response<CdnWebApplicationFirewallPolicyResource> RemoveTag(string key, CancellationToken cancellationToken = default) { Argument.AssertNotNull(key, nameof(key)); using var scope = _cdnWebApplicationFirewallPolicyPoliciesClientDiagnostics.CreateScope("CdnWebApplicationFirewallPolicyResource.RemoveTag"); scope.Start(); try { var originalTags = GetTagResource().Get(cancellationToken); originalTags.Value.Data.TagValues.Remove(key); GetTagResource().CreateOrUpdate(WaitUntil.Completed, originalTags.Value.Data, cancellationToken: cancellationToken); var originalResponse = _cdnWebApplicationFirewallPolicyPoliciesRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Name, cancellationToken); return Response.FromValue(new CdnWebApplicationFirewallPolicyResource(Client, originalResponse.Value), originalResponse.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } } }
62.889145
488
0.687048
[ "MIT" ]
damodaravadhani/azure-sdk-for-net
sdk/cdn/Azure.ResourceManager.Cdn/src/Generated/CdnWebApplicationFirewallPolicyResource.cs
27,231
C#
using System; using System.Collections.Generic; using System.Linq; using Faker.Helpers; using Faker.Selectors; namespace Faker { public enum SelectorPosition { First, Last } /// <summary> /// The repository which determines the order in which selectors are picked for any given type /// </summary> public sealed class TypeTable { //Our internal map for all types and their selectors used within Faker private readonly Dictionary<Type, LinkedList<ITypeSelector>> _typeMap; /// <summary> /// For testing purposes - exposes the underlying typemap /// </summary> internal IDictionary<Type, LinkedList<ITypeSelector>> TypeMap => _typeMap; /// <summary> /// Default constructor /// </summary> public TypeTable(bool useDefaults = true) : this(useDefaults, new Dictionary<Type, LinkedList<ITypeSelector>>()) { } /// <summary> /// Private constructor which accepts an inbound typemap as an argument /// </summary> /// <param name="useDefaults">Determines if we should load all of our default selectors or not</param> /// <param name="typeMap">A typemap instance</param> private TypeTable(bool useDefaults, Dictionary<Type, LinkedList<ITypeSelector>> typeMap) { _typeMap = typeMap; if (useDefaults) //Load defaults if the user requested it LoadDefaults(); } /// <summary> /// Private internal method for loading all of the default TypeSelectors into the TypeTable /// </summary> private void LoadDefaults() { /* NUMERIC DEFAULT SELECTORS */ AddSelector(new IntSelector()); AddSelector(new LongSelector()); AddSelector(new TimeStampSelector()); //TimeStamp selector should get used before the long selector AddSelector(new DoubleSelector()); AddSelector(new FloatSelector()); AddSelector(new DecimalSelector()); /* DATETIME SELECTORS */ AddSelector(new DateTimeSelector()); AddSelector(new DateTimeOffsetSelector()); /* STRING SELECTORS */ AddSelector(new StringSelector()); //String selector is the very last one we want to try and use AddSelector(new FirstNameSelector()); AddSelector(new LastNameSelector()); AddSelector(new FullNameSelector()); AddSelector(new EmailSelector()); /* GUID SELECTORS */ AddSelector(new GuidSelector()); } /// <summary> /// Internal method for securely creating type rows where needed /// </summary> /// <param name="incomingType">The type to which we're mapping this object</param> private void CreateTypeIfNotExists(Type incomingType) { //If we already have a collection in our dictionary that corresponds to this type, bail out if (_typeMap.ContainsKey(incomingType)) return; //Otherwise, create the row in our dictionary _typeMap.Add(incomingType, new LinkedList<ITypeSelector>()); } /// <summary> /// Add a strongly typed selector to the /// </summary> /// <param name="selector">A ITypeSelector implementation for Type T</param> /// <param name="position"> /// Optional parameter - indicates whether you want this type selector to be used first or last in /// the sequence of available selectors for this type /// </param> public void AddSelector(ITypeSelector selector, SelectorPosition position = SelectorPosition.First) { var activeType = selector.TargetType; CreateTypeIfNotExists(activeType); if (position == SelectorPosition.First) //If the user wants to add this selector to the front of the list (default), do that _typeMap[activeType].AddFirst(selector); else //Otherwise, add this type to the back of the list _typeMap[activeType].AddLast(selector); } /// <summary> /// Add a strongly typed selector to the /// </summary> /// <typeparam name="T">The type for which this selector is used</typeparam> /// <param name="selector">A TypeSelectorBase implementation for Type T</param> /// <param name="position"> /// Optional parameter - indicates whether you want this type selector to be used first or last in /// the sequence of available selectors for this type /// </param> public void AddSelector<T>(TypeSelectorBase<T> selector, SelectorPosition position = SelectorPosition.First) { AddSelector((ITypeSelector) selector, position); } /// <summary> /// Remove all of the selectors for a given type /// </summary> /// <typeparam name="T">The type for which we want to clear all of the selectors</typeparam> public void ClearSelectors<T>() { var activeType = typeof(T); if (_typeMap.ContainsKey(activeType)) //Reassign the value to a new list _typeMap[activeType] = new LinkedList<ITypeSelector>(); } /// <summary> /// Count all of the selectors for a given type /// </summary> /// <typeparam name="T">The type for which we need value selectors</typeparam> /// <returns>The number of selectors we have available for this type</returns> public int CountSelectors<T>() { var activeType = typeof(T); return CountSelectors(activeType); } /// <summary> /// Count all of the selectors for a given type /// </summary> /// <param name="t">A type object for which we want to know the number of available selectors</param> /// <returns>The number of selectors we have available for this type</returns> public int CountSelectors(Type t) { CreateTypeIfNotExists(t); return _typeMap[t].Count; } /// <summary> /// Get all of the selectors for a given type /// </summary> /// <typeparam name="T">The type for which we need value selectors</typeparam> /// <returns>An enumerable list of selectors</returns> public IEnumerable<TypeSelectorBase<T>> GetSelectors<T>() { var activeType = typeof(T); var selectors = GetSelectors(activeType); return selectors.Cast<TypeSelectorBase<T>>(); } /// <summary> /// Get all of the selectors for a given type /// </summary> /// <returns>An enumerable list of selectors</returns> public IEnumerable<ITypeSelector> GetSelectors(Type t) { CreateTypeIfNotExists(t); return _typeMap[t]; } /// <summary> /// Gets the base selector for a given datatype /// </summary> /// <param name="t">The type that we need to inject</param> /// <returns>A matching selector, null otherwise</returns> public ITypeSelector GetBaseSelector(Type t) { CreateTypeIfNotExists(t); var baseType = GenericHelper.GetGenericType(typeof(PrimitiveSelectorBase<>), t); return _typeMap[t].FirstOrDefault(x => baseType.IsAssignableFrom(x.GetType())); } /// <summary> /// Clone a deep copy of <see cref="TypeTable"/> with the same settings as this instance. /// /// Any modifications made to the new instance returned should not affect the parent instance. /// </summary> /// <returns>A deep copy of the current <see cref="TypeTable"/>.</returns> public TypeTable Clone() { // create a deep copy var newTypeMap = new Dictionary<Type, LinkedList<ITypeSelector>>(); foreach (var pair in _typeMap) { var newList = new ITypeSelector[pair.Value.Count]; pair.Value.CopyTo(newList, 0); newTypeMap.Add(pair.Key, new LinkedList<ITypeSelector>(newList)); } return new TypeTable(false, newTypeMap); } } }
40.545455
120
0.59417
[ "Apache-2.0" ]
AOA/faker-csharp
src/Faker/TypeTable.cs
8,476
C#
using UnrealBuildTool; public class DialogSystemEditor : ModuleRules { public DialogSystemEditor(ReadOnlyTargetRules Target) : base(Target) { PublicIncludePaths.AddRange( new string[] { "DialogSystemEditor/Public", } ); PrivateIncludePaths.AddRange( new string[] { "DialogSystemEditor/Private", } ); PublicDependencyModuleNames.AddRange( new string[] { "Core", "TargetPlatform", } ); PrivateDependencyModuleNames.AddRange( new string[] { "CoreUObject", "Engine", "Slate", "SlateCore", "InputCore", "UnrealEd", "PropertyEditor", "ToolMenus", "LevelEditor", "EditorStyle", "GraphEditor", "BlueprintGraph", "Projects", "ApplicationCore", "DesktopPlatform", "XmlParser", "DialogSystemRuntime", } ); } }
23.907407
73
0.410534
[ "Apache-2.0" ]
mrkriv/DialogPlugin
Source/DialogSystemEditor/DialogSystemEditor.Build.cs
1,291
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Server.Context { public class AuthorizationDbContext { } }
15
39
0.75
[ "MIT" ]
Andrewst-commits/MyMusicServer
Server/Server/Context/AuthorizationDbContext.cs
182
C#
// Copyright © 2020 EPAM Systems, Inc. All Rights Reserved. All information contained herein is, and remains the // property of EPAM Systems, Inc. and/or its suppliers and is protected by international intellectual // property law. Dissemination of this information or reproduction of this material is strictly forbidden, // unless prior written permission is obtained from EPAM Systems, Inc using System; using Epam.GraphQL.Tests.Common; using Epam.GraphQL.Tests.Common.Configs; using Epam.GraphQL.Tests.TestData; using NUnit.Framework; namespace Epam.GraphQL.Tests.Sorting { [TestFixture(PeopleQueryType.PeopleWithSearch, LoaderType.Loader, PersonLoaderConfigurationType.PersonFilterableAndSortable)] [TestFixture(PeopleQueryType.PeopleWithSearch, LoaderType.MutableLoader, PersonLoaderConfigurationType.PersonFilterableAndSortable)] [TestFixture(PeopleQueryType.PeopleWithSearch, LoaderType.IdentifiableLoader, PersonLoaderConfigurationType.PersonSortable)] [TestFixture(PeopleQueryType.PeopleWithSearch, LoaderType.MutableLoader, PersonLoaderConfigurationType.PersonSortable)] [TestFixture(PeopleQueryType.PeopleWithFilterAndSearch, LoaderType.Loader, PersonLoaderConfigurationType.PersonSortable)] [TestFixture(PeopleQueryType.PeopleWithFilterAndSearch, LoaderType.MutableLoader, PersonLoaderConfigurationType.PersonSortable)] [TestFixture(PeopleQueryType.PeopleWithFilterAndOrderedSearch, LoaderType.IdentifiableLoader, PersonLoaderConfigurationType.PersonSortable)] [TestFixture(PeopleQueryType.PeopleWithFilterAndOrderedSearch, LoaderType.MutableLoader, PersonLoaderConfigurationType.PersonSortable)] public class SortTests : BaseTests<Person, PeopleQueryConfigurator, PeopleQueryType, PersonLoaderTypeCreator, PersonLoaderConfigurator, PersonLoaderConfigurationType> { public SortTests(PeopleQueryType queryType, LoaderType loaderType, PersonLoaderConfigurationType loaderConfiguration) : base(queryType, loaderType, loaderConfiguration) { } [Test] public void ShouldSortEntitiesInNaturalOrderWithoutSorting() { TestQuery( @" query { people { items { id } } }", @" { people: { items: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }] } }"); } [Test] public void ShouldBeAbleToSortByStringField() { TestQuery( @" query { people(sorting: [{ field: ""fullName"" }]) { items { fullName } } }", @" { people: { items: [{ fullName: ""Aldon Exley"" }, { fullName: ""Florance Goodricke"" }, { fullName: ""Hannie Everitt"" }, { fullName: ""Linoel Livermore"" }, { fullName: ""Sophie Gandley"" }, { fullName: ""Walton Alvarez"" }] } }"); } [Test] public void ShouldBeAbleToSortByIntFieldAsc() { TestQuery( @" query { people(sorting: [{ field: ""id"", direction: ASC }]) { items { id } } }", @" { people: { items: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }] } }"); } [Test] public void ShouldBeAbleToSortByIntFieldAscWithContext() { TestQuery( @" query { people(sorting: [{ field: ""ctxId"", direction: ASC }]) { items { id } } }", @" { people: { items: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }] } }"); } [Test] public void ShouldBeAbleToSortByIntFieldAscDirectionAsString() { TestQuery( @" query { people(sorting: [{ field: ""id"", direction: ""asc"" }]) { items { id } } }", @" { people: { items: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }] } }"); } [Test] public void ShouldBeAbleToSortByIntFieldDesc() { TestQuery( @" query { people(sorting: [{ field: ""id"", direction: DESC }]) { items { id } } }", @" { people: { items: [{ id: 6 }, { id: 5 }, { id: 4 }, { id: 3 }, { id: 2 }, { id: 1 }] } }"); } [Test] public void ShouldBeAbleToSortByIntFieldDescDirectionAsString() { TestQuery( @" query { people(sorting: [{ field: ""id"", direction: ""desc"" }]) { items { id } } }", @" { people: { items: [{ id: 6 }, { id: 5 }, { id: 4 }, { id: 3 }, { id: 2 }, { id: 1 }] } }"); } [Test] public void ShouldBeAbleToSortByNullableIntFieldAscAndThenByStringFieldAsc() { TestQuery( @" query { people(sorting: [{ field: ""managerId"", direction: ASC }, { field: ""fullName"", direction: ASC }]) { items { managerId, fullName } } }", @" { people: { items: [{ managerId: null, fullName: ""Linoel Livermore"" }, { managerId: 1, fullName: ""Hannie Everitt"" }, { managerId: 1, fullName: ""Sophie Gandley"" }, { managerId: 2, fullName: ""Aldon Exley"" }, { managerId: 2, fullName: ""Florance Goodricke"" }, { managerId: 5, fullName: ""Walton Alvarez"" }] } }"); } [Test] public void ShouldBeAbleToSortByNullableIntFieldDescAndThenByStringFieldAsc() { TestQuery( @" query { people(sorting: [{ field: ""managerId"", direction: DESC }, { field: ""fullName"", direction: ASC }]) { items { managerId, fullName } } }", @" { people: { items: [{ managerId: 5, fullName: ""Walton Alvarez"" }, { managerId: 2, fullName: ""Aldon Exley"" }, { managerId: 2, fullName: ""Florance Goodricke"" }, { managerId: 1, fullName: ""Hannie Everitt"" }, { managerId: 1, fullName: ""Sophie Gandley"" }, { managerId: null, fullName: ""Linoel Livermore"" }] } }"); } [Test] public void ShouldBeAbleToSortByNullableIntFieldAscAndThenByStringFieldDesc() { TestQuery( @" query { people(sorting: [{ field: ""managerId"", direction: ASC }, { field: ""fullName"", direction: DESC }]) { items { managerId, fullName } } }", @" { people: { items: [{ managerId: null, fullName: ""Linoel Livermore"" }, { managerId: 1, fullName: ""Sophie Gandley"" }, { managerId: 1, fullName: ""Hannie Everitt"" }, { managerId: 2, fullName: ""Florance Goodricke"" }, { managerId: 2, fullName: ""Aldon Exley"" }, { managerId: 5, fullName: ""Walton Alvarez"" }] } }"); } [Test] public void ShouldBeAbleToSortByNullableIntFieldDescAndThenByStringFieldDesc() { TestQuery( @" query { people(sorting: [{ field: ""managerId"", direction: DESC }, { field: ""fullName"", direction: DESC }]) { items { managerId, fullName } } }", @" { people: { items: [{ managerId: 5, fullName: ""Walton Alvarez"" }, { managerId: 2, fullName: ""Florance Goodricke"" }, { managerId: 2, fullName: ""Aldon Exley"" }, { managerId: 1, fullName: ""Sophie Gandley"" }, { managerId: 1, fullName: ""Hannie Everitt"" }, { managerId: null, fullName: ""Linoel Livermore"" }] } }"); } [Test] public void ShouldBeAbleToSortByCalculatedField() { TestQuery( @" query { people(sorting: [{ field: ""roundedSalary"", direction: ASC }]) { items { id, roundedSalary } } }", @" { people: { items: [{ id: 4, roundedSalary: 549 }, { id: 3, roundedSalary: 1393 }, { id: 2, roundedSalary: 2382 }, { id: 5, roundedSalary: 3389 }, { id: 6, roundedSalary: 3437 }, { id: 1, roundedSalary: 4016 }] } }"); } [Test] public void ShouldBeAbleToSortByCustomFieldAsc() { TestQuery( @" query { people(sorting: [{ field: ""managerNameSorter"", direction: ASC }]) { items { id } } }", @" { people: { items: [{ id: 1 }, { id: 6 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }] } }"); } [Test] public void ShouldBeAbleToSortByCustomFieldDesc() { TestQuery( @" query { people(sorting: [{ field: ""managerNameSorter"", direction: DESC }]) { items { id } } }", @" { people: { items: [{ id: 4 }, { id: 5 }, { id: 2 }, { id: 3 }, { id: 6 }, { id: 1 }] } }"); } [Test] public void ShouldThrowIfSortByUnknownField() { TestQueryError( typeof(FormatException), "Failed to parse PersonFieldName from input 'unknown'. Input should be a string ('id', 'ctxId', 'managerId', 'fullName', 'roundedSalary', 'managerName', 'hireDate', 'terminationDate', 'managerNameSorter').", @" query { people(sorting: [{ field: ""unknown"" }]) { items { fullName } } }"); } [Test] public void ShouldThrowIfSortByInvalidDirection() { TestQueryError( typeof(FormatException), "Failed to parse SortDirection from input 'invalid'. Input should be a string (\"asc\", \"desc\") or enum (ASC, DESC).", @" query { people(sorting: [{ field: ""fullName"", direction: ""invalid"" }]) { items { fullName } } }"); } } }
32.45
223
0.272933
[ "MIT" ]
epam/epam-graphql
src/Tests/Epam.GraphQL.Tests/Sorting/SortTests.cs
19,471
C#
namespace GoalBasedMvc.Models { public class NetworkRecord { public int Id { get; set; } public string Name { get; set; } public string Url { get; set; } } }
19.5
40
0.569231
[ "MIT" ]
poppertech/GoalBasedMvc
GoalBasedMvc/GoalBasedMvc/Models/Network/NetworkRecord.cs
197
C#
/*<FILE_LICENSE> * NFX (.NET Framework Extension) Unistack Library * Copyright 2003-2018 Agnicore Inc. portions ITAdapter Corp. 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. </FILE_LICENSE>*/ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace NFX.Instrumentation.Analytics { /// <summary> /// Maps histogram data into some other representation (such as text, HTML, etc) /// </summary> public static class HistogramReporters { public static string ToStringReport(this IHistogram hist) { const string s_Count = "Count"; SortedList<HistogramKeys, HistogramEntry> m_Data = new SortedList<HistogramKeys, HistogramEntry>(); foreach (var entry in hist) m_Data.Add(entry.BucketKeys, entry); int[] maxDimTitleLen = new int[hist.DimensionCount]; foreach (var d in hist.Dimensions) maxDimTitleLen[d.Index] = d.Name.Length + 1; int maxTitleLen = 0; int maxValue = Convert.ToInt32(Math.Pow(10, s_Count.Length)); // Calculate max legth of partition titles in each dimension foreach (var item in m_Data) { int titleLen = 0; foreach (var d in hist.Dimensions) { int i = d.Index; int n = hist.GetPartitionName(i, item.Key[i]).Length + 1; if (n > maxDimTitleLen[i]) maxDimTitleLen[i] = n; else n = maxDimTitleLen[i]; titleLen += n; } if (titleLen > maxTitleLen) maxTitleLen = titleLen; if (item.Value.Count > maxValue) maxValue = item.Value.Count; } int maxValueLen = maxValue.ToString().Length; var result = new StringBuilder(); result.AppendFormat("{0}\n", hist.Title); foreach (var d in hist.Dimensions) result.AppendFormat("|{0}", hist.GetDimention(d.Index).Name.PadLeft(maxDimTitleLen[d.Index]-1)); result.AppendFormat("|{0}| %|Total%|\n", s_Count.PadLeft(maxValueLen)); foreach (var d in hist.Dimensions) result.AppendFormat("|{0," + (maxDimTitleLen[d.Index]-1) + "}", new String('-', maxDimTitleLen[d.Index]-1)); result.AppendFormat("|{0," + maxValueLen + "}|------|------|\n", new String('-', maxValueLen)); double tot = 0; foreach (var item in m_Data) { var title = new StringBuilder(); foreach (var d in hist.Dimensions) title.AppendFormat("|{0}", hist.GetPartitionName(d.Index, item.Key[d.Index]).PadLeft(maxDimTitleLen[d.Index]-1)); double pcnt = 100.0 * (double)item.Value.Count / hist.TotalSamples; tot += pcnt; result.AppendFormat( "{0}|{1," + maxValueLen + "}|{2,6:##0.00}|{3,6:##0.00}|\n", title.ToString().PadLeft(maxTitleLen), item.Value.Count, pcnt, tot); } return result.ToString(); } } }
37.161905
110
0.562532
[ "Apache-2.0" ]
agnicore/nfx
src/NFX/Instrumentation/Analytics/HistogramReporters.cs
3,902
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // // This source code was auto-generated by cf-sdk-builder // using CloudFoundry.CloudController.Common; using CloudFoundry.CloudController.V2.Client.Data; using Newtonsoft.Json; using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Globalization; using System.Net.Http; using System.Threading.Tasks; namespace CloudFoundry.CloudController.V2.Client { /// <summary> /// ServiceKeys Endpoint /// </summary> [GeneratedCodeAttribute("cf-sdk-builder", "1.0.0.0")] public partial class ServiceKeysEndpoint : CloudFoundry.CloudController.V2.Client.Base.AbstractServiceKeysEndpoint { internal ServiceKeysEndpoint(CloudFoundryClient client) : base() { this.Client = client; } } } namespace CloudFoundry.CloudController.V2.Client.Base { /// <summary> /// Base abstract class for ServiceKeys Endpoint /// </summary> [GeneratedCodeAttribute("cf-sdk-builder", "1.0.0.0")] public abstract class AbstractServiceKeysEndpoint : BaseEndpoint { /// <summary> /// Initializes the class /// </summary> protected AbstractServiceKeysEndpoint() { } /// <summary> /// List all Service Keys /// <para>For detailed information, see online documentation at: "http://apidocs.cloudfoundry.org/250/service_keys/list_all_service_keys.html"</para> /// </summary> public async Task<PagedResponseCollection<ListAllServiceKeysResponse>> ListAllServiceKeys() { return await ListAllServiceKeys(new RequestOptions()); } /// <summary> /// List all Service Keys /// <para>For detailed information, see online documentation at: "http://apidocs.cloudfoundry.org/250/service_keys/list_all_service_keys.html"</para> /// </summary> public async Task<PagedResponseCollection<ListAllServiceKeysResponse>> ListAllServiceKeys(RequestOptions options) { UriBuilder uriBuilder = new UriBuilder(this.Client.CloudTarget); uriBuilder.Path = "/v2/service_keys"; uriBuilder.Query = options.ToString(); var client = this.GetHttpClient(); client.Uri = uriBuilder.Uri; client.Method = HttpMethod.Get; var authHeader = await BuildAuthenticationHeader(); if (!string.IsNullOrWhiteSpace(authHeader.Key)) { client.Headers.Add(authHeader); } var expectedReturnStatus = 200; var response = await this.SendAsync(client, expectedReturnStatus); return Utilities.DeserializePage<ListAllServiceKeysResponse>(await response.ReadContentAsStringAsync(), this.Client); } /// <summary> /// Create a Service Key /// <para>For detailed information, see online documentation at: "http://apidocs.cloudfoundry.org/250/service_keys/create_a_service_key.html"</para> /// </summary> public async Task<CreateServiceKeyResponse> CreateServiceKey(CreateServiceKeyRequest value) { UriBuilder uriBuilder = new UriBuilder(this.Client.CloudTarget); uriBuilder.Path = "/v2/service_keys"; var client = this.GetHttpClient(); client.Uri = uriBuilder.Uri; client.Method = HttpMethod.Post; var authHeader = await BuildAuthenticationHeader(); if (!string.IsNullOrWhiteSpace(authHeader.Key)) { client.Headers.Add(authHeader); } client.ContentType = "application/x-www-form-urlencoded"; client.Content = ((string)JsonConvert.SerializeObject(value)).ConvertToStream(); var expectedReturnStatus = 201; var response = await this.SendAsync(client, expectedReturnStatus); return Utilities.DeserializeJson<CreateServiceKeyResponse>(await response.ReadContentAsStringAsync()); } /// <summary> /// Retrieve a Particular Service Key /// <para>For detailed information, see online documentation at: "http://apidocs.cloudfoundry.org/250/service_keys/retrieve_a_particular_service_key.html"</para> /// </summary> public async Task<RetrieveServiceKeyResponse> RetrieveServiceKey(Guid? guid) { UriBuilder uriBuilder = new UriBuilder(this.Client.CloudTarget); uriBuilder.Path = string.Format(CultureInfo.InvariantCulture, "/v2/service_keys/{0}", guid); var client = this.GetHttpClient(); client.Uri = uriBuilder.Uri; client.Method = HttpMethod.Get; var authHeader = await BuildAuthenticationHeader(); if (!string.IsNullOrWhiteSpace(authHeader.Key)) { client.Headers.Add(authHeader); } var expectedReturnStatus = 200; var response = await this.SendAsync(client, expectedReturnStatus); return Utilities.DeserializeJson<RetrieveServiceKeyResponse>(await response.ReadContentAsStringAsync()); } /// <summary> /// Delete a Particular Service Key /// <para>For detailed information, see online documentation at: "http://apidocs.cloudfoundry.org/250/service_keys/delete_a_particular_service_key.html"</para> /// </summary> public async Task DeleteServiceKey(Guid? guid) { UriBuilder uriBuilder = new UriBuilder(this.Client.CloudTarget); uriBuilder.Path = string.Format(CultureInfo.InvariantCulture, "/v2/service_keys/{0}", guid); var client = this.GetHttpClient(); client.Uri = uriBuilder.Uri; client.Method = HttpMethod.Delete; var authHeader = await BuildAuthenticationHeader(); if (!string.IsNullOrWhiteSpace(authHeader.Key)) { client.Headers.Add(authHeader); } client.ContentType = "application/x-www-form-urlencoded"; var expectedReturnStatus = 204; var response = await this.SendAsync(client, expectedReturnStatus); } } }
43.172185
169
0.632766
[ "Apache-2.0" ]
cloudfoundry-attic/cf-dotnet-sdk
src/CloudFoundry.CloudController.V2.Client/Generated/ServiceKeys.cs
6,519
C#
using System.Numerics; using AzureStorage; using AzureStorage.Tables; using Common.Log; using Lykke.AzureStorage.Tables; using Lykke.AzureStorage.Tables.Entity.Metamodel; using Lykke.AzureStorage.Tables.Entity.Metamodel.Providers; using Lykke.Service.EthereumClassicApi.Common.Settings; using Lykke.Service.EthereumClassicApi.Repositories.Entities; using Lykke.Service.EthereumClassicApi.Repositories.Factories.Interfaces; using Lykke.Service.EthereumClassicApi.Repositories.Interfaces; using Lykke.Service.EthereumClassicApi.Repositories.Serializers; using Lykke.SettingsReader; namespace Lykke.Service.EthereumClassicApi.Repositories.Factories { public class RepositoryFactory : IRepositoryFactory { private const string DynamicSettingsTable = "DynamicSettings"; private const string ObservableBalanceTable = "ObservableBalances"; private const string TransactionTable = "Transactions"; private readonly IReloadingManager<string> _connectionString; private readonly ILog _log; public RepositoryFactory( ILog log, IReloadingManager<DbSettings> settings) { _log = log; _connectionString = settings.ConnectionString(x => x.DataConnectionString); var provider = new CompositeMetamodelProvider() .AddProvider ( new AnnotationsBasedMetamodelProvider() ) .AddProvider ( new ConventionBasedMetamodelProvider() .AddTypeSerializerRule ( t => t == typeof(BigInteger), s => new BigIntegerSerializer() ) ); EntityMetamodel.Configure(provider); } private INoSQLTableStorage<T> CreateTable<T>(string tableName) where T : AzureTableEntity, new() { return AzureTableStorage<T>.Create(_connectionString, tableName, _log); } public IGasPriceRepository BuildGasPriceRepository() { var table = CreateTable<GasPriceEntity>(DynamicSettingsTable); return new GasPriceRepository(table); } public IObservableBalanceRepository BuildObservableBalanceRepository() { var table = CreateTable<ObservableBalanceEntity>(ObservableBalanceTable); return new ObservableBalanceRepository(table); } public ITransactionRepository BuildTransactionRepository() { var table = CreateTable<TransactionEntity>(TransactionTable); return new TransactionRepository(table); } } }
34.209877
87
0.646698
[ "MIT" ]
LykkeCity/Lykke.Service.EthereumClassic.Api
src/Lykke.Service.EthereumClassicApi.Repositories/Factories/RepositoryFactory.cs
2,773
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text.Json.Serialization; using System.Threading.Tasks; namespace JwtAuthDemo.Data { public class User { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int ID { get; set; } public string Username { get; set; } [JsonIgnore] public byte[] PasswordHash { get; set; } [JsonIgnore] public byte[] PasswordSalt { get; set; } public int OCID { get; set; } public int LevelOC { get; set; } public string EmployeeID { get; set; } public string Email { get; set; } public int RoleID { get; set; } public string ImageURL { get; set; } public string AccessTokenLineNotify { get; set; } public byte[] ImageBase64 { get; set; } public bool isLeader { get; set; } public bool IsShow { get; set; } public int DeleteBy { get; set; } public DateTime ModifyTime { get; set; } public Role Role { get; set; } public virtual ICollection<UserSystem> UserSystems { get; set; } } }
33.810811
72
0.632294
[ "MIT" ]
henryphamshc/api-auth-dmr
webapi/JwtAuthDemo/Data/User.cs
1,253
C#
//------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the 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.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using System.Threading; using Microsoft.IdentityModel.TestUtils; using Xunit; #pragma warning disable CS3016 // Arrays as attribute arguments is not CLS-compliant namespace Microsoft.IdentityModel.Protocols.Tests { /// <summary> /// /// </summary> public class HttpDocumentRetrieverTests { [Fact] public void Constructors() { HttpDocumentRetriever docRetriever = new HttpDocumentRetriever(); Assert.Throws<ArgumentNullException>(() => new HttpDocumentRetriever(null)); } [Fact] public void Defaults() { } [Fact] public void GetSets() { HttpDocumentRetriever docRetriever = new HttpDocumentRetriever(); Type type = typeof(HttpDocumentRetriever); PropertyInfo[] properties = type.GetProperties(); if (properties.Length != 1) Assert.True(true, "Number of properties has changed from 1 to: " + properties.Length + ", adjust tests"); GetSetContext context = new GetSetContext { PropertyNamesAndSetGetValue = new List<KeyValuePair<string, List<object>>> { new KeyValuePair<string, List<object>>("RequireHttps", new List<object>{true, false, true}), }, Object = docRetriever, }; TestUtilities.GetSet(context); TestUtilities.AssertFailIfErrors("HttpDocumentRetrieverTests_GetSets", context.Errors); } [Theory, MemberData(nameof(GetMetadataTheoryData))] public void GetMetadataTest(DocumentRetrieverTheoryData theoryData) { var context = TestUtilities.WriteHeader($"{this}.GetMetadataTest", theoryData); try { string doc = theoryData.DocumentRetriever.GetDocumentAsync(theoryData.Address, CancellationToken.None).Result; Assert.NotNull(doc); theoryData.ExpectedException.ProcessNoException(); } catch (AggregateException aex) { aex.Handle((x) => { if (x.Data.Count > 0) { if (!x.Data.Contains(HttpDocumentRetriever.StatusCode)) context.AddDiff("!x.Data.Contains(HttpResponseConstants.StatusCode)"); if (!x.Data.Contains(HttpDocumentRetriever.ResponseContent)) context.AddDiff("!x.Data.Contains(HttpResponseConstants.ResponseContent)"); IdentityComparer.AreEqual(x.Data[HttpDocumentRetriever.StatusCode], theoryData.ExpectedStatusCode, context); } theoryData.ExpectedException.ProcessException(x); return true; }); } TestUtilities.AssertFailIfErrors(context); } public static TheoryData<DocumentRetrieverTheoryData> GetMetadataTheoryData { get { var theoryData = new TheoryData<DocumentRetrieverTheoryData>(); var documentRetriever = new HttpDocumentRetriever(); theoryData.Add(new DocumentRetrieverTheoryData { Address = null, DocumentRetriever = documentRetriever, ExpectedException = ExpectedException.ArgumentNullException(), First = true, TestId = "Address NULL" }); theoryData.Add(new DocumentRetrieverTheoryData { Address = "OpenIdConnectMetadata.json", DocumentRetriever = documentRetriever, ExpectedException = new ExpectedException(typeof(ArgumentException), "IDX20108:"), TestId = "Require https, using file: 'OpenIdConnectMetadata.json'" }); theoryData.Add(new DocumentRetrieverTheoryData { Address = "httpss://OpenIdConnectMetadata.json", DocumentRetriever = documentRetriever, ExpectedException = new ExpectedException(typeof(ArgumentException), "IDX20108:"), TestId = "Require https, Address: 'httpss://OpenIdConnectMetadata.json'" }); theoryData.Add(new DocumentRetrieverTheoryData { Address = "https://login.microsoftonline.com/common/.well-known/openid-configuration", DocumentRetriever = documentRetriever, TestId = "AAD common: https" }); theoryData.Add(new DocumentRetrieverTheoryData { Address = "HTTPS://login.microsoftonline.com/common/.well-known/openid-configuration", DocumentRetriever = documentRetriever, TestId = "AAD common: HTTPS" }); documentRetriever = new HttpDocumentRetriever() { RequireHttps = false }; theoryData.Add(new DocumentRetrieverTheoryData { Address = "OpenIdConnectMetadata.json", DocumentRetriever = documentRetriever, ExpectedException = new ExpectedException(typeof(IOException), "IDX20804:", typeof(InvalidOperationException)), TestId = "RequireHttps == false, Address: 'OpenIdConnectMetadata.json'" }); theoryData.Add(new DocumentRetrieverTheoryData { Address = "https://login.microsoftonline.com/common/FederationMetadata/2007-06/FederationMetadata.xml", DocumentRetriever = documentRetriever, TestId = "AAD common: WsFed" }); theoryData.Add(new DocumentRetrieverTheoryData { Address = "https://login.windows.net/f686d426-8d16-42db-81b7-ab578e110ccd/.well-known/openid-configuration", DocumentRetriever = documentRetriever, ExpectedException = new ExpectedException(typeof(IOException), "IDX20807:"), ExpectedStatusCode = HttpStatusCode.BadRequest, TestId = "Client Miss Configuration" }); theoryData.Add(new DocumentRetrieverTheoryData { Address = "https://login.windows.net/f686d426-8d16-42db-81b7-ab578e110ccd/.well-known/openid-configuration", DocumentRetriever = new HttpDocumentRetriever(HttpResponseMessageUtils.SetupHttpClientThatReturns("ValidJson.json", HttpStatusCode.RequestTimeout)), TestId = "RequestTimeout_RefreshSucceeds" }); theoryData.Add(new DocumentRetrieverTheoryData { Address = "https://login.windows.net/f686d426-8d16-42db-81b7-ab578e110ccd/.well-known/openid-configuration", DocumentRetriever = new HttpDocumentRetriever(HttpResponseMessageUtils.SetupHttpClientThatReturns("ValidJson.json", HttpStatusCode.ServiceUnavailable)), TestId = "ServiceUnavailable_RefreshSucceeds" }); theoryData.Add(new DocumentRetrieverTheoryData { Address = "https://login.windows.net/f686d426-8d16-42db-81b7-ab578e110ccd/.well-known/openid-configuration", DocumentRetriever = new HttpDocumentRetriever(HttpResponseMessageUtils.SetupHttpClientThatReturns("ValidJson.json", HttpStatusCode.ServiceUnavailable)), TestId = "ServiceUnavailable_RefreshSucceeds" }); theoryData.Add(new DocumentRetrieverTheoryData { Address = "https://login.windows.net/f686d426-8d16-42db-81b7-ab578e110ccd/.well-known/openid-configuration", DocumentRetriever = new HttpDocumentRetriever(HttpResponseMessageUtils.SetupHttpClientThatReturns("ValidJson.json", HttpStatusCode.NotFound)), ExpectedException = new ExpectedException(typeof(IOException), "IDX20807:"), ExpectedStatusCode = HttpStatusCode.NotFound, TestId = "NotFound_NoRefresh" }); return theoryData; } } } public class DocumentRetrieverTheoryData : TheoryDataBase { public string Address { get; set; } public IDocumentRetriever DocumentRetriever { get; set; } public HttpStatusCode ExpectedStatusCode { get; set; } public override string ToString() { return $"{TestId}, {Address}, {ExpectedException}"; } } } #pragma warning restore CS3016 // Arrays as attribute arguments is not CLS-compliant
45.051502
172
0.595885
[ "MIT" ]
AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet
test/Microsoft.IdentityModel.Protocols.Tests/HttpDocumentRetrieverTests.cs
10,497
C#
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Natasha.Log; using Natasha.Log.Model; using System; using System.Collections.Generic; using System.Text; namespace System { public class NErrorLog : ALogWrite { public static bool Enabled; static NErrorLog() => Enabled = true; public Dictionary<string, List<Diagnostic>> Errors; public NErrorLog() { Errors = new Dictionary<string, List<Diagnostic>>(); } public override void Write() { NWriter<NErrorLog>.Recoder(Buffer); } public void Handler(CSharpCompilation compilation, List<Diagnostic> diagnostics) { Buffer.AppendLine($"\r\n\r\n========================Error : {compilation.AssemblyName}========================\r\n"); List<string> others = new List<string>(); foreach (var item in diagnostics) { if (item.Location == Location.None) { others.Add(item.ToString()); } else { string str = item.Location.SourceTree!.ToString(); if (!Errors.ContainsKey(str)) { Errors[str] = new List<Diagnostic>(); } Errors[str].Add(item); } } foreach (var item in Errors) { Buffer.AppendLine(); Buffer.Append(AddLineNumber(item.Key)); Buffer.AppendLine("\r\n\r\n-----------------------------------------------error---------------------------------------------------"); Buffer.AppendLine($"\r\n Time :\t{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}"); Buffer.AppendLine($"\r\n Lauguage :\t{compilation.Language} & {compilation.LanguageVersion}"); Buffer.AppendLine($"\r\n Target :\t{compilation.AssemblyName}"); Buffer.AppendLine($"\r\n Error :\t共{item.Value.Count}处错误!"); foreach (var error in item.Value) { var temp = error.Location.GetLineSpan().StartLinePosition; var result = GetErrorString(item.Key, error.Location.GetLineSpan()); Buffer.AppendLine($"\t\t第{temp.Line + 1}行,第{temp.Character}个字符: 内容【{result}】 {error.GetMessage()}"); } if (others.Count>0) { Buffer.AppendLine("\r\n-----------------------------------------------其他信息-----------------------------------------------"); foreach (var message in others) { Buffer.AppendLine($"\r\n Message :\t{message}"); } } Buffer.AppendLine("\r\n====================================================================\r\n"); } } public void Handler(List<Diagnostic> diagnostics) { string formartCode = diagnostics[0].Location.SourceTree!.ToString(); Buffer.AppendLine($"\r\n\r\n========================Error : 语法错误 ========================\r\n"); Buffer.AppendLine(); Buffer.Append(AddLineNumber(formartCode)); Buffer.AppendLine("\r\n\r\n-----------------------------------------------error---------------------------------------------------"); Buffer.AppendLine($"\r\n Time :\t\t{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}"); Buffer.AppendLine($"\r\n Error:\t\t共{diagnostics.Count}处错误!"); foreach (var error in diagnostics) { var temp = error.Location.GetLineSpan().StartLinePosition; var result = GetErrorString(formartCode, error.Location.GetLineSpan()); Buffer.AppendLine($"\t\t第{temp.Line + 1}行,第{temp.Character}个字符: 内容【{result}】 {error.GetMessage()}"); } Buffer.AppendLine("\r\n====================================================================\r\n"); } internal string GetErrorString(string content, FileLinePositionSpan linePositionSpan) { var start = linePositionSpan.StartLinePosition; var end = linePositionSpan.EndLinePosition; var arrayLines = content.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); var currentErrorLine = arrayLines[start.Line]; if (start.Line == end.Line) { if (start.Character == end.Character) { return currentErrorLine.Substring(0, currentErrorLine.Length).Trim(); } else { return currentErrorLine.Substring(startIndex: start.Character, end.Character - start.Character).Trim(); } } else { StringBuilder builder = new StringBuilder(); currentErrorLine.Substring(start.Character); builder.AppendLine(currentErrorLine); for (int i = start.Line; i < end.Line - 1; i += 1) { builder.AppendLine("\t\t\t" + arrayLines[i]); } currentErrorLine = arrayLines[end.Line]; currentErrorLine = currentErrorLine.Substring(0, end.Character); builder.AppendLine(currentErrorLine); return builder.ToString(); } } } }
30.446809
149
0.461915
[ "MIT" ]
hellomrsun/Natasha
src/Natasha.CSharp/Natasha.CSharp.Engine/NLog/NErrorLog.cs
5,810
C#
// Copyright (c) Jeremy W. Kuhne. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Drawing; using WInterop.Gdi; namespace WInterop.Windows { public static partial class Message { public readonly ref struct WindowPositionChanged { public WindowHandle InsertAfter { get; } public WindowHandle Handle { get; } public Rectangle Bounds { get; } public Rectangle ClientBounds { get; } public unsafe WindowPositionChanged(LParam lParam) { WindowPosition* position = (WindowPosition*)lParam; InsertAfter = position->InsertAfter; Handle = position->Handle; Rectangle bounds = new Rectangle(position->X, position->Y, position->Width, position->Height); Handle.ScreenToClient(ref bounds); Bounds = bounds; ClientBounds = Handle.GetClientRectangle(); } } } }
35.633333
110
0.609916
[ "MIT" ]
JeremyKuhne/WInterop
src/WInterop.Desktop/Windows/Messages/Message.WindowPositionChanged.cs
1,071
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using com.rfilkov.kinect; namespace com.rfilkov.components { /// <summary> /// SceneBlendRenderer provides volumetric rendering and lighting of the real environment, as seen by the sensor's color camera. /// </summary> public class SceneBlendRenderer : MonoBehaviour { [Tooltip("Added depth distance between the real environment and the virtual environment, in meters.")] [Range(-0.5f, 0.5f)] public float depthDistance = 0.1f; [Tooltip("Index of the depth sensor that generates the color camera background. 0 is the 1st one, 1 - the 2nd one, etc.")] public int sensorIndex = 0; [Tooltip("Depth value in meters, used for invalid depth points.")] public float invalidDepthValue = 5f; [Tooltip("Whether to maximize the rendered object on the screen, or not.")] private bool maximizeOnScreen = true; [Tooltip("Whether to apply per-pixel lighting on the foreground, or not.")] public bool applyLighting = false; [Tooltip("Camera used to scale the mesh, to fill the camera's background. If left empty, it will default to the main camera in the scene.")] public Camera foregroundCamera; [Tooltip("Background image (if any) that needs to be overlayed by this blend renderer.")] public UnityEngine.UI.RawImage backgroundImage; [Tooltip("Reference to a background removal manager, if one is available in the scene.")] public BackgroundRemovalManager backgroundRemovalManager = null; // references to KM and data private KinectManager kinectManager = null; private KinectInterop.SensorData sensorData = null; private Material matRenderer = null; // depth image buffer (in depth camera resolution) private ComputeBuffer depthImageBuffer = null; // textures private Texture alphaTex = null; private Texture colorTex = null; // lighting private FragmentLighting lighting = new FragmentLighting(); // saved screen width & height private int lastScreenW = 0; private int lastScreenH = 0; private int lastColorW = 0; private int lastColorH = 0; private float lastAnchorPos = 0f; private Vector3 initialScale = Vector3.one; // distances private float distToBackImage = 0f; private float distToTransform = 0f; void Start() { kinectManager = KinectManager.Instance; initialScale = transform.localScale; // get distance to back image if (backgroundImage) { Canvas canvas = backgroundImage.canvas; if (canvas.renderMode == RenderMode.ScreenSpaceCamera) distToBackImage = canvas.planeDistance; else distToBackImage = 0f; } // get distance to transform distToTransform = transform.localPosition.z; // set renderer material Renderer meshRenderer = GetComponent<Renderer>(); if (meshRenderer) { Shader blendShader = Shader.Find("Kinect/ForegroundBlendShader"); if (blendShader != null) { matRenderer = new Material(blendShader); meshRenderer.material = matRenderer; } } // get sensor data if (kinectManager && kinectManager.IsInitialized()) { sensorData = kinectManager.GetSensorData(sensorIndex); } if(foregroundCamera == null) { foregroundCamera = Camera.main; } // find scene lights Light[] sceneLights = GameObject.FindObjectsOfType<Light>(); lighting.SetLightsAndBounds(sceneLights, transform.position, new Vector3(20f, 20f, 20f)); } void OnDestroy() { if (sensorData != null && sensorData.colorDepthBuffer != null) { sensorData.colorDepthBuffer.Release(); sensorData.colorDepthBuffer = null; } if (depthImageBuffer != null) { //depthImageCopy = null; depthImageBuffer.Release(); depthImageBuffer = null; } // release lighting resources lighting.ReleaseResources(); } void Update() { if (matRenderer == null || sensorData == null) return; if(alphaTex == null || alphaTex.width != sensorData.colorImageWidth || alphaTex.height != sensorData.colorImageHeight) { // alpha texture alphaTex = backgroundRemovalManager != null ? backgroundRemovalManager.GetAlphaTex() : null; if (alphaTex != null) { matRenderer.SetTexture("_AlphaTex", alphaTex); } } if(colorTex == null || colorTex.width != sensorData.colorImageWidth || colorTex.height != sensorData.colorImageHeight) { // color texture colorTex = sensorData.colorImageTexture; if(backgroundRemovalManager != null) { colorTex = !backgroundRemovalManager.computeAlphaMaskOnly ? backgroundRemovalManager.GetForegroundTex() : alphaTex; } if (colorTex != null) { matRenderer.SetInt("_TexResX", colorTex.width); matRenderer.SetInt("_TexResY", colorTex.height); matRenderer.SetTexture("_ColorTex", colorTex); } } if (colorTex == null) return; int bufferLength = sensorData.colorImageWidth * sensorData.colorImageHeight / 2; if (sensorData.colorDepthBuffer == null || sensorData.colorDepthBuffer.count != bufferLength) { sensorData.colorDepthBuffer = new ComputeBuffer(bufferLength, sizeof(uint)); matRenderer.SetBuffer("_DepthMap", sensorData.colorDepthBuffer); //Debug.Log("Created colorDepthBuffer with len: " + bufferLength); } matRenderer.SetFloat("_DepthDistance", depthDistance); matRenderer.SetFloat("_InvDepthVal", invalidDepthValue); int curScreenW = foregroundCamera ? foregroundCamera.pixelWidth : Screen.width; int curScreenH = foregroundCamera ? foregroundCamera.pixelHeight : Screen.height; if (lastScreenW != curScreenW || lastScreenH != curScreenH || lastColorW != sensorData.colorImageWidth || lastColorH != sensorData.colorImageHeight) { ScaleRendererTransform(curScreenW, curScreenH); } Vector2 anchorPos = backgroundImage ? backgroundImage.rectTransform.anchoredPosition : Vector2.zero; float curAnchorPos = anchorPos.x + anchorPos.y; // Mathf.Abs(anchorPos.x) + Mathf.Abs(anchorPos.y); if (Mathf.Abs(curAnchorPos - lastAnchorPos) >= 20f) { //Debug.Log("anchorPos: " + anchorPos + ", curAnchorPos: " + curAnchorPos + ", lastAnchorPos: " + lastAnchorPos + ", diff: " + Mathf.Abs(curAnchorPos - lastAnchorPos)); CenterRendererTransform(anchorPos, curAnchorPos); } // update lighting parameters lighting.UpdateLighting(matRenderer, applyLighting); } // scales the renderer's transform properly private void ScaleRendererTransform(int curScreenW, int curScreenH) { lastScreenW = curScreenW; lastScreenH = curScreenH; lastColorW = sensorData.colorImageWidth; lastColorH = sensorData.colorImageHeight; Vector3 localScale = transform.localScale; if (maximizeOnScreen && foregroundCamera) { float objectZ = distToTransform; // transform.localPosition.z; // the transform should be a child of the camera float screenW = foregroundCamera.pixelWidth; float screenH = foregroundCamera.pixelHeight; if (backgroundImage) { PortraitBackground portraitBack = backgroundImage.gameObject.GetComponent<PortraitBackground>(); if (portraitBack != null) { Rect backRect = portraitBack.GetBackgroundRect(); screenW = backRect.width; screenH = backRect.height; } } Vector3 vLeft = foregroundCamera.ScreenToWorldPoint(new Vector3(0f, screenH / 2f, objectZ)); Vector3 vRight = foregroundCamera.ScreenToWorldPoint(new Vector3(screenW, screenH / 2f, objectZ)); float distLeftRight = (vRight - vLeft).magnitude; Vector3 vBottom = foregroundCamera.ScreenToWorldPoint(new Vector3(screenW / 2f, 0f, objectZ)); Vector3 vTop = foregroundCamera.ScreenToWorldPoint(new Vector3(screenW / 2f, screenH, objectZ)); float distBottomTop = (vTop - vBottom).magnitude; localScale.x = distLeftRight / initialScale.x; localScale.y = distBottomTop / initialScale.y; //Debug.Log("SceneRenderer scale: " + localScale + ", screenW: " + screenW + ", screenH: " + screenH + ", objZ: " + objectZ + // "\nleft: " + vLeft + ", right: " + vRight + ", bottom: " + vBottom + ", vTop: " + vTop + // "\ndH: " + distLeftRight + ", dV: " + distBottomTop + ", initialScale: " + initialScale); } // scale according to color-tex resolution //localScale.y = localScale.x * colorTex.height / colorTex.width; // apply color image scale Vector3 colorImageScale = kinectManager.GetColorImageScale(sensorIndex); if (colorImageScale.x < 0f) localScale.x = -localScale.x; if (colorImageScale.y < 0f) localScale.y = -localScale.y; transform.localScale = localScale; } // centers the renderer's transform, according to the background image private void CenterRendererTransform(Vector2 anchorPos, float curAnchorPos) { lastAnchorPos = curAnchorPos; if (foregroundCamera && distToBackImage > 0f) { float objectZ = distToTransform; // transform.localPosition.z; // the transform should be a child of the camera float screenW = sensorData.colorImageWidth; // foregroundCamera.pixelWidth; float screenH = sensorData.colorImageHeight; // foregroundCamera.pixelHeight; Vector2 screenCenter = new Vector2(screenW / 2f, screenH / 2f); Vector2 anchorScaled = new Vector2(anchorPos.x * distToTransform / distToBackImage, anchorPos.y * distToTransform / distToBackImage); Vector3 vCenter = foregroundCamera.ScreenToWorldPoint(new Vector3(screenCenter.x + anchorScaled.x, screenCenter.y + anchorScaled.y, objectZ)); transform.position = vCenter; //Vector3 vLocalPos = transform.localPosition; //string sLocalPos = string.Format("({0:F3}, {1:F3}, {2:F3})", vLocalPos.x, vLocalPos.y, vLocalPos.z); //Debug.Log("SceneRenderer anchor: " + anchorPos + ", screenW: " + screenW + ", screenH: " + screenH + ", objZ: " + objectZ + ", localPos: " + sLocalPos); } } } }
41.883803
184
0.589575
[ "MIT" ]
mmuu1987/ChangLongKinect
Assets/AzureKinectExamples/KinectScripts/SceneBlendRenderer.cs
11,897
C#
/* C# "SophisticatedSearcher.cs" by Jeremy Love <mailto:jez@jezlove.uk> copyright 2020 */ using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.IO.Compression; using System.Text.RegularExpressions; using System.Xml; using System.Xml.XPath; using ReSearcher.Epub; namespace ReSearcher { public class SophisticatedSearcher : AbstractMultiFormatSearcher { private readonly XPathExpression xpath; public SophisticatedSearcher(Regex regex, XPathExpression xpath, String filter = Filters.any) : base(regex, filter) { this.xpath = xpath; } #region searching-epub-documents protected override EpubEntrySearchResults searchEpubEntry(String entryName, Stream stream) { XmlDocument xmlDocument = SgmlDocuments.readHtmlAsXmlDocument(stream); // EPUB uses XHTML not HTML, but let's be forgiving if(null == xmlDocument) { Console.Error.WriteLine("Error: could not parse: {0}", entryName); return(null); } // TODO: switch to using XPathNavigator IEnumerable<Tuple<XmlNode, MatchCollection>> xmlNodeMatchCollections = xmlDocument.SelectNodes(xpath.Expression).matchWithinAll(regex); if(xmlNodeMatchCollections.isNullOrEmpty()) { return(null); } XmlNode titleXmlNode = xmlDocument.SelectSingleNode(".//title"); String entryTitle = (null == titleXmlNode) ? null : titleXmlNode.InnerText.Trim(); return(new EpubEntrySearchResults(entryName, entryTitle, xmlNodeMatchCollections.Select(t => new XmlNodeSearchResults(t.Item1.Name, new RegexSearchResultMatchCollection(t.Item2))))); } #endregion } }
29.438596
187
0.727652
[ "MIT" ]
jezlove/ReSearcher
SophisticatedSearcher.cs
1,678
C#
using System; public class SetTankVector : Message { private const int PAYLOAD_SIZE = 4; private short leftSpeed; private short rightSpeed; public SetTankVector() : base() { this.SetCommandCode(CommandCode.SET_TANT_VECTOR); } public SetTankVector(Message message) : base(message) { this.SetCommandCode(CommandCode.SET_TANT_VECTOR); } protected override void InitData() { base.InitData(); } protected override bool setPayloadFromJausBuffer(byte[] data, int index) { if (!base.setPayloadFromJausBuffer(data, index)) { Console.Error.WriteLine("Command Code Failed"); return false; } if (data.Length != PAYLOAD_SIZE) { Console.Error.WriteLine("Payload is incorrect size"); return false; } byte[] leftDataArray = new byte[sizeof(short)]; byte[] rightDataArray = new byte[sizeof(short)]; for (int i = 0; i < leftDataArray.Length; i++) { leftDataArray[i] = data[i]; } for (int i = 0; i < rightDataArray.Length; i++) { rightDataArray[i] = data[i + leftDataArray.Length]; } if (BitConverter.IsLittleEndian) { Array.Reverse(leftDataArray); Array.Reverse(rightDataArray); } this.leftSpeed = BitConverter.ToInt16(leftDataArray, 0); this.rightSpeed = BitConverter.ToInt16(rightDataArray, 0); return true; } protected override bool payloadToJausBuffer(byte[] data, int index) { if (!base.payloadToJausBuffer(data, index)) { Console.Error.WriteLine("Command Code Failed"); return false; } if (data.Length != PAYLOAD_SIZE) { Console.Error.WriteLine("Buffer is incorrect size, can't put payloadToJausBuffer"); return false; } BitConverter.GetBytes(this.leftSpeed).CopyTo(data, 0); BitConverter.GetBytes(this.rightSpeed).CopyTo(data, sizeof(short)); return true; } public override int GetPayloadSize() { return PAYLOAD_SIZE; } }
27.578313
96
0.570992
[ "BSD-3-Clause" ]
WisconsinRobotics/BadgerJAUS.NET
BadgerJaus/messages/localvectordriver/SetTankVector.cs
2,291
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801 { using Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.PowerShell; /// <summary>BackupRequest resource specific properties</summary> [System.ComponentModel.TypeConverter(typeof(BackupRequestPropertiesTypeConverter))] public partial class BackupRequestProperties { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.BackupRequestProperties" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal BackupRequestProperties(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupSchedule = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupSchedule) content.GetValueForProperty("BackupSchedule",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupSchedule, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.BackupScheduleTypeConverter.ConvertFrom); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupName = (string) content.GetValueForProperty("BackupName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupName, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).Enabled = (bool?) content.GetValueForProperty("Enabled",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).Enabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).StorageAccountUrl = (string) content.GetValueForProperty("StorageAccountUrl",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).StorageAccountUrl, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).Database = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDatabaseBackupSetting[]) content.GetValueForProperty("Database",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).Database, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDatabaseBackupSetting>(__y, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.DatabaseBackupSettingTypeConverter.ConvertFrom)); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleFrequencyUnit = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.FrequencyUnit) content.GetValueForProperty("BackupScheduleFrequencyUnit",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleFrequencyUnit, Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.FrequencyUnit.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleStartTime = (global::System.DateTime?) content.GetValueForProperty("BackupScheduleStartTime",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleFrequencyInterval = (int) content.GetValueForProperty("BackupScheduleFrequencyInterval",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleFrequencyInterval, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleKeepAtLeastOneBackup = (bool) content.GetValueForProperty("BackupScheduleKeepAtLeastOneBackup",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleKeepAtLeastOneBackup, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleRetentionPeriodInDay = (int) content.GetValueForProperty("BackupScheduleRetentionPeriodInDay",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleRetentionPeriodInDay, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleLastExecutionTime = (global::System.DateTime?) content.GetValueForProperty("BackupScheduleLastExecutionTime",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleLastExecutionTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.BackupRequestProperties" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal BackupRequestProperties(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupSchedule = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupSchedule) content.GetValueForProperty("BackupSchedule",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupSchedule, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.BackupScheduleTypeConverter.ConvertFrom); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupName = (string) content.GetValueForProperty("BackupName",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupName, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).Enabled = (bool?) content.GetValueForProperty("Enabled",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).Enabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).StorageAccountUrl = (string) content.GetValueForProperty("StorageAccountUrl",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).StorageAccountUrl, global::System.Convert.ToString); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).Database = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDatabaseBackupSetting[]) content.GetValueForProperty("Database",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).Database, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IDatabaseBackupSetting>(__y, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.DatabaseBackupSettingTypeConverter.ConvertFrom)); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleFrequencyUnit = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.FrequencyUnit) content.GetValueForProperty("BackupScheduleFrequencyUnit",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleFrequencyUnit, Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.FrequencyUnit.CreateFrom); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleStartTime = (global::System.DateTime?) content.GetValueForProperty("BackupScheduleStartTime",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleStartTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleFrequencyInterval = (int) content.GetValueForProperty("BackupScheduleFrequencyInterval",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleFrequencyInterval, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleKeepAtLeastOneBackup = (bool) content.GetValueForProperty("BackupScheduleKeepAtLeastOneBackup",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleKeepAtLeastOneBackup, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleRetentionPeriodInDay = (int) content.GetValueForProperty("BackupScheduleRetentionPeriodInDay",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleRetentionPeriodInDay, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); ((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleLastExecutionTime = (global::System.DateTime?) content.GetValueForProperty("BackupScheduleLastExecutionTime",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestPropertiesInternal)this).BackupScheduleLastExecutionTime, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); AfterDeserializePSObject(content); } /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.BackupRequestProperties" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestProperties" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new BackupRequestProperties(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.BackupRequestProperties" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestProperties" />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new BackupRequestProperties(content); } /// <summary> /// Creates a new instance of <see cref="BackupRequestProperties" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IBackupRequestProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// BackupRequest resource specific properties [System.ComponentModel.TypeConverter(typeof(BackupRequestPropertiesTypeConverter))] public partial interface IBackupRequestProperties { } }
116.211921
625
0.769603
[ "MIT" ]
3quanfeng/azure-powershell
src/Functions/generated/api/Models/Api20190801/BackupRequestProperties.PowerShell.cs
17,398
C#
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; using riddle_crud_application.Models; namespace riddle_crud_application.Data { public class ApplicationDbContext : IdentityDbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<riddle_crud_application.Models.Riddle> Riddle { get; set; } } }
27.736842
83
0.749526
[ "MIT" ]
Branbados/riddle-crud-application
Data/ApplicationDbContext.cs
529
C#
namespace Microsoft.AspNetCore.Mvc.ApiExplorer { using Microsoft.AspNet.OData; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.DotNet.PlatformAbstractions; using Microsoft.OData.Edm; using System; using System.Collections.Generic; using System.Diagnostics.Contracts; sealed class PseudoModelBindingVisitor { internal PseudoModelBindingVisitor( ApiParameterContext context, ParameterDescriptor parameter ) { Contract.Requires( context != null ); Contract.Requires( parameter != null ); Context = context; Parameter = parameter; } internal ApiParameterContext Context { get; } internal ParameterDescriptor Parameter { get; } private HashSet<PropertyKey> Visited { get; } = new HashSet<PropertyKey>( new PropertyKeyEqualityComparer() ); internal void WalkParameter( ApiParameterDescriptionContext context ) => Visit( context, BindingSource.ModelBinding, containerName: string.Empty ); private static string GetName( string containerName, ApiParameterDescriptionContext metadata ) { if ( string.IsNullOrEmpty( metadata.BinderModelName ) ) { return ModelNames.CreatePropertyModelName( containerName, metadata.PropertyName ); } return metadata.BinderModelName; } private void Visit( ApiParameterDescriptionContext bindingContext, BindingSource ambientSource, string containerName ) { var source = bindingContext.BindingSource; if ( source != null && source.IsGreedy ) { Context.Results.Add( CreateResult( bindingContext, source, containerName ) ); return; } var modelMetadata = bindingContext.ModelMetadata; if ( modelMetadata.IsEnumerableType || !modelMetadata.IsComplexType || modelMetadata.Properties.Count == 0 ) { Context.Results.Add( CreateResult( bindingContext, source ?? ambientSource, containerName ) ); return; } var newContainerName = containerName; if ( modelMetadata.ContainerType != null ) { newContainerName = GetName( containerName, bindingContext ); } for ( var i = 0; i < modelMetadata.Properties.Count; i++ ) { var propertyMetadata = modelMetadata.Properties[i]; var key = new PropertyKey( propertyMetadata, source ); var propertyContext = new ApiParameterDescriptionContext( propertyMetadata, bindingInfo: null, propertyName: null ); if ( Visited.Add( key ) ) { Visit( propertyContext, source ?? ambientSource, newContainerName ); } else { Context.Results.Add( CreateResult( propertyContext, source ?? ambientSource, newContainerName ) ); } } } ApiParameterDescription CreateResult( ApiParameterDescriptionContext bindingContext, BindingSource source, string containerName ) { var type = bindingContext.ModelMetadata.ModelType; if ( type.IsODataActionParameters() && Context.RouteContext.Operation?.IsAction() == true ) { var action = (IEdmAction) Context.RouteContext.Operation; var apiVersion = Context.RouteContext.ApiVersion; type = Context.TypeBuilder.NewActionParameters( action, apiVersion ); } else { type = type.SubstituteIfNecessary( Context.Services, Context.Assemblies, Context.TypeBuilder ); } return new ApiParameterDescription() { ModelMetadata = bindingContext.ModelMetadata, Name = GetName( containerName, bindingContext ), Source = source, Type = type, ParameterDescriptor = Parameter, }; } struct PropertyKey { public readonly Type ContainerType; public readonly string PropertyName; public readonly BindingSource Source; public PropertyKey( ModelMetadata metadata, BindingSource source ) { ContainerType = metadata.ContainerType; PropertyName = metadata.PropertyName; Source = source; } } sealed class PropertyKeyEqualityComparer : IEqualityComparer<PropertyKey> { public bool Equals( PropertyKey x, PropertyKey y ) => x.ContainerType == y.ContainerType && x.PropertyName == y.PropertyName && x.Source == y.Source; public int GetHashCode( PropertyKey obj ) { var hashCodeCombiner = HashCodeCombiner.Start(); hashCodeCombiner.Add( obj.ContainerType ); hashCodeCombiner.Add( obj.PropertyName ); hashCodeCombiner.Add( obj.Source ); return hashCodeCombiner.CombinedHash; } } } }
38.268116
161
0.60178
[ "MIT" ]
AzureMentor/aspnet-api-versioning
src/Microsoft.AspNetCore.OData.Versioning.ApiExplorer/AspNetCore.Mvc.ApiExplorer/PseudoModelBindingVisitor.cs
5,283
C#
namespace TeamLegend.Web.Areas.Administration.Models.League { using Common; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; public class LeagueCreateInputModel { private const string LeagueNameDisplay = "Name"; private const string LeagueCountryDisplay = "Country"; private const string LeagueParticipatingTeamsDisplay = "Participating Teams"; private const string LeagueNameErrorMessage = "League name length must be in range {2}-{1}."; private const string LeagueCountryErrorMessage = "Country name length must be in range {2}-{1}."; [Required] [Display(Name = LeagueNameDisplay)] [StringLength(ValidationConstants.LeagueNameMaxLength, MinimumLength = ValidationConstants.LeagueNameMinLength, ErrorMessage = LeagueNameErrorMessage)] public string Name { get; set; } [Required] [Display(Name = LeagueCountryDisplay)] [StringLength(ValidationConstants.LeagueCountryMaxLength, MinimumLength = ValidationConstants.LeagueCountryMinLength, ErrorMessage = LeagueCountryErrorMessage)] public string Country { get; set; } [Display(Name = LeagueParticipatingTeamsDisplay)] public List<string> ParticipatingTeams { get; set; } } }
42.064516
168
0.72546
[ "MIT" ]
alexdimitrov2000/AspNetCore_PersonalProject
TeamLegend/TeamLegend.Web/Areas/Administration/Models/Leagues/LeagueCreateInputModel.cs
1,306
C#
//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ using NMF.Collections.Generic; using NMF.Collections.ObjectModel; using NMF.Expressions; using NMF.Expressions.Linq; using NMF.Models; using NMF.Models.Collections; using NMF.Models.Expressions; using NMF.Models.Meta; using NMF.Models.Repository; using NMF.Serialization; using NMF.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Linq; using TTC2017.SmartGrids.CIM; using TTC2017.SmartGrids.CIM.IEC61968.Assets; using TTC2017.SmartGrids.CIM.IEC61968.Common; using TTC2017.SmartGrids.CIM.IEC61970.Core; using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfCommon; using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfERPSupport; using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfWork; namespace TTC2017.SmartGrids.CIM.IEC61970.Informative.InfLocations { /// <summary> /// The public interface for OrgPropertyRole /// </summary> [DefaultImplementationTypeAttribute(typeof(OrgPropertyRole))] [XmlDefaultImplementationTypeAttribute(typeof(OrgPropertyRole))] public interface IOrgPropertyRole : IModelElement, IRole { /// <summary> /// The ErpOrganisation property /// </summary> IErpOrganisation ErpOrganisation { get; set; } /// <summary> /// The LandProperty property /// </summary> IOrderedSetExpression<ILandProperty> LandProperty { get; } /// <summary> /// Gets fired before the ErpOrganisation property changes its value /// </summary> event System.EventHandler<ValueChangedEventArgs> ErpOrganisationChanging; /// <summary> /// Gets fired when the ErpOrganisation property changed its value /// </summary> event System.EventHandler<ValueChangedEventArgs> ErpOrganisationChanged; } }
31.282051
96
0.654918
[ "MIT" ]
georghinkel/ttc2017smartGrids
generator/Schema/IEC61970/Informative/InfLocations/IOrgPropertyRole.cs
2,442
C#
using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Linq; using TestMyCode.CSharp.Core.Data; using TestMyCode.CSharp.Core.Test; using Xunit; namespace TestMyCode.CSharp.Tests.Passed { public class TestPassed { private Assembly Assembly = Assembly.Load("TestAssembly"); private TestProjectData TestProjectData = new TestProjectData(); private ProjectTestRunner testRunner; public TestPassed() { this.TestProjectData.LoadAssembly(this.Assembly); testRunner = new ProjectTestRunner(TestProjectData); testRunner.RunAssemblyTests(Assembly); } [Theory] [InlineData(typeof(TestAssembly.TestPassed), nameof(TestAssembly.TestPassed.TestThatAlwaysPasses), true)] [InlineData(typeof(TestAssembly.TestPassed), nameof(TestAssembly.TestPassed.TestThatAlwaysFails), false)] public void MethodResultsCorrectPassed(Type methodClass, string methodName, bool expect) { bool passed = testRunner.TestResults.FirstOrDefault(result => result.Name == $"{methodClass.FullName}.{methodName}").Passed; Assert.Equal(passed, expect); } [Theory] [InlineData(typeof(TestAssembly.TestPassed), "TestThatAlwaysPasses", true)] [InlineData(typeof(TestAssembly.TestPassed), "TestThatAlwaysFails", true)] [InlineData(typeof(TestAssembly.TestPassed), "TestThatDoesNotExist", false)] public void MethodWithGivenNameCanBeFound(Type methodClass, string methodName, bool expect) { MethodTestResult found = testRunner.TestResults.FirstOrDefault(result => result.Name == $"{methodClass.FullName}.{methodName}"); Assert.Equal(found != null, expect); } [Theory] [InlineData(typeof(TestAssembly.TestPassed), nameof(TestAssembly.TestPassed.TestThatAlwaysFails), true)] [InlineData(typeof(TestAssembly.TestPassed), nameof(TestAssembly.TestPassed.TestThatAlwaysPasses), false)] public void ErrorStackTraceCanBeFoundAfterFailing(Type methodClass, string methodName, bool expect) { IList<string> stackTrace = testRunner.TestResults.FirstOrDefault(result => result.Name == $"{methodClass.FullName}.{methodName}").ErrorStackTrace; Assert.Equal(stackTrace.Count > 0, expect); } [Theory] [InlineData(typeof(TestAssembly.TestPassed), nameof(TestAssembly.TestPassed.TestThatAlwaysFails), true)] [InlineData(typeof(TestAssembly.TestPassed), nameof(TestAssembly.TestPassed.TestThatAlwaysPasses), false)] public void MessageCanBeFoundAfterFailing(Type methodClass, string methodName, bool expect) { string message = testRunner.TestResults.FirstOrDefault(result => result.Name == $"{methodClass.FullName}.{methodName}").Message; Assert.Equal(message != "", expect); } } }
44.238806
158
0.703104
[ "MIT" ]
TMC-CSharp/tmc-csharp-runner
Tests/Points/TestPassed.cs
2,964
C#
using System; using System.Collections.Generic; namespace P01_BillsPaymentSystem.Data.Models { public class CreditCard { public CreditCard() { } public CreditCard(decimal limit, decimal moneyOwned, DateTime expirationDate) { this.Limit = limit; this.MoneyOwned = moneyOwned; this.ExpirationDate = expirationDate; } public int CreditCardId { get; set; } private decimal limit; public decimal Limit { get => this.limit; private set { this.limit = value; } } private decimal moneyOwned; public decimal MoneyOwned { get => this. moneyOwned; private set { this.moneyOwned = value; } } public decimal LimitLeft => Limit - MoneyOwned; public DateTime ExpirationDate { get; set; } public int PaymentId { get; set; } public PaymentMethod PaymentMethod { get; set; } public void Deposit(decimal amount) { if (amount <= 0) { throw new Exception("Deposit should be at least 0.01"); } this.MoneyOwned += amount; if (this.MoneyOwned > this.Limit) { this.Limit = MoneyOwned; } } public void Withdraw(decimal amount) { if (amount <= 0) { throw new Exception("Withdraw should be at least 0.01"); } this.MoneyOwned = Math.Max(this.MoneyOwned - amount, 0); } } }
23.704225
85
0.505645
[ "MIT" ]
Shtereva/CSharp-DB-Fundamentals---Entity-Framework
Advanced Relations/P01_BillsPaymentSystem.Data.Models/CreditCard.cs
1,685
C#
using PandaSharp.Bamboo.Services.Plan.Contract; namespace PandaSharp.Bamboo.Services.Plan.Factory { public interface IPlanRequestBuilderFactory { IGetAllPlansRequest GetAllPlans(); IGetInformationOfPlanRequest GetInformationOf(string projectKey, string planKey); IGetBranchesOfPlanRequest GetBranchesOf(string projectKey, string planKey); IGetArtifactsOfPlanRequest GetArtifactsOf(string projectKey, string planKey); IGetLabelsOfPlanRequest GetLabelsOf(string projectKey, string planKey); IGetVcsBranchesOfPlanRequest GetVcsBranchesOf(string projectKey, string planKey); IAddLabelToPlanCommand AddLabelToPlan(string projectKey, string planKey, string labelName); IDeleteLabelOfPlanCommand DeleteLabelOfPlan(string projectKey, string planKey, string labelName); IEnableDisablePlanCommand EnablePlan(string projectKey, string planKey); IEnableDisablePlanCommand DisablePlan(string projectKey, string planKey); IDeletePlanCommand DeletePlan(string projectKey, string planKey); ICreatePlanCommand CreateBranch(string projectKey, string planKey, string branchName); IFavouritePlanCommand FavouritePlan(string projectKey, string planKey); IFavouritePlanCommand UnfavouritePlan(string projectKey, string planKey); } }
37.5
105
0.782222
[ "MIT" ]
soerendd/PandaSharp
PandaSharp.Bamboo/Services/Plan/Factory/IPlanRequestBuilderFactory.cs
1,352
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210 { using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions; /// <summary>The target VM tags.</summary> public partial class InMageAzureV2UpdateReplicationProtectedItemInputTargetVMTags : Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IInMageAzureV2UpdateReplicationProtectedItemInputTargetVMTags, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IInMageAzureV2UpdateReplicationProtectedItemInputTargetVMTagsInternal { /// <summary> /// Creates an new <see cref="InMageAzureV2UpdateReplicationProtectedItemInputTargetVMTags" /> instance. /// </summary> public InMageAzureV2UpdateReplicationProtectedItemInputTargetVMTags() { } } /// The target VM tags. public partial interface IInMageAzureV2UpdateReplicationProtectedItemInputTargetVMTags : Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IJsonSerializable, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IAssociativeArray<string> { } /// The target VM tags. internal partial interface IInMageAzureV2UpdateReplicationProtectedItemInputTargetVMTagsInternal { } }
43.594595
140
0.753875
[ "MIT" ]
Agazoth/azure-powershell
src/Migrate/generated/api/Models/Api20210210/InMageAzureV2UpdateReplicationProtectedItemInputTargetVMTags.cs
1,577
C#
// *** WARNING: this file was generated by pulumigen. *** // *** 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.Kubernetes.Storage.V1Beta1 { /// <summary> /// VolumeAttachmentList is a collection of VolumeAttachment objects. /// </summary> public partial class VolumeAttachmentList : KubernetesResource { /// <summary> /// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources /// </summary> [Output("apiVersion")] public Output<string> ApiVersion { get; private set; } = null!; /// <summary> /// Items is the list of VolumeAttachments /// </summary> [Output("items")] public Output<ImmutableArray<Pulumi.Kubernetes.Types.Outputs.Storage.V1Beta1.VolumeAttachment>> Items { get; private set; } = null!; /// <summary> /// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds /// </summary> [Output("kind")] public Output<string> Kind { get; private set; } = null!; /// <summary> /// Standard list metadata More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata /// </summary> [Output("metadata")] public Output<Pulumi.Kubernetes.Types.Outputs.Meta.V1.ListMeta> Metadata { get; private set; } = null!; /// <summary> /// Create a VolumeAttachmentList resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public VolumeAttachmentList(string name, Pulumi.Kubernetes.Types.Inputs.Storage.V1Beta1.VolumeAttachmentListArgs? args = null, CustomResourceOptions? options = null) : base("kubernetes:storage.k8s.io/v1beta1:VolumeAttachmentList", name, MakeArgs(args), MakeResourceOptions(options, "")) { } internal VolumeAttachmentList(string name, ImmutableDictionary<string, object?> dictionary, CustomResourceOptions? options = null) : base("kubernetes:storage.k8s.io/v1beta1:VolumeAttachmentList", name, new DictionaryResourceArgs(dictionary), MakeResourceOptions(options, "")) { } private VolumeAttachmentList(string name, Input<string> id, CustomResourceOptions? options = null) : base("kubernetes:storage.k8s.io/v1beta1:VolumeAttachmentList", name, null, MakeResourceOptions(options, id)) { } private static Pulumi.Kubernetes.Types.Inputs.Storage.V1Beta1.VolumeAttachmentListArgs? MakeArgs(Pulumi.Kubernetes.Types.Inputs.Storage.V1Beta1.VolumeAttachmentListArgs? args) { args ??= new Pulumi.Kubernetes.Types.Inputs.Storage.V1Beta1.VolumeAttachmentListArgs(); args.ApiVersion = "storage.k8s.io/v1beta1"; args.Kind = "VolumeAttachmentList"; return args; } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing VolumeAttachmentList resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static VolumeAttachmentList Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new VolumeAttachmentList(name, id, options); } } } namespace Pulumi.Kubernetes.Types.Inputs.Storage.V1Beta1 { public class VolumeAttachmentListArgs : Pulumi.ResourceArgs { /// <summary> /// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources /// </summary> [Input("apiVersion")] public Input<string>? ApiVersion { get; set; } [Input("items", required: true)] private InputList<Pulumi.Kubernetes.Types.Inputs.Storage.V1Beta1.VolumeAttachmentArgs>? _items; /// <summary> /// Items is the list of VolumeAttachments /// </summary> public InputList<Pulumi.Kubernetes.Types.Inputs.Storage.V1Beta1.VolumeAttachmentArgs> Items { get => _items ?? (_items = new InputList<Pulumi.Kubernetes.Types.Inputs.Storage.V1Beta1.VolumeAttachmentArgs>()); set => _items = value; } /// <summary> /// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds /// </summary> [Input("kind")] public Input<string>? Kind { get; set; } /// <summary> /// Standard list metadata More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata /// </summary> [Input("metadata")] public Input<Pulumi.Kubernetes.Types.Inputs.Meta.V1.ListMetaArgs>? Metadata { get; set; } public VolumeAttachmentListArgs() { } } }
50.316176
302
0.670174
[ "Apache-2.0" ]
hazsetata/pulumi-kubernetes
sdk/dotnet/Storage/V1Beta1/VolumeAttachmentList.cs
6,843
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using RestServer1.DAL.Enum; using RestServer1.DAL.Model; using RestServer1.Core.Abstract; using log4net; namespace RestServer1.API.Controllers { [Route("api/[controller]")] [ApiController] public class LogsController : ControllerBase { private static readonly NotImplementedException notImplementedException = new NotImplementedException("This REST method is not implemented."); private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private readonly IEventLogger logger; public LogsController(IEventLogger loggerInstance) { log.Info("Logs controller created."); this.logger = loggerInstance; } //---------------------------------------------------------- // RESTful //---------------------------------------------------------- // GET api/logs [HttpGet] public async Task<IEnumerable<LoggerEvent>> Get() { return await this.logger.GetAllEventsAsync(); } // GET api/logs/1b45c80f-21f6-4569-8500-636efd1e0c02 [HttpGet("{id:guid}")] public async Task<LoggerEvent> Get(string id) { var guid = Guid.Parse(id); return await this.logger.GetEventAsync(guid); } // POST api/values [HttpPost] public async Task<LoggerEvent> Post([FromBody] LoggerEvent value) { return await this.logger.AddEventAsync(value); } /* // PUT api/values/1b45c80f-21f6-4569-8500-636efd1e0c02 [HttpPut("{id}")] public Task<LoggerEvent> Put(string id, [FromBody] string value) { } */ /* // DELETE api/values/1b45c80f-21f6-4569-8500-636efd1e0c02 [HttpDelete("{id}")] public Task<LoggerEvent> Delete(string id) { } */ //---------------------------------------------------------- // SEARCH //---------------------------------------------------------- // GET api/logs/search/2 // GET api/logs/search/2018-10-17T16:21 // GET api/logs/search/2018-10-17T16:21/2 // GET api/logs/search/2018-10-17T16:21/2018-10-17T16:24 // GET api/logs/search/2018-10-17T16:21/2018-10-17T16:24/2 [HttpGet("search/{level:int}")] [HttpGet("search/{start:datetime}/{level:int?}")] [HttpGet("search/{start:datetime}/{end:datetime}/{level:int?}")] public async Task<IEnumerable<LoggerEvent>> SearchGet(string start, string end, string level) { DateTime? startUtc = null; if (!string.IsNullOrEmpty(start)) startUtc = DateTime.Parse(start); DateTime? endUtc = null; if (!string.IsNullOrEmpty(end)) endUtc = DateTime.Parse(end); LoggerEventLevel? logLevel = null; if (!string.IsNullOrEmpty(level)) logLevel = Enum.Parse<LoggerEventLevel>(level); return await this.logger.GetEventsAsync(startUtc, endUtc, logLevel); } //---------------------------------------------------------- // ADMIN //---------------------------------------------------------- // GET api/admin/flush [HttpGet("admin/flush")] public async Task<IEnumerable<LoggerEvent>> AdminFlush() { await this.logger.FlushAsync(); return await this.logger.GetAllEventsAsync(); } // GET api/admin/seed [HttpGet("admin/seed")] public async Task<IEnumerable<LoggerEvent>> AdminSeed() { await this.logger.SeedAsync(); return await this.logger.GetAllEventsAsync(); } // GET api/admin/reset [HttpGet("admin/reseed")] public async Task<IEnumerable<LoggerEvent>> AdminReset() { await this.logger.ReseedAsync(); return await this.logger.GetAllEventsAsync(); } } }
33.579365
150
0.538171
[ "MIT" ]
patricebeaujolin/RestServer1
API/Controllers/LogsController.cs
4,233
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Tests")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("6d09f9d4-8b58-4bfc-bd58-16a66adc2625")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.378378
84
0.742589
[ "BSD-3-Clause" ]
Microsoft/libyara.NET
Tests/Properties/AssemblyInfo.cs
1,386
C#
// // Klak - Utilities for creative coding with Unity // // Copyright (C) 2016 Keijiro Takahashi // // 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. // // Suppress "unused variable" warning messages. #pragma warning disable 0414 using UnityEngine; using UnityEngine.Events; using System; namespace Klak.Wiring { // Attribute for marking inlets [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)] public class InletAttribute : Attribute { public InletAttribute() {} } // Attribute for marking outlets [AttributeUsage(AttributeTargets.Field)] public class OutletAttribute : Attribute { public OutletAttribute() {} } // Base class of wiring node classes public class NodeBase : MonoBehaviour { [SerializeField, HideInInspector] Vector2 _wiringNodePosition = uninitializedNodePosition; [Serializable] public class VoidEvent : UnityEvent {} [Serializable] public class FloatEvent : UnityEvent<float> {} [Serializable] public class Vector3Event : UnityEvent<Vector3> {} [Serializable] public class QuaternionEvent : UnityEvent<Quaternion> {} [Serializable] public class ColorEvent : UnityEvent<Color> {} static public Vector2 uninitializedNodePosition { get { return new Vector2(-1000, -1000); } } } }
33.027027
80
0.711538
[ "MIT" ]
Adjuvant/videolab
Assets/Klak/Wiring/System/NodeBase.cs
2,444
C#
using System; using System.Linq; using System.Web; using System.Web.UI; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Owin; using RentACar.Models; namespace RentACar.Account { public partial class Register : Page { protected void CreateUser_Click(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>(); var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text }; IdentityResult result = manager.Create(user, Password.Text); if (result.Succeeded) { // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771 //string code = manager.GenerateEmailConfirmationToken(user.Id); //string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request); //manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>."); signInManager.SignIn( user, isPersistent: false, rememberBrowser: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { ErrorMessage.Text = result.Errors.FirstOrDefault(); } } } }
43.472222
156
0.649201
[ "MIT" ]
haithemChkel/ASP.Net_Training
RentACar/RentACar/Account/Register.aspx.cs
1,567
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("EA.Weee.Email")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EA.Weee.Email")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("d0f0fe44-d1f8-4473-a679-c295a189aa0d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.75
84
0.739514
[ "Unlicense" ]
DEFRA/prsd-weee
src/EA.Weee.Email/Properties/AssemblyInfo.cs
1,362
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.269 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace System.Web.WebPages.Deployment.Resources { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class ConfigurationResources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal ConfigurationResources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("System.Web.WebPages.Deployment.Resources.ConfigurationResources", typeof(ConfigurationResources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to The &quot;InstallPath&quot; name was not found in the Web Pages registry key &quot;{0}&quot;.. /// </summary> internal static string InstallPathNotFound { get { return ResourceManager.GetString("InstallPathNotFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not determine which version of ASP.NET Web Pages to use. /// ///In order to use this site, specify a version in the site’s web.config file. For more information, see the following article on the Microsoft support site: http://go.microsoft.com/fwlink/?LinkId=254126. /// </summary> internal static string WebPagesImplicitVersionFailure { get { return ResourceManager.GetString("WebPagesImplicitVersionFailure", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The Web Pages registry key &quot;{0}&quot; does not exist.. /// </summary> internal static string WebPagesRegistryKeyDoesNotExist { get { return ResourceManager.GetString("WebPagesRegistryKeyDoesNotExist", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Changes were detected in the Web Pages runtime version that require your application to be recompiled. Refresh your browser window to continue.. /// </summary> internal static string WebPagesVersionChanges { get { return ResourceManager.GetString("WebPagesVersionChanges", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Conflicting versions of ASP.NET Web Pages detected: specified version is &quot;{0}&quot;, but the version in bin is &quot;{1}&quot;. To continue, remove files from the application&apos;s bin directory or remove the version specification in web.config.. /// </summary> internal static string WebPagesVersionConflict { get { return ResourceManager.GetString("WebPagesVersionConflict", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Specified Web Pages version &quot;{0}&quot; could not be found. Update your web.config to specify a different version. Current version: &quot;{1}&quot;.. /// </summary> internal static string WebPagesVersionNotFound { get { return ResourceManager.GetString("WebPagesVersionNotFound", resourceCulture); } } } }
47.383333
305
0.619592
[ "Apache-2.0" ]
1508553303/AspNetWebStack
src/System.Web.WebPages.Deployment/Resources/ConfigurationResources.Designer.cs
5,690
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GlueItem : MonoBehaviour { public void UseGlue() { InventoryManager.UseGlue(transform.parent); } }
17.75
51
0.723005
[ "Unlicense" ]
zelakus/GGJ2020
Repair/Assets/Scripts/User Interface/GlueItem.cs
215
C#
using System; namespace HMPPS.ErrorReporting { public interface ILogManager { void LogInfo(string message, Type sourceType); void LogAudit(string message, Type sourceType); void LogDebug(string message, Type sourceType); void LogWarning(string message, Type sourceType); void LogError(string message, Type sourceType); void LogError(string message, Exception ex, Type sourceType); } }
29.733333
69
0.697309
[ "MIT" ]
glenjamin/hmpps-hub
src/HMPPS.Monitoring/HMPPS.ErrorReporting/ILogManager.cs
446
C#
namespace Hss.Web.Tests { using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Testing; using Xunit; public class WebTests : IClassFixture<WebApplicationFactory<Startup>> { private readonly WebApplicationFactory<Startup> server; public WebTests(WebApplicationFactory<Startup> server) { this.server = server; } [Fact(Skip = "Example test. Disabled for CI.")] public async Task IndexPageShouldReturnStatusCode200WithTitle() { var client = this.server.CreateClient(); var response = await client.GetAsync("/"); response.EnsureSuccessStatusCode(); var responseContent = await response.Content.ReadAsStringAsync(); Assert.Contains("<title>", responseContent); } [Fact(Skip = "Example test. Disabled for CI.")] public async Task AccountManagePageRequiresAuthorization() { var client = this.server.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); var response = await client.GetAsync("Identity/Account/Manage"); Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); } } }
33.447368
120
0.648308
[ "MIT" ]
ivan-nikolov/HSS
Src/Tests/Hss.Web.Tests/WebTests.cs
1,273
C#
namespace Masa.Contrib.Ddd.Domain.Repository.EF.Tests.Infrastructure; public class CustomDbContext : DbContext { public DbSet<Orders> Orders { get; set; } public DbSet<Students> Students { get; set; } public DbSet<Courses> Courses { get; set; } public DbSet<Hobbies> Hobbies { get; set; } public CustomDbContext(DbContextOptions<CustomDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Students>( entityTypeBuilder => { entityTypeBuilder.HasKey("SerialNumber"); }); } }
26.916667
89
0.660991
[ "MIT" ]
capdiem/MASA.Contrib
test/Masa.Contrib.Ddd.Domain.Repository.EF.Tests/Infrastructure/CustomDbContext.cs
646
C#
public class MapType { public const string DUSTLAND = "map_dust_land"; public const string SWAMP = "map_swamp"; }
24.4
49
0.713115
[ "MIT" ]
GraySchofield/SavageEraNew
Assets/Scirpts/Model/Map/MapType.cs
124
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using Google.Protobuf; using Microsoft.Data.DataView; using Microsoft.ML.Data; using Microsoft.ML.Model.OnnxConverter; using Microsoft.ML.RunTests; using Microsoft.ML.TestFramework.Attributes; using Microsoft.ML.Tools; using Microsoft.ML.Trainers; using Microsoft.ML.Transforms; using Newtonsoft.Json; using Xunit; using Xunit.Abstractions; using static Microsoft.ML.Model.OnnxConverter.OnnxCSharpToProtoWrapper; namespace Microsoft.ML.Tests { public class OnnxConversionTest : BaseTestBaseline { private class AdultData { [LoadColumn(0, 10), ColumnName("FeatureVector")] public float Features { get; set; } [LoadColumn(11)] public float Target { get; set; } } public OnnxConversionTest(ITestOutputHelper output) : base(output) { } /// <summary> /// In this test, we convert a trained <see cref="TransformerChain"/> into ONNX <see cref="ModelProto"/> file and then /// call <see cref="OnnxScoringEstimator"/> to evaluate that file. The outputs of <see cref="OnnxScoringEstimator"/> are checked against the original /// ML.NET model's outputs. /// </summary> [Fact] public void SimpleEndToEndOnnxConversionTest() { // Step 1: Create and train a ML.NET pipeline. var trainDataPath = GetDataPath(TestDatasets.generatedRegressionDataset.trainFilename); var mlContext = new MLContext(seed: 1, conc: 1); var data = mlContext.Data.LoadFromTextFile<AdultData>(trainDataPath, separatorChar: ';' , hasHeader: true); var cachedTrainData = mlContext.Data.Cache(data); var dynamicPipeline = mlContext.Transforms.Normalize("FeatureVector") .AppendCacheCheckpoint(mlContext) .Append(mlContext.Regression.Trainers.StochasticDualCoordinateAscent(labelColumnName: "Target", featureColumnName: "FeatureVector")); var model = dynamicPipeline.Fit(data); var transformedData = model.Transform(data); // Step 2: Convert ML.NET model to ONNX format and save it as a file. var onnxModel = mlContext.Model.ConvertToOnnxProtobuf(model, data); var onnxFileName = "model.onnx"; var onnxModelPath = GetOutputPath(onnxFileName); SaveOnnxModel(onnxModel, onnxModelPath, null); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && Environment.Is64BitProcess) { // Step 3: Evaluate the saved ONNX model using the data used to train the ML.NET pipeline. string[] inputNames = onnxModel.Graph.Input.Select(valueInfoProto => valueInfoProto.Name).ToArray(); string[] outputNames = onnxModel.Graph.Output.Select(valueInfoProto => valueInfoProto.Name).ToArray(); var onnxEstimator = mlContext.Transforms.ApplyOnnxModel(onnxModelPath, outputNames, inputNames); var onnxTransformer = onnxEstimator.Fit(data); var onnxResult = onnxTransformer.Transform(data); // Step 4: Compare ONNX and ML.NET results. CompareSelectedR4ScalarColumns("Score", "Score0", transformedData, onnxResult, 1); } // Step 5: Check ONNX model's text format. This test will be not necessary if Step 3 and Step 4 can run on Linux and // Mac to support cross-platform tests. var subDir = Path.Combine("..", "..", "BaselineOutput", "Common", "Onnx", "Regression", "Adult"); var onnxTextName = "SimplePipeline.txt"; var onnxTextPath = GetOutputPath(subDir, onnxTextName); SaveOnnxModel(onnxModel, null, onnxTextPath); CheckEquality(subDir, onnxTextName, digitsOfPrecision: 3); Done(); } private class BreastCancerFeatureVector { [LoadColumn(1, 9), VectorType(9)] public float[] Features; } private class BreastCancerCatFeatureExample { [LoadColumn(0)] public bool Label; [LoadColumn(1)] public float F1; [LoadColumn(2)] public string F2; } private class BreastCancerMulticlassExample { [LoadColumn(1)] public string Label; [LoadColumn(2, 9), VectorType(8)] public float[] Features; } [LessThanNetCore30OrNotNetCoreFact("netcoreapp3.0 output differs from Baseline. Tracked by https://github.com/dotnet/machinelearning/issues/2087")] public void KmeansOnnxConversionTest() { // Create a new context for ML.NET operations. It can be used for exception tracking and logging, // as a catalog of available operations and as the source of randomness. var mlContext = new MLContext(seed: 1, conc: 1); string dataPath = GetDataPath("breast-cancer.txt"); // Now read the file (remember though, readers are lazy, so the actual reading will happen when the data is accessed). var data = mlContext.Data.LoadFromTextFile<BreastCancerFeatureVector>(dataPath, separatorChar: '\t', hasHeader: true); var pipeline = mlContext.Transforms.Normalize("Features"). Append(mlContext.Clustering.Trainers.KMeans(new Trainers.KMeansPlusPlusTrainer.Options { FeatureColumnName = DefaultColumnNames.Features, MaxIterations = 1, ClustersCount = 4, NumThreads = 1, InitAlgorithm = Trainers.KMeansPlusPlusTrainer.InitAlgorithm.Random })); var model = pipeline.Fit(data); var transformedData = model.Transform(data); var onnxModel = mlContext.Model.ConvertToOnnxProtobuf(model, data); // Compare results produced by ML.NET and ONNX's runtime. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && Environment.Is64BitProcess) { var onnxFileName = "model.onnx"; var onnxModelPath = GetOutputPath(onnxFileName); SaveOnnxModel(onnxModel, onnxModelPath, null); // Evaluate the saved ONNX model using the data used to train the ML.NET pipeline. string[] inputNames = onnxModel.Graph.Input.Select(valueInfoProto => valueInfoProto.Name).ToArray(); string[] outputNames = onnxModel.Graph.Output.Select(valueInfoProto => valueInfoProto.Name).ToArray(); var onnxEstimator = mlContext.Transforms.ApplyOnnxModel(onnxModelPath, outputNames, inputNames); var onnxTransformer = onnxEstimator.Fit(data); var onnxResult = onnxTransformer.Transform(data); CompareSelectedR4VectorColumns("Score", "Score0", transformedData, onnxResult, 3); } // Check ONNX model's text format. We save the produced ONNX model as a text file and compare it against // the associated file in ML.NET repo. Such a comparison can be retired if ONNXRuntime ported to ML.NET // can support Linux and Mac. var subDir = Path.Combine("..", "..", "BaselineOutput", "Common", "Onnx", "Cluster", "BreastCancer"); var onnxTextName = "Kmeans.txt"; var onnxTextPath = GetOutputPath(subDir, onnxTextName); SaveOnnxModel(onnxModel, null, onnxTextPath); CheckEquality(subDir, onnxTextName, digitsOfPrecision: 2); Done(); } [Fact] void CommandLineOnnxConversionTest() { string dataPath = GetDataPath("breast-cancer.txt"); string modelPath = GetOutputPath("ModelWithLessIO.zip"); var trainingPathArgs = $"data={dataPath} out={modelPath}"; var trainingArgs = " loader=text{col=Label:BL:0 col=F1:R4:1-8 col=F2:TX:9} xf=Cat{col=F2} xf=Concat{col=Features:F1,F2} tr=ft{numThreads=1 numLeaves=8 numTrees=3} seed=1"; Assert.Equal(0, Maml.Main(new[] { "train " + trainingPathArgs + trainingArgs})); var subDir = Path.Combine("..", "..", "BaselineOutput", "Common", "Onnx", "BinaryClassification", "BreastCancer"); var onnxTextName = "ModelWithLessIO.txt"; var onnxFileName = "ModelWithLessIO.onnx"; var onnxTextPath = GetOutputPath(subDir, onnxTextName); var onnxFilePath = GetOutputPath(subDir, onnxFileName); string conversionCommand = $"saveonnx in={modelPath} onnx={onnxFilePath} json={onnxTextPath} domain=machinelearning.dotnet name=modelWithLessIO inputsToDrop=Label outputsToDrop=F1,F2,Features,Label"; Assert.Equal(0, Maml.Main(new[] { conversionCommand })); var fileText = File.ReadAllText(onnxTextPath); fileText = Regex.Replace(fileText, "\"producerVersion\": \".*\"", "\"producerVersion\": \"##VERSION##\""); File.WriteAllText(onnxTextPath, fileText); CheckEquality(subDir, onnxTextName); Done(); } [Fact] public void KeyToVectorWithBagOnnxConversionTest() { var mlContext = new MLContext(seed: 1, conc: 1); string dataPath = GetDataPath("breast-cancer.txt"); var data = mlContext.Data.LoadFromTextFile<BreastCancerCatFeatureExample>(dataPath, separatorChar: '\t', hasHeader: true); var pipeline = mlContext.Transforms.Categorical.OneHotEncoding("F2", "F2", Transforms.OneHotEncodingTransformer.OutputKind.Bag) .Append(mlContext.Transforms.ReplaceMissingValues(new MissingValueReplacingEstimator.ColumnOptions("F2"))) .Append(mlContext.Transforms.Concatenate("Features", "F1", "F2")) .Append(mlContext.BinaryClassification.Trainers.FastTree(labelColumnName: "Label", featureColumnName: "Features", numLeaves: 2, numTrees: 1, minDatapointsInLeaves: 2)); var model = pipeline.Fit(data); var onnxModel = mlContext.Model.ConvertToOnnxProtobuf(model, data); // Check ONNX model's text format. We save the produced ONNX model as a text file and compare it against // the associated file in ML.NET repo. Such a comparison can be retired if ONNXRuntime ported to ML.NET // can support Linux and Mac. var subDir = Path.Combine("..", "..", "BaselineOutput", "Common", "Onnx", "BinaryClassification", "BreastCancer"); var onnxTextName = "OneHotBagPipeline.txt"; var onnxFileName = "OneHotBagPipeline.onnx"; var onnxTextPath = GetOutputPath(subDir, onnxTextName); var onnxFilePath = GetOutputPath(subDir, onnxFileName); SaveOnnxModel(onnxModel, onnxFilePath, onnxTextPath); CheckEquality(subDir, onnxTextName); Done(); } [Fact] public void InitializerCreationTest() { var env = new MLContext(); // Create the actual implementation var ctxImpl = new OnnxContextImpl(env, "model", "ML.NET", "0", 0, "com.test", Model.OnnxConverter.OnnxVersion.Stable); // Use implementation as in the actual conversion code var ctx = ctxImpl as OnnxContext; ctx.AddInitializer(9.4f, "float"); ctx.AddInitializer(17L, "int64"); ctx.AddInitializer("36", "string"); ctx.AddInitializer(new List<float> { 9.4f, 1.7f, 3.6f }, new List<long> { 1, 3 }, "floats"); ctx.AddInitializer(new List<long> { 94L, 17L, 36L }, new List<long> { 1, 3 }, "int64s"); ctx.AddInitializer(new List<string> { "94", "17", "36" }, new List<long> { 1, 3 }, "strings"); var model = ctxImpl.MakeModel(); var floatScalar = model.Graph.Initializer[0]; Assert.True(floatScalar.Name == "float"); Assert.True(floatScalar.Dims.Count == 0); Assert.True(floatScalar.FloatData.Count == 1); Assert.True(floatScalar.FloatData[0] == 9.4f); var int64Scalar = model.Graph.Initializer[1]; Assert.True(int64Scalar.Name == "int64"); Assert.True(int64Scalar.Dims.Count == 0); Assert.True(int64Scalar.Int64Data.Count == 1); Assert.True(int64Scalar.Int64Data[0] == 17L); var stringScalar = model.Graph.Initializer[2]; Assert.True(stringScalar.Name == "string"); Assert.True(stringScalar.Dims.Count == 0); Assert.True(stringScalar.StringData.Count == 1); Assert.True(stringScalar.StringData[0].ToStringUtf8() == "36"); var floatsTensor = model.Graph.Initializer[3]; Assert.True(floatsTensor.Name == "floats"); Assert.True(floatsTensor.Dims.Count == 2); Assert.True(floatsTensor.Dims[0] == 1); Assert.True(floatsTensor.Dims[1] == 3); Assert.True(floatsTensor.FloatData.Count == 3); Assert.True(floatsTensor.FloatData[0] == 9.4f); Assert.True(floatsTensor.FloatData[1] == 1.7f); Assert.True(floatsTensor.FloatData[2] == 3.6f); var int64sTensor = model.Graph.Initializer[4]; Assert.True(int64sTensor.Name == "int64s"); Assert.True(int64sTensor.Dims.Count == 2); Assert.True(int64sTensor.Dims[0] == 1); Assert.True(int64sTensor.Dims[1] == 3); Assert.True(int64sTensor.Int64Data.Count == 3); Assert.True(int64sTensor.Int64Data[0] == 94L); Assert.True(int64sTensor.Int64Data[1] == 17L); Assert.True(int64sTensor.Int64Data[2] == 36L); var stringsTensor = model.Graph.Initializer[5]; Assert.True(stringsTensor.Name == "strings"); Assert.True(stringsTensor.Dims.Count == 2); Assert.True(stringsTensor.Dims[0] == 1); Assert.True(stringsTensor.Dims[1] == 3); Assert.True(stringsTensor.StringData.Count == 3); Assert.True(stringsTensor.StringData[0].ToStringUtf8() == "94"); Assert.True(stringsTensor.StringData[1].ToStringUtf8() == "17"); Assert.True(stringsTensor.StringData[2].ToStringUtf8() == "36"); } [Fact] public void LogisticRegressionOnnxConversionTest() { // Step 1: Create and train a ML.NET pipeline. var trainDataPath = GetDataPath(TestDatasets.generatedRegressionDataset.trainFilename); var mlContext = new MLContext(seed: 1, conc: 1); var data = mlContext.Data.LoadFromTextFile<AdultData>(trainDataPath, separatorChar: ';' , hasHeader: true); var cachedTrainData = mlContext.Data.Cache(data); var dynamicPipeline = mlContext.Transforms.Normalize("FeatureVector") .AppendCacheCheckpoint(mlContext) .Append(mlContext.Regression.Trainers.StochasticDualCoordinateAscent(labelColumnName: "Target", featureColumnName: "FeatureVector")); var model = dynamicPipeline.Fit(data); // Step 2: Convert ML.NET model to ONNX format and save it as a file. var onnxModel = mlContext.Model.ConvertToOnnxProtobuf(model, data); // Step 3: Save ONNX model as binary and text files. var subDir = Path.Combine("..", "..", "BaselineOutput", "Common", "Onnx", "BinaryClassification", "BreastCancer"); var onnxFileName = "LogisticRegressionSaveModelToOnnxTest.onnx"; var onnxFilePath = GetOutputPath(subDir, onnxFileName); var onnxTextName = "LogisticRegressionSaveModelToOnnxTest.txt"; var onnxTextPath = GetOutputPath(subDir, onnxTextName); SaveOnnxModel(onnxModel, onnxFilePath, onnxTextPath); // Step 4: Check ONNX model's text format. CheckEquality(subDir, onnxTextName, digitsOfPrecision: 3); Done(); } [LightGBMFact] public void LightGbmBinaryClassificationOnnxConversionTest() { // Step 1: Create and train a ML.NET pipeline. var trainDataPath = GetDataPath(TestDatasets.generatedRegressionDataset.trainFilename); var mlContext = new MLContext(seed: 1, conc: 1); var data = mlContext.Data.LoadFromTextFile<AdultData>(trainDataPath, separatorChar: ';' , hasHeader: true); var cachedTrainData = mlContext.Data.Cache(data); var dynamicPipeline = mlContext.Transforms.Normalize("FeatureVector") .AppendCacheCheckpoint(mlContext) .Append(mlContext.Regression.Trainers.LightGbm(labelColumnName: "Target", featureColumnName: "FeatureVector", numBoostRound: 3, numLeaves: 16, minDataPerLeaf: 100)); var model = dynamicPipeline.Fit(data); // Step 2: Convert ML.NET model to ONNX format and save it as a file. var onnxModel = mlContext.Model.ConvertToOnnxProtobuf(model, data); // Step 3: Save ONNX model as binary and text files. var subDir = Path.Combine("..", "..", "BaselineOutput", "Common", "Onnx", "BinaryClassification", "BreastCancer"); var onnxFileName = "LightGbmBinaryClassificationOnnxConversionTest.onnx"; var onnxFilePath = GetOutputPath(subDir, onnxFileName); var onnxTextName = "LightGbmBinaryClassificationOnnxConversionTest.txt"; var onnxTextPath = GetOutputPath(subDir, onnxTextName); SaveOnnxModel(onnxModel, onnxFilePath, onnxTextPath); // Step 4: Check ONNX model's text format. CheckEquality(subDir, onnxTextName, digitsOfPrecision: 3); Done(); } [Fact] public void MulticlassLogisticRegressionOnnxConversionTest() { var mlContext = new MLContext(seed: 1, conc: 1); string dataPath = GetDataPath("breast-cancer.txt"); var data = mlContext.Data.LoadFromTextFile<BreastCancerMulticlassExample>(dataPath, separatorChar: '\t', hasHeader: true); var pipeline = mlContext.Transforms.Normalize("Features"). Append(mlContext.Transforms.Conversion.MapValueToKey("Label")). Append(mlContext.MulticlassClassification.Trainers.LogisticRegression(new MulticlassLogisticRegression.Options() { UseThreads = false })); var model = pipeline.Fit(data); var transformedData = model.Transform(data); var onnxModel = mlContext.Model.ConvertToOnnxProtobuf(model, data); var subDir = Path.Combine("..", "..", "BaselineOutput", "Common", "Onnx", "MultiClassClassification", "BreastCancer"); var onnxFileName = "MultiClassificationLogisticRegressionSaveModelToOnnxTest.onnx"; var onnxFilePath = GetOutputPath(subDir, onnxFileName); var onnxTextName = "MultiClassificationLogisticRegressionSaveModelToOnnxTest.txt"; var onnxTextPath = GetOutputPath(subDir, onnxTextName); SaveOnnxModel(onnxModel, onnxFilePath, onnxTextPath); CheckEquality(subDir, onnxTextName, digitsOfPrecision: 2); Done(); } [Fact] public void RemoveVariablesInPipelineTest() { var mlContext = new MLContext(seed: 1, conc: 1); string dataPath = GetDataPath("breast-cancer.txt"); var data = mlContext.Data.LoadFromTextFile<BreastCancerCatFeatureExample>(dataPath, separatorChar: '\t', hasHeader: true); var pipeline = mlContext.Transforms.Categorical.OneHotEncoding("F2", "F2", Transforms.OneHotEncodingTransformer.OutputKind.Bag) .Append(mlContext.Transforms.ReplaceMissingValues(new MissingValueReplacingEstimator.ColumnOptions("F2"))) .Append(mlContext.Transforms.Concatenate("Features", "F1", "F2")) .Append(mlContext.Transforms.Normalize("Features")) .Append(mlContext.BinaryClassification.Trainers.FastTree(labelColumnName: "Label", featureColumnName: "Features", numLeaves: 2, numTrees: 1, minDatapointsInLeaves: 2)); var model = pipeline.Fit(data); var transformedData = model.Transform(data); var onnxConversionContext = new OnnxContextImpl(mlContext, "A Simple Pipeline", "ML.NET", "0", 0, "machinelearning.dotnet", OnnxVersion.Stable); LinkedList<ITransformCanSaveOnnx> transforms = null; using (var conversionChannel = (mlContext as IChannelProvider).Start("ONNX conversion")) { SaveOnnxCommand.GetPipe(onnxConversionContext, conversionChannel, transformedData, out IDataView root, out IDataView sink, out transforms); // Input columns' names to be excluded in the resulted ONNX model. var redundantInputColumnNames = new HashSet<string> { "Label" }; // Output columns' names to be excluded in the resulted ONNX model. var redundantOutputColumnNames = new HashSet<string> { "Label", "F1", "F2", "Features" }; var onnxModel = SaveOnnxCommand.ConvertTransformListToOnnxModel(onnxConversionContext, conversionChannel, root, sink, transforms, redundantInputColumnNames, redundantOutputColumnNames); // Check ONNX model's text format. We save the produced ONNX model as a text file and compare it against // the associated file in ML.NET repo. Such a comparison can be retired if ONNXRuntime ported to ML.NET // can support Linux and Mac. var subDir = Path.Combine("..", "..", "BaselineOutput", "Common", "Onnx", "BinaryClassification", "BreastCancer"); var onnxTextName = "ExcludeVariablesInOnnxConversion.txt"; var onnxFileName = "ExcludeVariablesInOnnxConversion.onnx"; var onnxTextPath = GetOutputPath(subDir, onnxTextName); var onnxFilePath = GetOutputPath(subDir, onnxFileName); SaveOnnxModel(onnxModel, onnxFilePath, onnxTextPath); CheckEquality(subDir, onnxTextName, digitsOfPrecision: 3); } Done(); } private class SmallSentimentExample { [LoadColumn(0,3), VectorType(4)] public string[] Tokens; } [Fact] public void WordEmbeddingsTest() { var mlContext = new MLContext(seed: 1, conc: 1); var dataPath = GetDataPath(@"small-sentiment-test.tsv"); var embedNetworkPath = GetDataPath(@"shortsentiment.emd"); var data = mlContext.Data.LoadFromTextFile<SmallSentimentExample>(dataPath, separatorChar: '\t', hasHeader: false); var pipeline = mlContext.Transforms.Text.ExtractWordEmbeddings("Embed", embedNetworkPath, "Tokens"); var model = pipeline.Fit(data); var transformedData = model.Transform(data); var subDir = Path.Combine("..", "..", "BaselineOutput", "Common", "Onnx", "Transforms", "Sentiment"); var onnxTextName = "SmallWordEmbed.txt"; var onnxFileName = "SmallWordEmbed.onnx"; var onnxTextPath = GetOutputPath(subDir, onnxTextName); var onnxFilePath = GetOutputPath(subDir, onnxFileName); var onnxModel = mlContext.Model.ConvertToOnnxProtobuf(model, data); SaveOnnxModel(onnxModel, onnxFilePath, onnxTextPath); CheckEquality(subDir, onnxTextName); Done(); } private void CreateDummyExamplesToMakeComplierHappy() { var dummyExample = new BreastCancerFeatureVector() { Features = null }; var dummyExample1 = new BreastCancerCatFeatureExample() { Label = false, F1 = 0, F2 = "Amy" }; var dummyExample2 = new BreastCancerMulticlassExample() { Label = "Amy", Features = null }; var dummyExample3 = new SmallSentimentExample() { Tokens = null }; } private void CompareSelectedR4VectorColumns(string leftColumnName, string rightColumnName, IDataView left, IDataView right, int precision = 6) { var leftColumnIndex = left.Schema[leftColumnName].Index; var rightColumnIndex = right.Schema[rightColumnName].Index; using (var expectedCursor = left.GetRowCursor(left.Schema[leftColumnIndex])) using (var actualCursor = right.GetRowCursor(right.Schema[rightColumnIndex])) { VBuffer<float> expected = default; VBuffer<float> actual = default; var expectedGetter = expectedCursor.GetGetter<VBuffer<float>>(leftColumnIndex); var actualGetter = actualCursor.GetGetter<VBuffer<float>>(rightColumnIndex); while (expectedCursor.MoveNext() && actualCursor.MoveNext()) { expectedGetter(ref expected); actualGetter(ref actual); Assert.Equal(expected.Length, actual.Length); for (int i = 0; i < expected.Length; ++i) Assert.Equal(expected.GetItemOrDefault(i), actual.GetItemOrDefault(i), precision); } } } private void CompareSelectedR4ScalarColumns(string leftColumnName, string rightColumnName, IDataView left, IDataView right, int precision = 6) { var leftColumnIndex = left.Schema[leftColumnName].Index; var rightColumnIndex = right.Schema[rightColumnName].Index; using (var expectedCursor = left.GetRowCursor(left.Schema[leftColumnIndex])) using (var actualCursor = right.GetRowCursor(right.Schema[rightColumnIndex])) { float expected = default; VBuffer<float> actual = default; var expectedGetter = expectedCursor.GetGetter<float>(leftColumnIndex); var actualGetter = actualCursor.GetGetter<VBuffer<float>>(rightColumnIndex); while (expectedCursor.MoveNext() && actualCursor.MoveNext()) { expectedGetter(ref expected); actualGetter(ref actual); // Scalar such as R4 (float) is converted to [1, 1]-tensor in ONNX format for consitency of making batch prediction. Assert.Equal(1, actual.Length); Assert.Equal(expected, actual.GetItemOrDefault(0), precision); } } } private void SaveOnnxModel(ModelProto model, string binaryFormatPath, string textFormatPath) { DeleteOutputPath(binaryFormatPath); // Clean if such a file exists. DeleteOutputPath(textFormatPath); if (binaryFormatPath != null) using (var file = Env.CreateOutputFile(binaryFormatPath)) using (var stream = file.CreateWriteStream()) model.WriteTo(stream); if (textFormatPath != null) { using (var file = Env.CreateOutputFile(textFormatPath)) using (var stream = file.CreateWriteStream()) using (var writer = new StreamWriter(stream)) { var parsedJson = JsonConvert.DeserializeObject(model.ToString()); writer.Write(JsonConvert.SerializeObject(parsedJson, Formatting.Indented)); } // Strip the version information. var fileText = File.ReadAllText(textFormatPath); fileText = Regex.Replace(fileText, "\"producerVersion\": \".*\"", "\"producerVersion\": \"##VERSION##\""); File.WriteAllText(textFormatPath, fileText); } } } }
51.060932
211
0.626211
[ "MIT" ]
endintiers/machinelearning
test/Microsoft.ML.Tests/OnnxConversionTest.cs
28,494
C#
using System.ComponentModel.DataAnnotations; using Domain.Enums; namespace BLL.App.DTO.DomainEntityDTOs { public class Folder { public int Id { get; set; } public FolderType FolderType { get; set; } [MaxLength(64)] [MinLength(1)] [Required] public string Name { get; set; } [MaxLength(1000)] [MinLength(1)] public string Comment { get; set; } //public ICollection<UserFolder> UserFolders { get; set; } //public ICollection<SongInFolder> SongInFolders { get; set; } } }
23.64
70
0.58714
[ "MIT" ]
JanekV/Learn2Play
Learn2Play/BLL.App.DTO/DomainEntityDTOs/Folder.cs
593
C#
using System; using System.Collections.Generic; using UnityEngine; using XLua; namespace Main { public class PhysicsListener : BehaviourListener { public string listenerTag; public Action<LuaTable, Collider> onTriggerEnter; public Action<LuaTable, Collider> onTriggerStay; public Action<LuaTable, Collider> onTriggerExit; public Action<LuaTable, Collision> onCollisionEnter; public Action<LuaTable, Collision> onCollisionStay; public Action<LuaTable, Collision> onCollisionExit; private LuaTable m_LuaTable; void Awake() { LuaBehaviour behaviour = gameObject.GetComponent<LuaBehaviour>(); m_LuaTable = behaviour ? behaviour.LuaTable : null; } void OnTriggerEnter(Collider other) { if (onTriggerEnter != null) { onTriggerEnter(m_LuaTable, other); } } void OnTriggerStay(Collider other) { if (onTriggerStay != null) { onTriggerStay(m_LuaTable, other); } } void OnTriggerExit(Collider other) { if (onTriggerExit != null) { onTriggerExit(m_LuaTable, other); } } void OnCollisionEnter(Collision collision) { if (onCollisionEnter != null) { onCollisionEnter(m_LuaTable, collision); } } void OnCollisionStay(Collision collision) { if (onCollisionStay != null) { onCollisionStay(m_LuaTable, collision); } } void OnCollisionExit(Collision collision) { if (onCollisionExit != null) { onCollisionExit(m_LuaTable, collision); } } private static PhysicsListener FindListener(PhysicsListener[] listeners, string listenerTag) { foreach (PhysicsListener listener in listeners) { if (string.Equals(listener.listenerTag, listenerTag)) { return listener; } } return null; } public static PhysicsListener Get(GameObject go, string listenerTag = null) { PhysicsListener[] listeners = go.GetComponents<PhysicsListener>(); PhysicsListener listener = FindListener(listeners, listenerTag); if (listener == null) { listener = go.AddComponent<PhysicsListener>(); listener.listenerTag = listenerTag; } return listener; } public static PhysicsListener Get(Component comp, string listenerTag = null) { return Get(comp.gameObject, listenerTag); } public override void Dispose() { onTriggerEnter = null; onTriggerStay = null; onTriggerExit = null; onCollisionEnter = null; onCollisionStay = null; onCollisionExit = null; Destroy(this); } } }
21.318966
94
0.705216
[ "MIT" ]
1174290471/HotUpdateSolution
Assets/Scripts/Lua/BehaviourListener/PhysicsListener.cs
2,475
C#
using UnityEngine; using UnityEngine.UI; namespace UIParts { [RequireComponent(typeof(Text))] public class VersionText : MonoBehaviour { public void Start() { GetComponent<Text>().text = Game.Version; } } }
15.785714
44
0.710407
[ "MIT" ]
kyubuns/OnlineCoinPusher
Assets/Scripts/UIParts/VersionText.cs
223
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace CloudAwesome.Xrm.Customisation { [System.Runtime.Serialization.DataContractAttribute()] public enum CustomAPIRequestParameterState { [System.Runtime.Serialization.EnumMemberAttribute()] Active = 0, [System.Runtime.Serialization.EnumMemberAttribute()] Inactive = 1, } /// <summary> /// Entity that defines a request parameter for a custom API /// </summary> [System.Runtime.Serialization.DataContractAttribute()] [Microsoft.Xrm.Sdk.Client.EntityLogicalNameAttribute("customapirequestparameter")] public partial class CustomAPIRequestParameter : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged { public static class Fields { public const string ComponentIdUnique = "componentidunique"; public const string ComponentState = "componentstate"; public const string CreatedBy = "createdby"; public const string CreatedOn = "createdon"; public const string CreatedOnBehalfBy = "createdonbehalfby"; public const string CustomAPIId = "customapiid"; public const string CustomAPIRequestParameterId = "customapirequestparameterid"; public const string Id = "customapirequestparameterid"; public const string Description = "description"; public const string DisplayName = "displayname"; public const string ImportSequenceNumber = "importsequencenumber"; public const string IsCustomizable = "iscustomizable"; public const string IsManaged = "ismanaged"; public const string IsOptional = "isoptional"; public const string LogicalEntityName = "logicalentityname"; public const string ModifiedBy = "modifiedby"; public const string ModifiedOn = "modifiedon"; public const string ModifiedOnBehalfBy = "modifiedonbehalfby"; public const string Name = "name"; public const string OverriddenCreatedOn = "overriddencreatedon"; public const string OverwriteTime = "overwritetime"; public const string OwnerId = "ownerid"; public const string OwningBusinessUnit = "owningbusinessunit"; public const string OwningTeam = "owningteam"; public const string OwningUser = "owninguser"; public const string SolutionId = "solutionid"; public const string StateCode = "statecode"; public const string StatusCode = "statuscode"; public const string TimeZoneRuleVersionNumber = "timezoneruleversionnumber"; public const string Type = "type"; public const string UniqueName = "uniquename"; public const string UTCConversionTimeZoneCode = "utcconversiontimezonecode"; public const string VersionNumber = "versionnumber"; public const string customapi_customapirequestparameter = "customapi_customapirequestparameter"; } /// <summary> /// Default Constructor. /// </summary> [System.Diagnostics.DebuggerNonUserCode()] public CustomAPIRequestParameter() : base(EntityLogicalName) { } public const string AlternateKeys = "componentstate,customapiid,overwritetime,uniquename"; public const string EntityLogicalName = "customapirequestparameter"; public const string EntitySchemaName = "CustomAPIRequestParameter"; public const string PrimaryIdAttribute = "customapirequestparameterid"; public const string PrimaryNameAttribute = "name"; public const string EntityLogicalCollectionName = "customapirequestparameters"; public const string EntitySetName = "customapirequestparameters"; public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging; [System.Diagnostics.DebuggerNonUserCode()] private void OnPropertyChanged(string propertyName) { if ((this.PropertyChanged != null)) { this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } [System.Diagnostics.DebuggerNonUserCode()] private void OnPropertyChanging(string propertyName) { if ((this.PropertyChanging != null)) { this.PropertyChanging(this, new System.ComponentModel.PropertyChangingEventArgs(propertyName)); } } /// <summary> /// For internal use only. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("componentidunique")] public System.Nullable<System.Guid> ComponentIdUnique { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.Guid>>("componentidunique"); } } /// <summary> /// For internal use only. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("componentstate")] public virtual ComponentState? ComponentState { [System.Diagnostics.DebuggerNonUserCode()] get { return ((ComponentState?)(EntityOptionSetEnum.GetEnum(this, "componentstate"))); } } /// <summary> /// Unique identifier of the user who created the record. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdby")] public Microsoft.Xrm.Sdk.EntityReference CreatedBy { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("createdby"); } } /// <summary> /// Date and time when the record was created. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdon")] public System.Nullable<System.DateTime> CreatedOn { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.DateTime>>("createdon"); } } /// <summary> /// Unique identifier of the delegate user who created the record. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdonbehalfby")] public Microsoft.Xrm.Sdk.EntityReference CreatedOnBehalfBy { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("createdonbehalfby"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("CreatedOnBehalfBy"); this.SetAttributeValue("createdonbehalfby", value); this.OnPropertyChanged("CreatedOnBehalfBy"); } } /// <summary> /// Unique identifier for the custom API that owns this custom API request parameter /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("customapiid")] public Microsoft.Xrm.Sdk.EntityReference CustomAPIId { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("customapiid"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("CustomAPIId"); this.SetAttributeValue("customapiid", value); this.OnPropertyChanged("CustomAPIId"); } } /// <summary> /// Unique identifier for custom API request parameter instances /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("customapirequestparameterid")] public System.Nullable<System.Guid> CustomAPIRequestParameterId { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.Guid>>("customapirequestparameterid"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("CustomAPIRequestParameterId"); this.SetAttributeValue("customapirequestparameterid", value); if (value.HasValue) { base.Id = value.Value; } else { base.Id = System.Guid.Empty; } this.OnPropertyChanged("CustomAPIRequestParameterId"); } } [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("customapirequestparameterid")] public override System.Guid Id { [System.Diagnostics.DebuggerNonUserCode()] get { return base.Id; } [System.Diagnostics.DebuggerNonUserCode()] set { this.CustomAPIRequestParameterId = value; } } /// <summary> /// Localized description for custom API request parameter instances /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("description")] public string Description { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("description"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("Description"); this.SetAttributeValue("description", value); this.OnPropertyChanged("Description"); } } /// <summary> /// Localized display name for custom API request parameter instances /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("displayname")] public string DisplayName { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("displayname"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("DisplayName"); this.SetAttributeValue("displayname", value); this.OnPropertyChanged("DisplayName"); } } /// <summary> /// Sequence number of the import that created this record. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("importsequencenumber")] public System.Nullable<int> ImportSequenceNumber { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<int>>("importsequencenumber"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("ImportSequenceNumber"); this.SetAttributeValue("importsequencenumber", value); this.OnPropertyChanged("ImportSequenceNumber"); } } /// <summary> /// For internal use only. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("iscustomizable")] public Microsoft.Xrm.Sdk.BooleanManagedProperty IsCustomizable { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.BooleanManagedProperty>("iscustomizable"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("IsCustomizable"); this.SetAttributeValue("iscustomizable", value); this.OnPropertyChanged("IsCustomizable"); } } /// <summary> /// Indicates whether the solution component is part of a managed solution. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("ismanaged")] public System.Nullable<bool> IsManaged { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<bool>>("ismanaged"); } } /// <summary> /// Indicates if the custom API request parameter is optional /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("isoptional")] public System.Nullable<bool> IsOptional { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<bool>>("isoptional"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("IsOptional"); this.SetAttributeValue("isoptional", value); this.OnPropertyChanged("IsOptional"); } } /// <summary> /// The logical name of the entity bound to the custom API request parameter /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("logicalentityname")] public string LogicalEntityName { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("logicalentityname"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("LogicalEntityName"); this.SetAttributeValue("logicalentityname", value); this.OnPropertyChanged("LogicalEntityName"); } } /// <summary> /// Unique identifier of the user who modified the record. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedby")] public Microsoft.Xrm.Sdk.EntityReference ModifiedBy { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("modifiedby"); } } /// <summary> /// Date and time when the record was modified. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedon")] public System.Nullable<System.DateTime> ModifiedOn { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.DateTime>>("modifiedon"); } } /// <summary> /// Unique identifier of the delegate user who modified the record. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedonbehalfby")] public Microsoft.Xrm.Sdk.EntityReference ModifiedOnBehalfBy { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("modifiedonbehalfby"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("ModifiedOnBehalfBy"); this.SetAttributeValue("modifiedonbehalfby", value); this.OnPropertyChanged("ModifiedOnBehalfBy"); } } /// <summary> /// The primary name of the custom API request parameter /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("name")] public string Name { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("name"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("Name"); this.SetAttributeValue("name", value); this.OnPropertyChanged("Name"); } } /// <summary> /// Date and time that the record was migrated. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("overriddencreatedon")] public System.Nullable<System.DateTime> OverriddenCreatedOn { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.DateTime>>("overriddencreatedon"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("OverriddenCreatedOn"); this.SetAttributeValue("overriddencreatedon", value); this.OnPropertyChanged("OverriddenCreatedOn"); } } /// <summary> /// For internal use only. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("overwritetime")] public System.Nullable<System.DateTime> OverwriteTime { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.DateTime>>("overwritetime"); } } /// <summary> /// Owner Id /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("ownerid")] public Microsoft.Xrm.Sdk.EntityReference OwnerId { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("ownerid"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("OwnerId"); this.SetAttributeValue("ownerid", value); this.OnPropertyChanged("OwnerId"); } } /// <summary> /// Unique identifier for the business unit that owns the record /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("owningbusinessunit")] public Microsoft.Xrm.Sdk.EntityReference OwningBusinessUnit { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("owningbusinessunit"); } } /// <summary> /// Unique identifier for the team that owns the record. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("owningteam")] public Microsoft.Xrm.Sdk.EntityReference OwningTeam { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("owningteam"); } } /// <summary> /// Unique identifier for the user that owns the record. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("owninguser")] public Microsoft.Xrm.Sdk.EntityReference OwningUser { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("owninguser"); } } /// <summary> /// Unique identifier of the associated solution. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("solutionid")] public System.Nullable<System.Guid> SolutionId { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<System.Guid>>("solutionid"); } } /// <summary> /// Status of the Custom API Request Parameter /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("statecode")] public System.Nullable<CloudAwesome.Xrm.Customisation.CustomAPIRequestParameterState> StateCode { [System.Diagnostics.DebuggerNonUserCode()] get { Microsoft.Xrm.Sdk.OptionSetValue optionSet = this.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValue>("statecode"); if ((optionSet != null)) { return ((CloudAwesome.Xrm.Customisation.CustomAPIRequestParameterState)(System.Enum.ToObject(typeof(CloudAwesome.Xrm.Customisation.CustomAPIRequestParameterState), optionSet.Value))); } else { return null; } } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("StateCode"); if ((value == null)) { this.SetAttributeValue("statecode", null); } else { this.SetAttributeValue("statecode", new Microsoft.Xrm.Sdk.OptionSetValue(((int)(value)))); } this.OnPropertyChanged("StateCode"); } } /// <summary> /// Reason for the status of the Custom API Request Parameter /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("statuscode")] public virtual CustomAPIRequestParameter_StatusCode? StatusCode { [System.Diagnostics.DebuggerNonUserCode()] get { return ((CustomAPIRequestParameter_StatusCode?)(EntityOptionSetEnum.GetEnum(this, "statuscode"))); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("StatusCode"); this.SetAttributeValue("statuscode", value.HasValue ? new Microsoft.Xrm.Sdk.OptionSetValue((int)value) : null); this.OnPropertyChanged("StatusCode"); } } /// <summary> /// For internal use only. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("timezoneruleversionnumber")] public System.Nullable<int> TimeZoneRuleVersionNumber { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<int>>("timezoneruleversionnumber"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("TimeZoneRuleVersionNumber"); this.SetAttributeValue("timezoneruleversionnumber", value); this.OnPropertyChanged("TimeZoneRuleVersionNumber"); } } /// <summary> /// The data type of the custom API request parameter /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("type")] public virtual CustomAPIFieldType? Type { [System.Diagnostics.DebuggerNonUserCode()] get { return ((CustomAPIFieldType?)(EntityOptionSetEnum.GetEnum(this, "type"))); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("Type"); this.SetAttributeValue("type", value.HasValue ? new Microsoft.Xrm.Sdk.OptionSetValue((int)value) : null); this.OnPropertyChanged("Type"); } } /// <summary> /// Unique name for the custom API request parameter /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("uniquename")] public string UniqueName { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<string>("uniquename"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("UniqueName"); this.SetAttributeValue("uniquename", value); this.OnPropertyChanged("UniqueName"); } } /// <summary> /// Time zone code that was in use when the record was created. /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("utcconversiontimezonecode")] public System.Nullable<int> UTCConversionTimeZoneCode { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<int>>("utcconversiontimezonecode"); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("UTCConversionTimeZoneCode"); this.SetAttributeValue("utcconversiontimezonecode", value); this.OnPropertyChanged("UTCConversionTimeZoneCode"); } } /// <summary> /// Version Number /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("versionnumber")] public System.Nullable<long> VersionNumber { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetAttributeValue<System.Nullable<long>>("versionnumber"); } } /// <summary> /// N:1 customapi_customapirequestparameter /// </summary> [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("customapiid")] [Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("customapi_customapirequestparameter")] public CloudAwesome.Xrm.Customisation.CustomAPI customapi_customapirequestparameter { [System.Diagnostics.DebuggerNonUserCode()] get { return this.GetRelatedEntity<CloudAwesome.Xrm.Customisation.CustomAPI>("customapi_customapirequestparameter", null); } [System.Diagnostics.DebuggerNonUserCode()] set { this.OnPropertyChanging("customapi_customapirequestparameter"); this.SetRelatedEntity<CloudAwesome.Xrm.Customisation.CustomAPI>("customapi_customapirequestparameter", null, value); this.OnPropertyChanged("customapi_customapirequestparameter"); } } /// <summary> /// Constructor for populating via LINQ queries given a LINQ anonymous type /// <param name="anonymousType">LINQ anonymous type.</param> /// </summary> [System.Diagnostics.DebuggerNonUserCode()] public CustomAPIRequestParameter(object anonymousType) : this() { foreach (var p in anonymousType.GetType().GetProperties()) { var value = p.GetValue(anonymousType, null); var name = p.Name.ToLower(); if (name.EndsWith("enum") && value.GetType().BaseType == typeof(System.Enum)) { value = new Microsoft.Xrm.Sdk.OptionSetValue((int) value); name = name.Remove(name.Length - "enum".Length); } switch (name) { case "id": base.Id = (System.Guid)value; Attributes["customapirequestparameterid"] = base.Id; break; case "customapirequestparameterid": var id = (System.Nullable<System.Guid>) value; if(id == null){ continue; } base.Id = id.Value; Attributes[name] = base.Id; break; case "formattedvalues": // Add Support for FormattedValues FormattedValues.AddRange((Microsoft.Xrm.Sdk.FormattedValueCollection)value); break; default: Attributes[name] = value; break; } } } } }
30.900783
188
0.699493
[ "MIT" ]
Cloud-Awesome/cds-customisation
src/CloudAwesome.Xrm.Customisation/CloudAwesome.Xrm.Customisation/EarlyBoundModels/CustomAPIRequestParameter.cs
23,670
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.NBCEL.ClassFile { /// <summary> /// Visitor with empty method bodies, can be extended and used in conjunction /// with the DescendingVisitor class, e.g. /// </summary> /// <remarks> /// Visitor with empty method bodies, can be extended and used in conjunction /// with the DescendingVisitor class, e.g. By courtesy of David Spencer. /// </remarks> /// <seealso cref="DescendingVisitor" /> public class EmptyVisitor : Visitor { protected internal EmptyVisitor() { } /// <since>6.0</since> public virtual void VisitAnnotation(Annotations obj) { } /// <since>6.0</since> public virtual void VisitParameterAnnotation(ParameterAnnotations obj) { } /// <since>6.0</since> public virtual void VisitAnnotationEntry(AnnotationEntry obj) { } /// <since>6.0</since> public virtual void VisitAnnotationDefault(AnnotationDefault obj) { } public virtual void VisitCode(Code obj) { } public virtual void VisitCodeException(CodeException obj) { } public virtual void VisitConstantClass(ConstantClass obj) { } public virtual void VisitConstantDouble(ConstantDouble obj) { } public virtual void VisitConstantFieldref(ConstantFieldref obj) { } public virtual void VisitConstantFloat(ConstantFloat obj) { } public virtual void VisitConstantInteger(ConstantInteger obj) { } public virtual void VisitConstantInterfaceMethodref(ConstantInterfaceMethodref obj) { } public virtual void VisitConstantInvokeDynamic(ConstantInvokeDynamic obj) { } public virtual void VisitConstantLong(ConstantLong obj) { } public virtual void VisitConstantMethodref(ConstantMethodref obj) { } public virtual void VisitConstantNameAndType(ConstantNameAndType obj) { } public virtual void VisitConstantPool(ConstantPool obj) { } public virtual void VisitConstantString(ConstantString obj) { } public virtual void VisitConstantUtf8(ConstantUtf8 obj) { } public virtual void VisitConstantValue(ConstantValue obj) { } public virtual void VisitDeprecated(Deprecated obj) { } public virtual void VisitExceptionTable(ExceptionTable obj) { } public virtual void VisitField(Field obj) { } public virtual void VisitInnerClass(InnerClass obj) { } public virtual void VisitInnerClasses(InnerClasses obj) { } /// <since>6.0</since> public virtual void VisitBootstrapMethods(BootstrapMethods obj) { } public virtual void VisitJavaClass(JavaClass obj) { } public virtual void VisitLineNumber(LineNumber obj) { } public virtual void VisitLineNumberTable(LineNumberTable obj) { } public virtual void VisitLocalVariable(LocalVariable obj) { } public virtual void VisitLocalVariableTable(LocalVariableTable obj ) { } public virtual void VisitMethod(Method obj) { } public virtual void VisitSignature(Signature obj) { } public virtual void VisitSourceFile(SourceFile obj) { } public virtual void VisitSynthetic(Synthetic obj) { } public virtual void VisitUnknown(Unknown obj) { } public virtual void VisitStackMap(StackMap obj) { } public virtual void VisitStackMapEntry(StackMapEntry obj) { } /// <since>6.0</since> public virtual void VisitEnclosingMethod(EnclosingMethod obj) { } /// <since>6.0</since> public virtual void VisitLocalVariableTypeTable(LocalVariableTypeTable obj) { } /// <since>6.0</since> public virtual void VisitMethodParameters(MethodParameters obj) { } /// <since>6.4.0</since> public virtual void VisitMethodParameter(MethodParameter obj) { } /// <since>6.0</since> public virtual void VisitConstantMethodType(ConstantMethodType obj ) { } /// <since>6.0</since> public virtual void VisitConstantMethodHandle(ConstantMethodHandle constantMethodHandle) { } /// <since>6.0</since> public virtual void VisitParameterAnnotationEntry(ParameterAnnotationEntry parameterAnnotationEntry) { } /// <since>6.1</since> public virtual void VisitConstantPackage(ConstantPackage constantPackage ) { } /// <since>6.1</since> public virtual void VisitConstantModule(ConstantModule constantModule ) { } /// <since>6.3</since> public virtual void VisitConstantDynamic(ConstantDynamic obj) { } /// <since>6.4.0</since> public virtual void VisitModule(Module obj) { } /// <since>6.4.0</since> public virtual void VisitModuleRequires(ModuleRequires obj) { } /// <since>6.4.0</since> public virtual void VisitModuleExports(ModuleExports obj) { } /// <since>6.4.0</since> public virtual void VisitModuleOpens(ModuleOpens obj) { } /// <since>6.4.0</since> public virtual void VisitModuleProvides(ModuleProvides obj) { } /// <since>6.4.0</since> public virtual void VisitModulePackages(ModulePackages obj) { } /// <since>6.4.0</since> public virtual void VisitModuleMainClass(ModuleMainClass obj) { } /// <since>6.4.0</since> public virtual void VisitNestHost(NestHost obj) { } /// <since>6.4.0</since> public virtual void VisitNestMembers(NestMembers obj) { } } }
24.41806
86
0.586632
[ "MIT" ]
SkriptInsight/Apache.NBCEL
NBCEL/ClassFile/EmptyVisitor.cs
7,301
C#
namespace VI.ParallelComputing.Drivers { public interface IGpuInterface { ParalleExecutorlInterface Executor { get; } } }
20.285714
51
0.697183
[ "MIT" ]
snownz/Virtual-Intelligence
VI/VI.ParallelComputing/Drivers/IAnnParallelInterface.cs
144
C#
using System.ComponentModel.DataAnnotations; namespace Frapid.AddressBook.QueryModels { public class AddressBookQuery { public string Tags { get; set; } [Required] public bool PrivateOnly { get; set; } public int UserId { get; set; } } }
20.357143
45
0.638596
[ "Apache-2.0" ]
Sandeepchau/MixErp22
src/Frapid.Web/Areas/Frapid.AddressBook/Backup/QueryModels/AddressBookQuery.cs
287
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.Azure.IIoT.Api.Jobs.Runtime { using Microsoft.Azure.IIoT.Api.Runtime; using Microsoft.Extensions.Configuration; /// <summary> /// Configuration - wraps a configuration root /// </summary> public class JobsServiceConfig : ApiConfigBase, IJobsServiceConfig { /// <summary> /// Jobs configuration /// </summary> private const string kJobServiceUrlKey = "JobServiceUrl"; private const string kJobServiceIdKey = "JobServiceResourceId"; /// <summary>Jobs service endpoint url</summary> public string JobServiceUrl => GetStringOrDefault( kJobServiceUrlKey, () => GetStringOrDefault(PcsVariable.PCS_JOBS_SERVICE_URL, () => GetDefaultUrl("9046", "jobs"))); /// <summary>Jobs service audience</summary> public string JobServiceResourceId => GetStringOrDefault( kJobServiceIdKey, () => GetStringOrDefault("JOBS_APP_ID", () => GetStringOrDefault(PcsVariable.PCS_AUTH_AUDIENCE, () => null))); /// <inheritdoc/> public JobsServiceConfig(IConfiguration configuration) : base(configuration) { } } }
39.384615
99
0.583984
[ "MIT" ]
bamajeed/Industrial-IoT
api/src/Microsoft.Azure.IIoT.Api/src/Jobs/Runtime/JobsServiceConfig.cs
1,538
C#
namespace ContosoInsurance.Models { public interface INetworkConnection { bool IsConnected { get; } void CheckNetworkConnection(); } }
18.222222
39
0.658537
[ "MIT" ]
Azure-Samples/ContosoInsurance
Src/Mobile/ContosoInsurance/ContosoInsurance/Models/INetworkConnection.cs
166
C#
using AutoMapper; using Microsoft.EntityFrameworkCore; using RPG.Data.Context; using RPG.Data.Repository.CharacterRepository; using RPG.Domain.Dto.Character; using RPG.Domain.Entities; using RPG.Domain.Response; using System.Collections.Generic; using System.Threading.Tasks; namespace RPG.Services.CharacterServices { public class CharacterService : ICharacterService { private readonly IMapper _mapper; private readonly DataContext _dataContext; private readonly ICharacterRepository _characterRepository; public CharacterService(IMapper mapper, ICharacterRepository characterRepository, DataContext dataContext) { _mapper = mapper; _dataContext = dataContext; _characterRepository = characterRepository; } public async Task<ServiceResponse<List<GetCharacterDto>>> AddCharacter(AddCharacterDto newCharacter) { var serviceResponse = new ServiceResponse<List<GetCharacterDto>> { Data = await _characterRepository.AddCharacter(newCharacter) }; if (serviceResponse.Data == null) { serviceResponse.Message = "There Is No Characters"; } if (serviceResponse.Data != null) { serviceResponse.Message = "Characters List"; } return serviceResponse; } public async Task<ServiceResponse<List<GetCharacterDto>>> DeleteCharacters(int id) { ServiceResponse<List<GetCharacterDto>> serviceResponse = new ServiceResponse<List<GetCharacterDto>> { Data = await _characterRepository.DeleteCharacters(id) }; if (serviceResponse.Data != null) { serviceResponse.Message = "Character deleted successfully"; return serviceResponse; } serviceResponse.Success = false; serviceResponse.Message = "No Such Character"; return serviceResponse; } public async Task<ServiceResponse<List<GetCharacterDto>>> GetAllCharacters() { ServiceResponse<List<GetCharacterDto>> serviceResponse = new ServiceResponse<List<GetCharacterDto>>(); serviceResponse.Data = _mapper.Map<List<GetCharacterDto>>(await _dataContext.Character.ToListAsync()); return serviceResponse; } public async Task<ServiceResponse<GetCharacterDto>> GetCharacterById(int id) { ServiceResponse<GetCharacterDto> serviceResponse = new ServiceResponse<GetCharacterDto>(); serviceResponse.Data = _mapper.Map<GetCharacterDto>(await _dataContext.Character.FirstOrDefaultAsync(c => c.Id == id)); return serviceResponse; } public async Task<ServiceResponse<GetCharacterDto>> UpdateCharacter(UpdateCharacterDto updateCharacter) { ServiceResponse<GetCharacterDto> serviceResponse = new ServiceResponse<GetCharacterDto>(); var character = _mapper.Map<Character>(updateCharacter); _dataContext.Character.Update(character); var success = await SaveChangesAsync(); if (success) { serviceResponse.Data = _mapper.Map<GetCharacterDto>(character); serviceResponse.Message = "All changes saved"; } if (!success) { serviceResponse.Success = false; serviceResponse.Message = "No Such Character"; } return serviceResponse; } public async Task<bool> SaveChangesAsync() { return await _dataContext.SaveChangesAsync() > 0; } } }
38.232323
131
0.634875
[ "MIT" ]
HusseinShukri/DotNET-RPG
RPG/RPG.Services/CharacterService/.vshistory/CharacterService.cs/2021-08-13_20_56_18_591.cs
3,787
C#