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
/* * This message is auto generated by ROS#. Please DO NOT modify. * Note: * - Comments from the original code will be written in their own line * - Variable sized arrays will be initialized to array of size 0 * Please report any issues at * <https://github.com/siemens/ros-sharp> */ namespace RosSharp.RosBridgeClient.MessageTypes.ObjectRecognition { public class ObjectRecognitionFeedback : Message { public const string RosMessageName = "object_recognition_msgs/ObjectRecognitionFeedback"; // no feedback public ObjectRecognitionFeedback() { } } }
24.8
97
0.696774
[ "Apache-2.0" ]
1441048907/ros-sharp
Libraries/RosBridgeClient/MessageTypes/ObjectRecognition/action/ObjectRecognitionFeedback.cs
620
C#
using System; namespace ASTRA.EMSG.Mobile.ViewModels { public interface IZustandsabschnittTabViewModel : ISaveable, IViewModel { string HeaderText { get; } bool HasError { get; } event EventHandler Changed; void Init(); bool IsValid { get; } void RefreshValidation(); void OpenHelp(); } }
23.8
75
0.621849
[ "BSD-3-Clause" ]
astra-emsg/ASTRA.EMSG
Mobile/ASTRA.EMSG.Mobile/ViewModels/IZustandsabschnittTabViewModel.cs
357
C#
namespace MagicGradients.Parser.TokenDefinitions { public interface ITokenDefinition { bool IsMatch(string token); void Parse(CssReader reader, GradientBuilder builder); } }
20.3
62
0.70936
[ "MIT" ]
Pemmican-Pete/MagicGradients
MagicGradients/Parser/TokenDefinitions/ITokenDefinition.cs
203
C#
using System; using Akka.Actor; namespace WinTail { /// <summary> /// Actor responsible for reading FROM the console. /// Also responsible for calling <see cref="ActorSystem.Terminate"/>. /// </summary> class ConsoleReaderActor : UntypedActor { public const string StartCommand = "start"; public const string ExitCommand = "exit"; protected override void OnReceive(object message) { if (message.Equals(StartCommand)) { DoPrintInstructions(); } GetAndValidateInput(); } #region Internal methods private void DoPrintInstructions() { Console.WriteLine("Please provide the URI of a log file on disk.\n"); } /// <summary> /// Reads input from console, validates it, then signals appropriate response /// (continue processing, error, success, etc.). /// </summary> private void GetAndValidateInput() { var message = Console.ReadLine(); if (!string.IsNullOrEmpty(message) && String.Equals(message, ExitCommand, StringComparison.OrdinalIgnoreCase)) { // if user typed ExitCommand, shut down the entire actor // system (allows the process to exit) Context.System.Terminate(); return; } // otherwise, just hand message off to validation actor // (by telling its actor ref) Context.ActorSelection("akka://MyActorSystem/user/fileValidationActor").Tell(message); } #endregion } }
30.454545
98
0.572537
[ "Apache-2.0" ]
michaeldeongreen/akka-bootcamp
src/Unit-1/DoThis/ConsoleReaderActor.cs
1,675
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Lclb.Cllb.Interfaces.Models { using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Microsoft.Dynamics.CRM.sharepointdocumentlocation /// </summary> public partial class MicrosoftDynamicsCRMsharepointdocumentlocation { /// <summary> /// Initializes a new instance of the /// MicrosoftDynamicsCRMsharepointdocumentlocation class. /// </summary> public MicrosoftDynamicsCRMsharepointdocumentlocation() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// MicrosoftDynamicsCRMsharepointdocumentlocation class. /// </summary> public MicrosoftDynamicsCRMsharepointdocumentlocation(string description = default(string), string _owneridValue = default(string), System.DateTimeOffset? createdon = default(System.DateTimeOffset?), int? statuscode = default(int?), string _owningbusinessunitValue = default(string), string userid = default(string), string _transactioncurrencyidValue = default(string), int? locationtype = default(int?), string _owninguserValue = default(string), string absoluteurl = default(string), int? importsequencenumber = default(int?), string _createdbyValue = default(string), string name = default(string), string _modifiedonbehalfbyValue = default(string), string _regardingobjectidValue = default(string), string _parentsiteorlocationValue = default(string), string versionnumber = default(string), int? timezoneruleversionnumber = default(int?), int? utcconversiontimezonecode = default(int?), int? statecode = default(int?), string _owningteamValue = default(string), decimal? exchangerate = default(decimal?), string sitecollectionid = default(string), System.DateTimeOffset? overriddencreatedon = default(System.DateTimeOffset?), string relativeurl = default(string), System.DateTimeOffset? modifiedon = default(System.DateTimeOffset?), string _modifiedbyValue = default(string), string sharepointdocumentlocationid = default(string), string _createdonbehalfbyValue = default(string), int? servicetype = default(int?), MicrosoftDynamicsCRMknowledgearticle regardingobjectidKnowledgearticle = default(MicrosoftDynamicsCRMknowledgearticle), MicrosoftDynamicsCRMsystemuser owninguser = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMteam owningteam = default(MicrosoftDynamicsCRMteam), MicrosoftDynamicsCRMprincipal ownerid = default(MicrosoftDynamicsCRMprincipal), MicrosoftDynamicsCRMbusinessunit owningbusinessunit = default(MicrosoftDynamicsCRMbusinessunit), MicrosoftDynamicsCRMadoxioApplication regardingobjectidAdoxioApplication = default(MicrosoftDynamicsCRMadoxioApplication), MicrosoftDynamicsCRMadoxioComplaint regardingobjectidAdoxioComplaint = default(MicrosoftDynamicsCRMadoxioComplaint), MicrosoftDynamicsCRMadoxioInvestigation regardingobjectidAdoxioInvestigation = default(MicrosoftDynamicsCRMadoxioInvestigation), MicrosoftDynamicsCRMadoxioLegalentity regardingobjectidAdoxioLegalentity = default(MicrosoftDynamicsCRMadoxioLegalentity), MicrosoftDynamicsCRMadoxioPersonalhistorysummary regardingobjectidAdoxioPersonalhistorysummary = default(MicrosoftDynamicsCRMadoxioPersonalhistorysummary), MicrosoftDynamicsCRMadoxioSpdexports regardingobjectidAdoxioSpdexports = default(MicrosoftDynamicsCRMadoxioSpdexports), MicrosoftDynamicsCRMadoxioWorker regardingobjectidAdoxioWorker = default(MicrosoftDynamicsCRMadoxioWorker), MicrosoftDynamicsCRMincident regardingobjectidIncident = default(MicrosoftDynamicsCRMincident), MicrosoftDynamicsCRMadoxioDocument regardingobjectidAdoxioDocument = default(MicrosoftDynamicsCRMadoxioDocument), MicrosoftDynamicsCRMcontact regardingobjectidContact = default(MicrosoftDynamicsCRMcontact), MicrosoftDynamicsCRMadoxioComplianceinvestigation regardingobjectidAdoxioComplianceinvestigation = default(MicrosoftDynamicsCRMadoxioComplianceinvestigation), MicrosoftDynamicsCRMadoxioLicences regardingobjectidAdoxioLicences = default(MicrosoftDynamicsCRMadoxioLicences), MicrosoftDynamicsCRMadoxioEvent regardingobjectidAdoxioEvent = default(MicrosoftDynamicsCRMadoxioEvent), MicrosoftDynamicsCRMadoxioContravention regardingobjectidAdoxioContravention = default(MicrosoftDynamicsCRMadoxioContravention), MicrosoftDynamicsCRMadoxioFederalreportexport regardingobjectidAdoxioFederalreportexport = default(MicrosoftDynamicsCRMadoxioFederalreportexport), MicrosoftDynamicsCRMadoxioLdborder regardingobjectidAdoxioLdborder = default(MicrosoftDynamicsCRMadoxioLdborder), MicrosoftDynamicsCRMadoxioEndorsement regardingobjectidAdoxioEndorsement = default(MicrosoftDynamicsCRMadoxioEndorsement), MicrosoftDynamicsCRMadoxioEnforcementaction regardingobjectidAdoxioEnforcementaction = default(MicrosoftDynamicsCRMadoxioEnforcementaction), MicrosoftDynamicsCRMaccount regardingobjectidAccount = default(MicrosoftDynamicsCRMaccount), IList<MicrosoftDynamicsCRMprincipalobjectattributeaccess> sharepointdocumentlocationPrincipalobjectattributeaccess = default(IList<MicrosoftDynamicsCRMprincipalobjectattributeaccess>), MicrosoftDynamicsCRMquote regardingobjectidQuote = default(MicrosoftDynamicsCRMquote), MicrosoftDynamicsCRMproduct regardingobjectidProduct = default(MicrosoftDynamicsCRMproduct), MicrosoftDynamicsCRMsharepointdocumentlocation parentsiteorlocationSharepointdocumentlocation = default(MicrosoftDynamicsCRMsharepointdocumentlocation), IList<MicrosoftDynamicsCRMsharepointdocumentlocation> sharepointdocumentlocationParentSharepointdocumentlocation = default(IList<MicrosoftDynamicsCRMsharepointdocumentlocation>), MicrosoftDynamicsCRMsystemuser createdonbehalfby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser modifiedby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMlead regardingobjectidLead = default(MicrosoftDynamicsCRMlead), IList<MicrosoftDynamicsCRMduplicaterecord> sharePointDocumentLocationDuplicateBaseRecord = default(IList<MicrosoftDynamicsCRMduplicaterecord>), MicrosoftDynamicsCRMsystemuser createdby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsalesliterature regardingobjectidSalesliterature = default(MicrosoftDynamicsCRMsalesliterature), MicrosoftDynamicsCRMopportunity regardingobjectidOpportunity = default(MicrosoftDynamicsCRMopportunity), MicrosoftDynamicsCRMsharepointsite parentsiteorlocationSharepointsite = default(MicrosoftDynamicsCRMsharepointsite), MicrosoftDynamicsCRMsystemuser modifiedonbehalfby = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMkbarticle regardingobjectidKbarticle = default(MicrosoftDynamicsCRMkbarticle), IList<MicrosoftDynamicsCRMduplicaterecord> sharePointDocumentLocationDuplicateMatchingRecord = default(IList<MicrosoftDynamicsCRMduplicaterecord>), IList<MicrosoftDynamicsCRMprocesssession> sharePointDocumentLocationProcessSessions = default(IList<MicrosoftDynamicsCRMprocesssession>), MicrosoftDynamicsCRMtransactioncurrency transactioncurrencyid = default(MicrosoftDynamicsCRMtransactioncurrency), IList<MicrosoftDynamicsCRMsyncerror> sharePointDocumentLocationSyncErrors = default(IList<MicrosoftDynamicsCRMsyncerror>), IList<MicrosoftDynamicsCRMasyncoperation> sharePointDocumentLocationAsyncOperations = default(IList<MicrosoftDynamicsCRMasyncoperation>)) { Description = description; this._owneridValue = _owneridValue; Createdon = createdon; Statuscode = statuscode; this._owningbusinessunitValue = _owningbusinessunitValue; Userid = userid; this._transactioncurrencyidValue = _transactioncurrencyidValue; Locationtype = locationtype; this._owninguserValue = _owninguserValue; Absoluteurl = absoluteurl; Importsequencenumber = importsequencenumber; this._createdbyValue = _createdbyValue; Name = name; this._modifiedonbehalfbyValue = _modifiedonbehalfbyValue; this._regardingobjectidValue = _regardingobjectidValue; this._parentsiteorlocationValue = _parentsiteorlocationValue; Versionnumber = versionnumber; Timezoneruleversionnumber = timezoneruleversionnumber; Utcconversiontimezonecode = utcconversiontimezonecode; Statecode = statecode; this._owningteamValue = _owningteamValue; Exchangerate = exchangerate; Sitecollectionid = sitecollectionid; Overriddencreatedon = overriddencreatedon; Relativeurl = relativeurl; Modifiedon = modifiedon; this._modifiedbyValue = _modifiedbyValue; Sharepointdocumentlocationid = sharepointdocumentlocationid; this._createdonbehalfbyValue = _createdonbehalfbyValue; Servicetype = servicetype; RegardingobjectidKnowledgearticle = regardingobjectidKnowledgearticle; Owninguser = owninguser; Owningteam = owningteam; Ownerid = ownerid; Owningbusinessunit = owningbusinessunit; RegardingobjectidAdoxioApplication = regardingobjectidAdoxioApplication; RegardingobjectidAdoxioComplaint = regardingobjectidAdoxioComplaint; RegardingobjectidAdoxioInvestigation = regardingobjectidAdoxioInvestigation; RegardingobjectidAdoxioLegalentity = regardingobjectidAdoxioLegalentity; RegardingobjectidAdoxioPersonalhistorysummary = regardingobjectidAdoxioPersonalhistorysummary; RegardingobjectidAdoxioSpdexports = regardingobjectidAdoxioSpdexports; RegardingobjectidAdoxioWorker = regardingobjectidAdoxioWorker; RegardingobjectidIncident = regardingobjectidIncident; RegardingobjectidAdoxioDocument = regardingobjectidAdoxioDocument; RegardingobjectidContact = regardingobjectidContact; RegardingobjectidAdoxioComplianceinvestigation = regardingobjectidAdoxioComplianceinvestigation; RegardingobjectidAdoxioLicences = regardingobjectidAdoxioLicences; RegardingobjectidAdoxioEvent = regardingobjectidAdoxioEvent; RegardingobjectidAdoxioContravention = regardingobjectidAdoxioContravention; RegardingobjectidAdoxioFederalreportexport = regardingobjectidAdoxioFederalreportexport; RegardingobjectidAdoxioLdborder = regardingobjectidAdoxioLdborder; RegardingobjectidAdoxioEndorsement = regardingobjectidAdoxioEndorsement; RegardingobjectidAdoxioEnforcementaction = regardingobjectidAdoxioEnforcementaction; RegardingobjectidAccount = regardingobjectidAccount; SharepointdocumentlocationPrincipalobjectattributeaccess = sharepointdocumentlocationPrincipalobjectattributeaccess; RegardingobjectidQuote = regardingobjectidQuote; RegardingobjectidProduct = regardingobjectidProduct; ParentsiteorlocationSharepointdocumentlocation = parentsiteorlocationSharepointdocumentlocation; SharepointdocumentlocationParentSharepointdocumentlocation = sharepointdocumentlocationParentSharepointdocumentlocation; Createdonbehalfby = createdonbehalfby; Modifiedby = modifiedby; RegardingobjectidLead = regardingobjectidLead; SharePointDocumentLocationDuplicateBaseRecord = sharePointDocumentLocationDuplicateBaseRecord; Createdby = createdby; RegardingobjectidSalesliterature = regardingobjectidSalesliterature; RegardingobjectidOpportunity = regardingobjectidOpportunity; ParentsiteorlocationSharepointsite = parentsiteorlocationSharepointsite; Modifiedonbehalfby = modifiedonbehalfby; RegardingobjectidKbarticle = regardingobjectidKbarticle; SharePointDocumentLocationDuplicateMatchingRecord = sharePointDocumentLocationDuplicateMatchingRecord; SharePointDocumentLocationProcessSessions = sharePointDocumentLocationProcessSessions; Transactioncurrencyid = transactioncurrencyid; SharePointDocumentLocationSyncErrors = sharePointDocumentLocationSyncErrors; SharePointDocumentLocationAsyncOperations = sharePointDocumentLocationAsyncOperations; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "description")] public string Description { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_ownerid_value")] public string _owneridValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdon")] public System.DateTimeOffset? Createdon { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "statuscode")] public int? Statuscode { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_owningbusinessunit_value")] public string _owningbusinessunitValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "userid")] public string Userid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_transactioncurrencyid_value")] public string _transactioncurrencyidValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "locationtype")] public int? Locationtype { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_owninguser_value")] public string _owninguserValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "absoluteurl")] public string Absoluteurl { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "importsequencenumber")] public int? Importsequencenumber { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_createdby_value")] public string _createdbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_modifiedonbehalfby_value")] public string _modifiedonbehalfbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_regardingobjectid_value")] public string _regardingobjectidValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_parentsiteorlocation_value")] public string _parentsiteorlocationValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "versionnumber")] public string Versionnumber { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "timezoneruleversionnumber")] public int? Timezoneruleversionnumber { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "utcconversiontimezonecode")] public int? Utcconversiontimezonecode { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "statecode")] public int? Statecode { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_owningteam_value")] public string _owningteamValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "exchangerate")] public decimal? Exchangerate { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "sitecollectionid")] public string Sitecollectionid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "overriddencreatedon")] public System.DateTimeOffset? Overriddencreatedon { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "relativeurl")] public string Relativeurl { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedon")] public System.DateTimeOffset? Modifiedon { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_modifiedby_value")] public string _modifiedbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "sharepointdocumentlocationid")] public string Sharepointdocumentlocationid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "_createdonbehalfby_value")] public string _createdonbehalfbyValue { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "servicetype")] public int? Servicetype { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_knowledgearticle")] public MicrosoftDynamicsCRMknowledgearticle RegardingobjectidKnowledgearticle { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "owninguser")] public MicrosoftDynamicsCRMsystemuser Owninguser { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "owningteam")] public MicrosoftDynamicsCRMteam Owningteam { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "ownerid")] public MicrosoftDynamicsCRMprincipal Ownerid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "owningbusinessunit")] public MicrosoftDynamicsCRMbusinessunit Owningbusinessunit { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_adoxio_application")] public MicrosoftDynamicsCRMadoxioApplication RegardingobjectidAdoxioApplication { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_adoxio_complaint")] public MicrosoftDynamicsCRMadoxioComplaint RegardingobjectidAdoxioComplaint { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_adoxio_investigation")] public MicrosoftDynamicsCRMadoxioInvestigation RegardingobjectidAdoxioInvestigation { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_adoxio_legalentity")] public MicrosoftDynamicsCRMadoxioLegalentity RegardingobjectidAdoxioLegalentity { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_adoxio_personalhistorysummary")] public MicrosoftDynamicsCRMadoxioPersonalhistorysummary RegardingobjectidAdoxioPersonalhistorysummary { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_adoxio_spdexports")] public MicrosoftDynamicsCRMadoxioSpdexports RegardingobjectidAdoxioSpdexports { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_adoxio_worker")] public MicrosoftDynamicsCRMadoxioWorker RegardingobjectidAdoxioWorker { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_incident")] public MicrosoftDynamicsCRMincident RegardingobjectidIncident { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_adoxio_document")] public MicrosoftDynamicsCRMadoxioDocument RegardingobjectidAdoxioDocument { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_contact")] public MicrosoftDynamicsCRMcontact RegardingobjectidContact { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_adoxio_complianceinvestigation")] public MicrosoftDynamicsCRMadoxioComplianceinvestigation RegardingobjectidAdoxioComplianceinvestigation { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_adoxio_licences")] public MicrosoftDynamicsCRMadoxioLicences RegardingobjectidAdoxioLicences { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_adoxio_event")] public MicrosoftDynamicsCRMadoxioEvent RegardingobjectidAdoxioEvent { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_adoxio_contravention")] public MicrosoftDynamicsCRMadoxioContravention RegardingobjectidAdoxioContravention { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_adoxio_federalreportexport")] public MicrosoftDynamicsCRMadoxioFederalreportexport RegardingobjectidAdoxioFederalreportexport { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_adoxio_ldborder")] public MicrosoftDynamicsCRMadoxioLdborder RegardingobjectidAdoxioLdborder { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_adoxio_endorsement")] public MicrosoftDynamicsCRMadoxioEndorsement RegardingobjectidAdoxioEndorsement { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_adoxio_enforcementaction")] public MicrosoftDynamicsCRMadoxioEnforcementaction RegardingobjectidAdoxioEnforcementaction { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_account")] public MicrosoftDynamicsCRMaccount RegardingobjectidAccount { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "sharepointdocumentlocation_principalobjectattributeaccess")] public IList<MicrosoftDynamicsCRMprincipalobjectattributeaccess> SharepointdocumentlocationPrincipalobjectattributeaccess { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_quote")] public MicrosoftDynamicsCRMquote RegardingobjectidQuote { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_product")] public MicrosoftDynamicsCRMproduct RegardingobjectidProduct { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "parentsiteorlocation_sharepointdocumentlocation")] public MicrosoftDynamicsCRMsharepointdocumentlocation ParentsiteorlocationSharepointdocumentlocation { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "sharepointdocumentlocation_parent_sharepointdocumentlocation")] public IList<MicrosoftDynamicsCRMsharepointdocumentlocation> SharepointdocumentlocationParentSharepointdocumentlocation { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdonbehalfby")] public MicrosoftDynamicsCRMsystemuser Createdonbehalfby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedby")] public MicrosoftDynamicsCRMsystemuser Modifiedby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_lead")] public MicrosoftDynamicsCRMlead RegardingobjectidLead { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "SharePointDocumentLocation_DuplicateBaseRecord")] public IList<MicrosoftDynamicsCRMduplicaterecord> SharePointDocumentLocationDuplicateBaseRecord { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "createdby")] public MicrosoftDynamicsCRMsystemuser Createdby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_salesliterature")] public MicrosoftDynamicsCRMsalesliterature RegardingobjectidSalesliterature { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_opportunity")] public MicrosoftDynamicsCRMopportunity RegardingobjectidOpportunity { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "parentsiteorlocation_sharepointsite")] public MicrosoftDynamicsCRMsharepointsite ParentsiteorlocationSharepointsite { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "modifiedonbehalfby")] public MicrosoftDynamicsCRMsystemuser Modifiedonbehalfby { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "regardingobjectid_kbarticle")] public MicrosoftDynamicsCRMkbarticle RegardingobjectidKbarticle { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "SharePointDocumentLocation_DuplicateMatchingRecord")] public IList<MicrosoftDynamicsCRMduplicaterecord> SharePointDocumentLocationDuplicateMatchingRecord { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "SharePointDocumentLocation_ProcessSessions")] public IList<MicrosoftDynamicsCRMprocesssession> SharePointDocumentLocationProcessSessions { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "transactioncurrencyid")] public MicrosoftDynamicsCRMtransactioncurrency Transactioncurrencyid { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "SharePointDocumentLocation_SyncErrors")] public IList<MicrosoftDynamicsCRMsyncerror> SharePointDocumentLocationSyncErrors { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "SharePointDocumentLocation_AsyncOperations")] public IList<MicrosoftDynamicsCRMasyncoperation> SharePointDocumentLocationAsyncOperations { get; set; } } }
55.39959
6,565
0.722841
[ "Apache-2.0" ]
brianorwhatever/jag-lcrb-carla-public
cllc-interfaces/Dynamics-Autorest/Models/MicrosoftDynamicsCRMsharepointdocumentlocation.cs
27,035
C#
using MyOnlineShop.Common.ViewModels.ShoppingCarts; using Refit; using System.Threading.Tasks; namespace MyOnlineShop.WebMVC.Services.ShoppingCart { public interface IShoppingCartService { [Get("/ShoppingCart/Count/{userId}")] Task<int> GetCartItemsCount([Query] string userId); [Get("/ShoppingCart/{userId}")] Task<ShoppingCartViewModel> GetShoppingCart(string userId); [Post("/ShoppingCart")] Task AddToCart([Query] string userId, [Body] CartItemViewModel cartItemViewModel); [Post("/ShoppingCart/Clear/{userId}")] Task Clear([Body] string userId); [Post("/ShoppingCart/Remove/{productId}/{userId}")] Task RemoveItem([Query] int productId, [Query] string userId); } }
30.72
90
0.682292
[ "MIT" ]
DimchoLakov/Architecture-Of-ASP-NET-Core-Microservices-Apps
MyOnlineShop/MyOnlineShop.WebMVC/Services/ShoppingCart/IShoppingCartService.cs
770
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. namespace Microsoft.Psi.Components { using Microsoft.Psi.Common; using Microsoft.Psi.Serialization; /// <summary> /// Deserializer optimized for streaming scenarios, where buffers and instances can be cached. /// </summary> /// <typeparam name="T">The type of messages to serialize.</typeparam> public sealed class DeserializerComponent<T> : ConsumerProducer<Message<BufferReader>, T> { private readonly SerializationContext context; private readonly KnownSerializers serializers; private readonly SerializationHandler<T> handler; private T reusableInstance; /// <summary> /// Initializes a new instance of the <see cref="DeserializerComponent{T}"/> class. /// </summary> /// <param name="pipeline">The pipeline to attach to.</param> /// <param name="serializers">A set of known serializers, or KnownSerializers.Default.</param> /// <param name="reusableInstance">An instance of type T to use as a deserialization buffer, or null / default(T) to let the component allocate one.</param> public DeserializerComponent(Pipeline pipeline, KnownSerializers serializers, T reusableInstance) : base(pipeline) { this.serializers = serializers; this.context = new SerializationContext(this.serializers); this.handler = this.serializers.GetHandler<T>(); this.reusableInstance = reusableInstance; } /// <summary> /// Deserializes and instance from the specified reader. /// </summary> /// <param name="msg">The byte data to deserialize.</param> /// <param name="envelope">The envelope of the message.</param> protected override void Receive(Message<BufferReader> msg, Envelope envelope) { // don't read unless there are active subscribers this.handler.Deserialize(msg.Data, ref this.reusableInstance, this.context); this.context.Reset(); this.Out.Deliver(this.reusableInstance, msg.Envelope); } } }
45.877551
165
0.647242
[ "MIT" ]
Bhaskers-Blu-Org2/psi
Sources/Runtime/Microsoft.Psi/Components/DeserializerComponent.cs
2,250
C#
using System; using System.Collections.Generic; using System.Linq; using Delve.Models.Expressions; namespace Delve.Models.Validation { internal class ValidationRules { private readonly IList<IValidationRule> _rules = new List<IValidationRule>(); public ValidationRules(IValidationRule rule, string key) { AddRule(rule, key); } public void AddRule(IValidationRule rule, string key) { var type = rule.ValidationType; if (_rules.Select(x => x.ValidationType).Contains(type)) { throw new InvalidValidationBuilderException($"Invalid rule definition of key: '{key}'." + $"Cannot define two equal ValidationRules on same key."); } _rules.Add(rule); } public IValidationRule ValidateExpression(ValidationType type, IExpression exp) { CheckForValidationType(type, exp.Key); return _rules.SingleOrDefault(x => x.ValidationType == type).ValidateExpression(exp); } public Type GetResultType(ValidationType type, string key) { CheckForValidationType(type, key); return _rules.SingleOrDefault(x => x.ValidationType == type).ResultType; } private void CheckForValidationType(ValidationType type, string key) { if (!_rules.Select(x => x.ValidationType).Contains(type)) { throw new InvalidQueryException($"Type: '{type}' has not been registered under key: '{key}'"); } } } }
32.705882
117
0.588729
[ "MIT" ]
bbartels/Delve
Source/Delve/Models/Validation/ValidationRules.cs
1,670
C#
using System; using Microsoft.Extensions.Configuration; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.Hosting; using Adnc.Application.Shared.RpcServices; using Adnc.WebApi.Shared; namespace Microsoft.Extensions.DependencyInjection { public static class ServiceCollectionExtension { /// <summary> /// 统一注册Adnc.Webpi通用服务 /// </summary> /// <typeparam name="TPermissionHandler"></typeparam> /// <param name="services"></param> /// <param name="configuration"></param> /// <param name="environment"></param> /// <param name="serviceInfo"></param> /// <param name="completedExecute"></param> /// <returns></returns> public static IServiceCollection AddAdncServices<TPermissionHandler>(this IServiceCollection services , IConfiguration configuration , IWebHostEnvironment environment , ServiceInfo serviceInfo , Action<SharedServicesRegistration> completedExecute = null) where TPermissionHandler : PermissionHandler { services.AddSingleton(serviceInfo); services.AddHttpContextAccessor(); services.AddMemoryCache(); var _srvRegistration = new SharedServicesRegistration(configuration, services, environment, serviceInfo); _srvRegistration.Configure(); _srvRegistration.AddControllers(); _srvRegistration.AddJWTAuthentication(); _srvRegistration.AddAuthorization<TPermissionHandler>(); _srvRegistration.AddCors(); _srvRegistration.AddHealthChecks(); _srvRegistration.AddEfCoreContext(); _srvRegistration.AddMongoContext(); _srvRegistration.AddCaching(); _srvRegistration.AddSwaggerGen(); var policies = _srvRegistration.GenerateDefaultRefitPolicies(); var authServerAddress = (environment.IsProduction() || environment.IsStaging()) ? "adnc.usr.webapi" : "http://localhost:5010"; _srvRegistration.AddRpcService<IAuthRpcService>(authServerAddress, policies); var maintServiceAddress = (environment.IsProduction() || environment.IsStaging()) ? "adnc.maint.webapi" : "http://localhost:5020"; _srvRegistration.AddRpcService<IMaintRpcService>(maintServiceAddress, policies); completedExecute?.Invoke(_srvRegistration); return services; } } }
42.779661
142
0.672742
[ "MIT" ]
kuiningcomeon/Adnc
src/ServerApi/Services/Shared/Adnc.WebApi.Shared/Extensions/ServiceCollectionExtension.cs
2,542
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Text; using System.Threading; using System.Threading.Tasks; using Tasks; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Networking.BackgroundTransfer; using Windows.Security.Cryptography; using Windows.Security.Cryptography.Certificates; using Windows.Storage; using Windows.Storage.Streams; using Windows.System; using Windows.UI.Core; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using Windows.Web.Http; using Windows.Web.Http.Filters; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace BackgroundTaskApp { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { private IAsyncOperation<IUICommand> showOperation; public MainPage() { Debug.WriteLine(ApplicationData.Current.LocalFolder.Path); this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); SetRedditValuesFromToast(e.Parameter); } private void DisplayException(Exception ex) { var dialog = new MessageDialog(ex.ToString(), ex.Message); if (showOperation != null) { showOperation.Cancel(); } showOperation = dialog.ShowAsync(); } #region BT private DownloadOperation slowDownload; private CancellationTokenSource downloadCancellationTokenSource; public void SetRedditValuesFromToast(object parameter) { RedditItem item = new RedditItem(); string jsonString = parameter as string; if (!String.IsNullOrEmpty(jsonString)) { if (item.TryParse(jsonString)) { RedditTitleBlock.Text = item.Title; Uri uri; if (item.TryUrlToUri(out uri)) { RedditLinkButton.NavigateUri = uri; } if (item.TryPermalinkToUri(out uri)) { RedditCommentsButton.NavigateUri = uri; } } } } private async void RunBackgroundTaskCode_Click(object sender, RoutedEventArgs e) { SongProcessingTask2 task = new SongProcessingTask2(); await task.RunAsync(new TaskInstanceMock()); } private async void GetCurrentDownloads_Click(object sender, RoutedEventArgs e) { try { var downloads = await BackgroundDownloader.GetCurrentDownloadsAsync(); CurrentBlock.Text = String.Format("Count: {0}", downloads.Count); } catch (Exception ex) { DisplayException(ex); } } private async void AttachDownloads_Click(object sender, RoutedEventArgs e) { try { CurrentBlock.Text = String.Empty; IReadOnlyList<DownloadOperation> downloads = await BackgroundDownloader.GetCurrentDownloadsAsync(); foreach (var download in downloads) { AttachDownloadOperationHandles(download); } } catch (Exception ex) { DisplayException(ex); } } private void AttachDownloadOperationHandles(DownloadOperation download) { CurrentBlock.Text += String.Format( "Download {0} has status {1}.\r\n", download.Guid, download.Progress.Status); var asyncInfo = download.AttachAsync(); asyncInfo.Progress = new AsyncOperationProgressHandler<DownloadOperation, DownloadOperation>(OnAttachedDownloadProgress); asyncInfo.Completed = new AsyncOperationWithProgressCompletedHandler<DownloadOperation, DownloadOperation>(OnAttachedDownloadCompleted); } private void OnAttachedDownloadProgress(IAsyncOperationWithProgress<DownloadOperation, DownloadOperation> asyncInfo, DownloadOperation progressInfo) { string message = String.Empty; try { DownloadOperation download = asyncInfo.GetResults(); message = String.Format( "Download {0} progress with status {1}.", progressInfo.Guid, progressInfo.Progress.Status); } catch (Exception ex) { message = ex.Message; } var runAsyncInfo = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { CurrentBlock.Text += String.Format("{0}\r\n", message); }); } private void OnAttachedDownloadCompleted(IAsyncOperationWithProgress<DownloadOperation, DownloadOperation> asyncInfo, AsyncStatus asyncStatus) { string message = String.Empty; try { DownloadOperation download = asyncInfo.GetResults(); message = String.Format( "Download {0} completed with status {1}.", download.Guid, download.Progress.Status); } catch (Exception ex) { message = ex.Message; } var runAsyncInfo = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { CurrentBlock.Text += String.Format("{0}\r\n", message); }); } private BackgroundDownloader CreateDownloader() { BackgroundDownloader downloader = new BackgroundDownloader(); downloader.SetRequestHeader("Cookie", "time=" + DateTime.Now); return downloader; } private async void CreateButDoNotStartDownload_Click(object sender, RoutedEventArgs e) { BackgroundDownloader downloader = CreateDownloader(); downloader.ProxyCredential = new Windows.Security.Credentials.PasswordCredential(); //downloader.ProxyCredential.UserName = "HOLA"; Debug.WriteLine(downloader.ProxyCredential.UserName.Length); Debug.WriteLine(downloader.ProxyCredential.UserName); Debug.WriteLine(downloader.ProxyCredential.Password.Length); Debug.WriteLine(downloader.ProxyCredential.Password); IStorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("neverStarted.txt", CreationCollisionOption.GenerateUniqueName); var aDownload = downloader.CreateDownload(new Uri("http://example.com"), file); Debug.WriteLine(aDownload.Guid); } private async void Start_Click(object sender, RoutedEventArgs e) { BackgroundDownloader downloader = CreateDownloader(); try { IStorageFile file = await KnownFolders.PicturesLibrary.CreateFileAsync("downloadFile.txt", CreationCollisionOption.GenerateUniqueName); Uri uri = new Uri(UriBox.Text); slowDownload = downloader.CreateDownload(uri, file); downloadCancellationTokenSource = new CancellationTokenSource(); ProgressBlock.Text = String.Empty; StartBlock.Text = String.Format("Guid: {0}\r\nPath: {1}", slowDownload.Guid, slowDownload.ResultFile.Path); HeadersBlock.Text = String.Empty; Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(OnDownloadProgress); var task = slowDownload.StartAsync().AsTask(downloadCancellationTokenSource.Token, progressCallback); var notAwaited = task.ContinueWith(OnDownloadCompleted, slowDownload); } catch (Exception ex) { DisplayException(ex); } } public void OnDownloadProgress(DownloadOperation download) { // Keep a local copy of current progress. BackgroundDownloadProgress progress = download.Progress; var notAwiated = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ProgressBlock.Text = String.Format( "Guid: {0}\r\n{1}: {2:N0} of {3:N0}\r\nHasRestarted: {4}\r\nHasResponseChanged: {5}", download.Guid, progress.Status, progress.BytesReceived, progress.TotalBytesToReceive, progress.HasRestarted, progress.HasResponseChanged); }); } private void OnDownloadCompleted(Task<DownloadOperation> task, object arg) { DownloadOperation slowDownload = arg as DownloadOperation; // Append headers. StringBuilder builder = new StringBuilder(); ResponseInformation response = slowDownload.GetResponseInformation(); // Append Task.Status. builder.Append(String.Format("Status: {0}\r\n", task.Status)); // If server never replied, 'response' is null. if (response != null) { builder.Append(String.Format("ActualUri: {0}\r\n", response.ActualUri)); builder.Append(String.Format("StatusCode: {0}\r\n", response.StatusCode)); builder.Append(String.Format("IsResumable: {0}\r\n", response.IsResumable)); foreach (var headerPair in response.Headers) { builder.Append(String.Format("{0}: {1}\r\n", headerPair.Key, headerPair.Value)); } } // Format excpetion info. string exceptionInfo = String.Empty; if (task.Exception != null) { builder.Append(String.Format( "Exception: 0x{0:X8} {1}\r\n", task.Exception.HResult, task.Exception.Message)); } var notAwaited = Dispatcher.RunAsync(CoreDispatcherPriority.High, () => { HeadersBlock.Text = builder.ToString().Trim(); }); } private void Pause_Click(object sender, RoutedEventArgs e) { try { if (slowDownload != null) { slowDownload.Pause(); } } catch (InvalidOperationException ex) { DisplayException(ex); } } private void Resume_Click(object sender, RoutedEventArgs e) { try { if (slowDownload != null) { slowDownload.Resume(); } } catch (InvalidOperationException ex) { DisplayException(ex); } } private void Cancel_Click(object sender, RoutedEventArgs e) { if (downloadCancellationTokenSource != null) { downloadCancellationTokenSource.Cancel(); downloadCancellationTokenSource = null; } } #endregion #region HttpClient private void GetAsync_Click(object sender, RoutedEventArgs e) { DoGet(false, String.Empty, String.Empty, String.Empty); } private void IgnoreCertErrorsGetAsync_Click(object sender, RoutedEventArgs e) { DoGet(true, String.Empty, String.Empty, String.Empty); } private void ClientCertGetAsync_Click(object sender, RoutedEventArgs e) { DoGet(true, String.Empty, String.Empty, "tempClientCert"); } private void NoCacheGetAsync_Click(object sender, RoutedEventArgs e) { DoGet(false, "Cache-Control", "no-cache", string.Empty); } private void NoStoreGetAsync_Click(object sender, RoutedEventArgs e) { DoGet(false, "Cache-Control", "no-store", String.Empty); } private void OnlyIfCachedGetAsync_Click(object sender, RoutedEventArgs e) { DoGet(false, "Cache-Control", "only-if-cached", String.Empty); } private async void DoGet(bool ignoreCertErrors, string key, string value, string friendlyName) { ResponseHeadersBlock.Text = String.Empty; CertErrorsBlock.Text = String.Empty; ResponseContentBlock.Text = String.Empty; HttpRequestMessage request = null; try { request = new HttpRequestMessage( HttpMethod.Get, new Uri(UriBox2.Text)); HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter(); if (ignoreCertErrors) { filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName); filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.RevocationFailure); } if (!String.IsNullOrEmpty(friendlyName)) { CertificateQuery query = new CertificateQuery(); query.FriendlyName = friendlyName; IReadOnlyCollection<Certificate> certs = await CertificateStores.FindAllAsync(query); filter.ClientCertificate = certs.ElementAt(0); } HttpClient client = new HttpClient(filter); if (!String.IsNullOrEmpty(key)) { client.DefaultRequestHeaders.Add(key, value); } HttpResponseMessage response = await client.SendRequestAsync(request); ResponseHeadersBlock.Text = response.ReasonPhrase; ResponseContentBlock.Text = await response.Content.ReadAsStringAsync(); } catch (Exception ex) { ResponseHeadersBlock.Text = ex.ToString(); // Something like: 'Untrusted, InvalidName, RevocationFailure' CertErrorsBlock.Text = String.Join( ", ", request.TransportInformation.ServerCertificateErrors); } } #endregion #region Certs private async void InstallClientCert_Click(object sender, RoutedEventArgs e) { InstallClientCertCompleted.Visibility = Visibility.Collapsed; try { Uri uri = new Uri("ms-appx:///Assets/tempClientCert.pfx"); var file = await StorageFile.GetFileFromApplicationUriAsync(uri); IBuffer buffer = await FileIO.ReadBufferAsync(file); //byte[] bytes; //CryptographicBuffer.CopyToByteArray(buffer, out bytes); string pfxData = CryptographicBuffer.EncodeToBase64String(buffer); // UserCertificateEnrollmentManager requires 'Shared User certificates' capability. //await CertificateEnrollmentManager.UserCertificateEnrollmentManager.ImportPfxDataAsync(...); await CertificateEnrollmentManager.ImportPfxDataAsync( pfxData, String.Empty, // password ExportOption.Exportable, KeyProtectionLevel.NoConsent, InstallOptions.None, "tempClientCert"); } catch (Exception ex) { DisplayException(ex); } InstallClientCertCompleted.Visibility = Visibility.Visible; } private async void QueryCerts_Click(object sender, RoutedEventArgs e) { QueryCertsCompleted.Visibility = Visibility.Collapsed; try { IReadOnlyCollection<Certificate> certs = await CertificateStores.FindAllAsync(); StringBuilder builder = new StringBuilder(); // Append count. builder.AppendFormat("Count: {0}\r\n", certs.Count); foreach (var cert in certs) { builder.Append("--------------------\r\n"); builder.AppendFormat("EnhancedKeyUsages: {0}\r\n", String.Join(", ", cert.EnhancedKeyUsages)); builder.AppendFormat("FriendlyName: {0}\r\n", cert.FriendlyName); builder.AppendFormat("HasPrivateKey: {0}\r\n", cert.HasPrivateKey); builder.AppendFormat("IsStronglyProtected: {0}\r\n", cert.IsStronglyProtected); builder.AppendFormat("Issuer: {0}\r\n", cert.Issuer); builder.AppendFormat("SerialNumber: {0}\r\n", BitConverter.ToString(cert.SerialNumber)); builder.AppendFormat("Subject: {0}\r\n", cert.Subject); builder.AppendFormat("ValidFrom: {0}\r\n", cert.ValidFrom); builder.AppendFormat("ValidTo: {0}\r\n", cert.ValidTo); string thumbprint = CryptographicBuffer.EncodeToHexString(CryptographicBuffer.CreateFromByteArray(cert.GetHashValue())); builder.AppendFormat("Thumbprint: {0}\r\n", thumbprint); } CertsBlock.Text = builder.ToString(); } catch (Exception ex) { DisplayException(ex); } QueryCertsCompleted.Visibility = Visibility.Visible; } private async void DeleteCerts_Click(object sender, RoutedEventArgs e) { DeleteCertsCompleted.Visibility = Visibility.Collapsed; try { IReadOnlyCollection<Certificate> certs = await CertificateStores.FindAllAsync(); StringBuilder builder = new StringBuilder(); // Append count. builder.AppendFormat("Count: {0}\r\n", certs.Count); foreach (var cert in certs) { builder.Append("--------------------\r\n"); builder.AppendFormat("Issuer: {0}\r\n", cert.Issuer); builder.AppendFormat("Subject: {0}\r\n", cert.Subject); string thumbprint = CryptographicBuffer.EncodeToHexString(CryptographicBuffer.CreateFromByteArray(cert.GetHashValue())); builder.AppendFormat("Thumbprint: {0}\r\n", thumbprint); // Not working: CertificateStores.IntermediateCertificationAuthorities.Delete(cert); } CertsBlock.Text = builder.ToString(); } catch (Exception ex) { DisplayException(ex); } DeleteCertsCompleted.Visibility = Visibility.Visible; } #endregion } }
37.893458
157
0.555073
[ "MIT" ]
kiewic/Projects
BackgroundTaskApp/BackgroundTaskApp/MainPage.xaml.cs
20,275
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlotMenu : MonoBehaviour { private Vector2 plotMenuShow; private Vector2 plotMenuHide; private Vector2 quickReapShow; private Vector2 quickReapHide; private Vector2 characterMenuShow; private Vector2 characterMenuHide; public RectTransform GUITransform; public GameObject quickReapButton; public GameObject characterMenu; // Use this for initialization void Start() { plotMenuShow = this.GetComponent<RectTransform>().anchoredPosition; plotMenuHide = new Vector2(plotMenuShow.x, plotMenuShow.y - GUITransform.rect.height); quickReapShow = quickReapButton.GetComponent<RectTransform>().anchoredPosition; quickReapHide = new Vector2(quickReapShow.x, quickReapShow.y - GUITransform.rect.height); characterMenuShow = characterMenu.GetComponent<RectTransform>().anchoredPosition; characterMenuHide = new Vector2(characterMenuShow.x, characterMenuShow.y - GUITransform.rect.height); this.GetComponent<RectTransform>().anchoredPosition = plotMenuHide; } // Update is called once per frame void Update() { } public void ShowMenu() { this.GetComponent<RectTransform>().anchoredPosition = plotMenuShow; quickReapButton.GetComponent<RectTransform>().anchoredPosition = quickReapHide; characterMenu.GetComponent<RectTransform>().anchoredPosition = characterMenuHide; } public void HideMenu() { this.GetComponent<RectTransform>().anchoredPosition = plotMenuHide; quickReapButton.GetComponent<RectTransform>().anchoredPosition = quickReapShow; characterMenu.GetComponent<RectTransform>().anchoredPosition = characterMenuShow; } }
32.927273
109
0.739371
[ "MIT" ]
JacobusRoos/CasualGame2
CasualGame2/Assets/Scripts/PlotMenu.cs
1,813
C#
using Microsoft.Bot.Builder; using Microsoft.Bot.Connector.Authentication; using Microsoft.Bot.Schema; using Microsoft.Bot.Schema.Teams; using Microsoft.Graph; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace FetchGroupChatMessagesWithRSC.helper { public class GetChatHelper { // Get groupchat message public static async Task<IChatMessagesCollectionPage> GetGroupChatMessage(ITurnContext turnContext, TokenResponse tokenResponse, string Chatid) { if (turnContext == null) { throw new ArgumentNullException(nameof(turnContext)); } if (tokenResponse == null) { throw new ArgumentNullException(nameof(tokenResponse)); } try { var client = new SimpleGraphClient(tokenResponse.Token); var messages = await client.GetGroupChatMessages(Chatid); return messages; } catch (ServiceException ex) { throw ex; } } // Send archive messages file to user. public static async Task SendGroupChatMessage(ITurnContext turnContext, long fileSize,string microsoftAppId, string microsoftAppPassword, CancellationToken cancellationToken) { if (turnContext == null) { throw new ArgumentNullException(nameof(turnContext)); } try { string filename = "chat.txt"; var member = new ChannelAccount { AadObjectId = turnContext.Activity.From.AadObjectId, Name = turnContext.Activity.From.Name, Id = turnContext.Activity.From.Id }; ConversationReference conversationReference = null; var conversationParameters = new ConversationParameters { IsGroup = false, Bot = turnContext.Activity.Recipient, Members = new ChannelAccount[] { member }, TenantId = turnContext.Activity.Conversation.TenantId, }; var credentials = new MicrosoftAppCredentials(microsoftAppId, microsoftAppPassword); var serviceUrl = turnContext.Activity.ServiceUrl; // Creates a conversation on the specified groupchat and send file consent card on that conversation. await ((BotFrameworkAdapter)turnContext.Adapter).CreateConversationAsync( turnContext.Activity.ChannelId, serviceUrl, credentials, conversationParameters, async (conversationTurnContext, conversationCancellationToken) => { conversationReference = conversationTurnContext.Activity.GetConversationReference(); await ((BotFrameworkAdapter)turnContext.Adapter).ContinueConversationAsync( microsoftAppId, conversationReference, async (conversationContext, conversationCancellation) => { var replyActivity = SendFileCardAsync(turnContext, filename, fileSize); await conversationContext.SendActivityAsync(replyActivity, conversationCancellation); }, cancellationToken); }, cancellationToken); } catch (ServiceException ex) { throw ex; } } // Send consent card to user. private static Activity SendFileCardAsync(ITurnContext turnContext, string filename, long filesize) { var consentContext = new Dictionary<string, string> { { "filename", filename }, }; var fileCard = new FileConsentCard { Description = "This is the archive chat file I want to send you", SizeInBytes = filesize, AcceptContext = consentContext, DeclineContext = consentContext, }; var asAttachment = new Microsoft.Bot.Schema.Attachment { Content = fileCard, ContentType = FileConsentCard.ContentType, Name = filename, }; var replyActivity = turnContext.Activity.CreateReply(); replyActivity.Attachments = new List<Microsoft.Bot.Schema.Attachment>() { asAttachment }; return replyActivity; } } }
38.76
183
0.55872
[ "MIT" ]
AbhijeetThakur-msft/Microsoft-Teams-Samples
samples/bot-archive-groupchat-messages/csharp/FetchGroupChatMessages/helper/GetChatHelper.cs
4,847
C#
using System; using System.Collections.Generic; using System.Linq; using QFJH.DataStruct; using static System.Math; namespace QFJH.Algorithm { /// <summary> /// 后方交汇 /// </summary> public class BackMatch { #region 后方交会公开属性 /// <summary> /// 是否计算过了 /// </summary> public bool HasProcessed { get; private set; } /// <summary> /// S在地面摄影坐标系中的X坐标 /// </summary> public double Xs { get; private set; } /// <summary> /// S在地面摄影坐标系中的Y坐标 /// </summary> public double Ys { get; private set; } /// <summary> /// S在地面摄影坐标系中的Z坐标 /// </summary> public double Zs { get; private set; } /// <summary> /// 航向倾角 /// </summary> public double p { get; private set; } /// <summary> /// 旁向倾角 /// </summary> public double w { get; private set; } /// <summary> /// 像片旋角 /// </summary> public double k { get; private set; } /// <summary> /// 航高(m) /// </summary> public double FlightHeight { get; private set; } /// <summary> /// 比例尺(m) /// </summary> public double M { get; private set; } /// <summary> /// 迭代次数 /// </summary> public int ItCount { get; private set; } #endregion private readonly double _l0, _h0; private double _limits = 0.001; private readonly List<Dictionary<string, double>> _existMatch = new List<Dictionary<string, double>>(); private readonly CameraPara _camData; /// <summary> /// 设置限差 /// </summary> public void SetLimit(double a) { this._limits = a; } public double GetLimit() { return this._limits; } /// <summary> /// 返回计算用的字典,用于数据保存(临时添加) /// </summary> public List<Dictionary<string, double>> GetDictForSave() { return this._existMatch; } /// <summary> /// 后方交会处理 /// </summary> /// <param name="data">匹配线数据</param> /// <param name="cam">相机参数</param> /// <param name="dir">左影像或者右影像</param> public BackMatch(List<DataList> data, CameraPara cam, string dir) { if (data.Count < 4) throw new FormatException("进行单张像片的空间后方交会,至少应有三个已知三维坐标的地面控制点!"); this.HasProcessed = false; this._camData = cam; // PPT:4-1.P9 _l0 = (_camData.WidthPix - 1) / 2.0 + _camData.MainPosX / _camData.PixSize; _h0 = (_camData.HeightPix - 1) / 2.0 + _camData.MainPosY / _camData.PixSize; MakeMatchList(data, dir); } /// <summary> /// 处理计算过程 /// </summary> public void Process() { CalcScale(); InitialOuter(); MainLoop(); this.HasProcessed = true; } /// <summary> /// 计算全图比例尺 /// </summary> private void CalcScale() { List<double> scale = new List<double>(); for (int i = 0; i < _existMatch.Count; i++) { for (int j = i + 1; j < _existMatch.Count; j++) { double x1 = _existMatch[i]["x"], y1 = _existMatch[i]["y"], x2 = _existMatch[j]["x"], y2 = _existMatch[j]["y"], xa1 = _existMatch[i]["xa"], ya1 = _existMatch[i]["ya"], xa2 = _existMatch[j]["xa"], ya2 = _existMatch[j]["ya"]; // 真实单位是m,相片单位是mm double lenReal = Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)), lenImg = Sqrt((xa1 - xa2) * (xa1 - xa2) + (ya1 - ya2) * (ya1 - ya2)); scale.Add(lenReal / (lenImg / 1000)); } } this.M = scale.Average(); //米 this.FlightHeight = _camData.f / 1000 * this.M; } /// <summary> /// 初始化外方位元素 /// </summary> private void InitialOuter() { this.Zs = this.FlightHeight; this.p = 0; this.w = 0; this.k = 0; int count = _existMatch.Count; double xs = 0, ys = 0; for (int i = 0; i < count; i++) { xs += _existMatch[i]["x"]; ys += _existMatch[i]["y"]; } this.Xs = xs / count; this.Ys = ys / count; } /// <summary> /// 主迭代计算 /// </summary> private void MainLoop() { #region 需要的变量申明 this.ItCount = 0; double[] xNear = new double[_existMatch.Count], yNear = new double[_existMatch.Count], zNear = new double[_existMatch.Count]; Matrix[] errA = new Matrix[_existMatch.Count], errL = new Matrix[_existMatch.Count]; double[,] dFinal = null; #endregion do { var R = MatrixR(); GXFC(R, xNear, yNear, zNear); ErrorEqu(R, xNear, yNear, zNear, errA, errL); dFinal = SolveEqu(errA, errL); this.Xs += dFinal[0, 0]; this.Ys += dFinal[1, 0]; this.Zs += dFinal[2, 0]; this.p += dFinal[3, 0]; this.w += dFinal[4, 0]; this.k += dFinal[5, 0]; this.ItCount++; } while (!HasLimited(dFinal)); } /// <summary> /// 解方程,求出本次迭代的外方位元素 /// </summary> private double[,] SolveEqu(Matrix[] aMat, Matrix[] lMat) { Matrix mergeA = MergeMatrix(aMat), mergeL = MergeMatrix(lMat); var AT = MatrixOperation.MatrixTrans(mergeA); var final = (1 / (AT * mergeA)) * AT * mergeL; // 结果一定是6*1的矩阵 return final.Data; } /// <summary> /// 合并矩阵 /// </summary> private Matrix MergeMatrix(Matrix[] aMat) { int count = aMat.Length, rowCount = aMat[0].Data.GetLength(0), colCount = aMat[0].Data.GetLength(1); double[,] tmp = new double[rowCount * count, colCount]; for (int i = 0; i < count; i++) { var A = aMat[i].Data; for (int j = 0; j < colCount; j++) { for (int l = 0; l < rowCount; l++) { tmp[rowCount * i + l, j] = A[l, j]; } } } return new Matrix(tmp, true); } /// <summary> /// 计算误差方程式(A与L) /// </summary> private void ErrorEqu(Matrix r, double[] xGx, double[] yGx, double[] zGx, Matrix[] A, Matrix[] L) { var R = r.Data; var f = this._camData.f; for (int i = 0; i < _existMatch.Count; i++) { double[,] tmpA = new double[2, 6], tmpL = new double[2, 1]; double x = _existMatch[i]["xa"], y = _existMatch[i]["ya"]; tmpA[0, 0] = (R[0, 0] * f + R[0, 2] * x) / zGx[i]; tmpA[0, 1] = (R[1, 0] * f + R[1, 2] * x) / zGx[i]; tmpA[0, 2] = (R[2, 0] * f + R[2, 2] * x) / zGx[i]; tmpA[0, 3] = y * Sin(this.w) - ((x / f) * (x * Cos(this.k) - y * Sin(this.k)) + f * Cos(this.k)) * Cos(this.w); tmpA[0, 4] = -f * Sin(this.k) - (x / f) * (x * Sin(this.k) + y * Cos(this.k)); tmpA[0, 5] = y; tmpA[1, 0] = (R[0, 1] * f + R[0, 2] * y) / zGx[i]; tmpA[1, 1] = (R[1, 1] * f + R[1, 2] * y) / zGx[i]; tmpA[1, 2] = (R[2, 1] * f + R[2, 2] * y) / zGx[i]; tmpA[1, 3] = -x * Sin(this.w) - ((y / f) * (x * Cos(this.k) - y * Sin(this.k)) - f * Sin(this.k)) * Cos(this.w); tmpA[1, 4] = -f * Cos(this.k) - (y / f) * (x * Sin(this.k) + y * Cos(this.k)); tmpA[1, 5] = -x; tmpL[0, 0] = x - xGx[i]; tmpL[1, 0] = y - yGx[i]; A[i] = new Matrix(tmpA, true); L[i] = new Matrix(tmpL, true); } } /// <summary> /// 共线方程X,Y解算 /// </summary> private void GXFC(Matrix r, double[] x, double[] y, double[] z) { var R = r.Data; var f = this._camData.f; for (int i = 0; i < _existMatch.Count; i++) { double dX = (_existMatch[i]["x"] - this.Xs), dY = (_existMatch[i]["y"] - this.Ys), dZ = (_existMatch[i]["z"] - this.Zs); z[i] = R[0, 2] * dX + R[1, 2] * dY + R[2, 2] * dZ; x[i] = -f * (R[0, 0] * dX + R[1, 0] * dY + R[2, 0] * dZ) / z[i]; y[i] = -f * (R[0, 1] * dX + R[1, 1] * dY + R[2, 1] * dZ) / z[i]; } } /// <summary> /// 计算旋转矩阵R /// </summary> /// <returns>R阵</returns> private Matrix MatrixR() { double[,] Rp = { {Cos(this.p), 0, -Sin(this.p)}, {0, 1, 0}, {Sin(this.p), 0, Cos(this.p)} }, Rw = { {1, 0, 0}, {0, Cos(this.w), -Sin(this.w)}, {0, Sin(this.w), Cos(this.w)} }, Rk = { {Cos(this.k), -Sin(this.k), 0}, {Sin(this.k), Cos(this.k), 0}, {0, 0, 1} }; Matrix mp = new Matrix(Rp, true), mw = new Matrix(Rw, true), mk = new Matrix(Rk, true); return mp * mw * mk; } /// <summary> /// 是否收敛,以结束计算 /// </summary> private bool HasLimited(double[,] final) { if (this.ItCount > 500000) throw new Exception("迭代超过50W次无结果,该方程很可能不收敛"); for (int i = 0; i < final.GetLength(0); i++) { if (Abs(final[i, 0]) > _limits) { return false; } } return true; } /// <summary> /// 影像上任一像点a(h行,l列)处的像平面坐标(xa, ya) /// </summary> private void RowColtoImgPaneCoord(double h, double l, out double xa, out double ya) { xa = (l - _l0) * _camData.PixSize; ya = (_h0 - h) * _camData.PixSize; } private void MakeMatchList(List<DataList> data, string dir) { var s = dir.ToLower(); foreach (var t in data) { var tmp = new Dictionary<string, double> { {"ID", t.PointNumber}, {"x", t.X}, {"y", t.Y}, {"z", t.Z} }; double xa, ya; switch (s) { case "left": tmp.Add("col", t.LeftColNumber); tmp.Add("row", t.LeftRowNumber); RowColtoImgPaneCoord(t.LeftRowNumber, t.LeftColNumber, out xa, out ya); break; case "right": tmp.Add("col", t.RightColNumber); tmp.Add("row",t.RightRowNumber); RowColtoImgPaneCoord(t.RightRowNumber, t.RightColNumber, out xa, out ya); break; default: throw new Exception("数据格式错误"); } tmp.Add("xa", xa); tmp.Add("ya", ya); _existMatch.Add(tmp); } } } }
31.098734
128
0.395718
[ "Apache-2.0" ]
bestYou/Photogrammetry
Photogrammetry/QFJH/Algorithm/BackMatch.cs
12,890
C#
using System; using System.Collections.Generic; using System.Net.Mime; using Microsoft.OpenApi.Models; using Xunit; namespace Atc.OpenApi.Tests.XUnitTestData { public static class TestMemberDataForOpenApiMediaTypeExtensions { public static TheoryData<string, IDictionary<string, OpenApiMediaType>> GetSchemaItemData => new TheoryData<string, IDictionary<string, OpenApiMediaType>> { { OpenApiDataTypeConstants.Array, CreateContent(OpenApiDataTypeConstants.Array) }, }; public static TheoryData<string, IDictionary<string, OpenApiMediaType>> GetSchemaByFirstMediaTypeItemData => new TheoryData<string, IDictionary<string, OpenApiMediaType>> { { OpenApiDataTypeConstants.Array, CreateMultipleContents(OpenApiDataTypeConstants.Array, OpenApiDataTypeConstants.Object) }, }; public static TheoryData<string, string, IDictionary<string, OpenApiMediaType>> GetSchemaContentTypeItemData => new TheoryData<string, string, IDictionary<string, OpenApiMediaType>> { { OpenApiDataTypeConstants.Array, MediaTypeNames.Application.Json, CreateContent(OpenApiDataTypeConstants.Array) }, }; private static IDictionary<string, OpenApiMediaType> CreateContent(string typeName) => new Dictionary<string, OpenApiMediaType>(StringComparer.Ordinal) { { MediaTypeNames.Application.Json, new OpenApiMediaType { Schema = new OpenApiSchema { Type = typeName, }, } }, }; private static IDictionary<string, OpenApiMediaType> CreateMultipleContents(string typeName1, string typeName2) => new Dictionary<string, OpenApiMediaType>(StringComparer.Ordinal) { { MediaTypeNames.Application.Json, new OpenApiMediaType { Schema = new OpenApiSchema { Type = typeName1, }, } }, { MediaTypeNames.Application.Octet, new OpenApiMediaType { Schema = new OpenApiSchema { Type = typeName2, }, } }, }; } }
38.811594
140
0.535474
[ "MIT" ]
atc-net/atc
test/Atc.OpenApi.Tests/XUnitTestData/TestMemberDataForOpenApiMediaTypeExtensions.cs
2,678
C#
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.WorkspaceServices; namespace Microsoft.CodeAnalysis.Formatting.Rules { #if MEF [ExportWorkspaceServiceFactory(typeof(IBaseIndentationFormattingRuleFactoryService), WorkspaceKind.Any)] #endif internal sealed class DefaultBaseIndentationFormattingRuleFactoryServiceFactory : IWorkspaceServiceFactory { public DefaultBaseIndentationFormattingRuleFactoryServiceFactory() { } public IWorkspaceService CreateService(IWorkspaceServiceProvider workspaceServices) { return new Factory(); } private sealed class Factory : IBaseIndentationFormattingRuleFactoryService { private readonly IFormattingRule singleton = new NoOpFormattingRule(); public bool ShouldUseBaseIndentation(Document document) { return false; } public IFormattingRule CreateRule(Document document, int position) { return singleton; } public IEnumerable<TextChange> FilterFormattedChanges(Document document, TextSpan span, IList<TextChange> changes) { return changes; } } } }
33.466667
184
0.689243
[ "ECL-2.0", "Apache-2.0" ]
binsys/roslyn_java
Src/Workspaces/Core/Formatting/Rules/DefaultBaseIndentationFormattingRuleFactoryServiceFactory.cs
1,508
C#
 namespace ProceduralMusic { public class PhaseShift : Source { private Source _src; private double _period; public PhaseShift(Source src, double period) { _src = src; _period = period; } public override float Sample(double t) { return _src.Sample(t - _period); } } }
18.238095
52
0.524804
[ "MIT" ]
Metapyziks/ProceduralMusic
ProceduralMusic/PhaseShift.cs
385
C#
using McMaster.Extensions.CommandLineUtils; using System; using System.Collections.Generic; using System.Text; namespace Ipfs.Cli { [Command("init", Description = "Initialize ipfs local configuration [WIP]")] class InitCommand : CommandBase { } }
20.384615
80
0.732075
[ "MIT" ]
sbiaudet/net-ipfs-engine
IpfsCli/Commands/InitCommand.cs
267
C#
/* * NetworkHelper.cs * * Copyright (c) 2009, Michael Schwarz (http://www.schwarz-interactive.de) * * 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. * * MS 08-03-24 initial version * MS 09-02-10 fixed MF support * */ using System; using System.Net; using System.Net.Sockets; using Socket = System.Net.Sockets.Socket; namespace MFToolkit.Net { public class NetworkHelper { public static byte[] GetMacFromString(string mac) { string[] macparts = mac.Split('-'); if (macparts.Length != 6) throw new ArgumentException("MAC address not in correct format."); byte[] bytes = new byte[6]; for (int i = 0; i < macparts.Length; i++) { int b = 0; for (int c = 0; c < 2; c++) { switch (macparts[i][1 - c]) { case '0': break; case '1': b += 1 * (int)Math.Pow(16, c); break; case '2': b += 2 * (int)Math.Pow(16, c); break; case '3': b += 3 * (int)Math.Pow(16, c); break; case '4': b += 4 * (int)Math.Pow(16, c); break; case '5': b += 5 * (int)Math.Pow(16, c); break; case '6': b += 6 * (int)Math.Pow(16, c); break; case '7': b += 7 * (int)Math.Pow(16, c); break; case '8': b += 8 * (int)Math.Pow(16, c); break; case '9': b += 9 * (int)Math.Pow(16, c); break; case 'A': b += 10 * (int)Math.Pow(16, c); break; case 'B': b += 11 * (int)Math.Pow(16, c); break; case 'C': b += 12 * (int)Math.Pow(16, c); break; case 'D': b += 13 * (int)Math.Pow(16, c); break; case 'E': b += 14 * (int)Math.Pow(16, c); break; case 'F': b += 15 * (int)Math.Pow(16, c); break; } } bytes[i] = (byte)b; } return bytes; } public static void WakeUp(byte[] mac) { using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { IPEndPoint endPoint = new IPEndPoint(new IPAddress(4294967295), 40000); // IP 255.255.255.255 socket.Connect(endPoint); byte[] packet = new byte[17 * 6]; for (int i = 0; i < 6; i++) packet[i] = 0xFF; for (int i = 1; i <= 16; i++) for (int j = 0; j < 6; j++) packet[i * 6 + j] = mac[j]; socket.Send(packet); // , SocketFlags.Broadcast); } } } }
32.572816
102
0.596423
[ "MIT" ]
MatthewJallah/NETMF-Toolkit
HTTP/Helper/NetworkHelper.cs
3,355
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Diagnostics; using System.Linq; using System.Reflection; using GeoAPI.Geometries; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Design.Internal; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Conventions; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Migrations.Design; using Microsoft.EntityFrameworkCore.Migrations.Internal; using Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.Internal; using Microsoft.EntityFrameworkCore.TestUtilities; using Microsoft.EntityFrameworkCore.ValueGeneration; using Microsoft.Extensions.DependencyInjection; using NetTopologySuite.Geometries; using Xunit; // ReSharper disable InconsistentNaming // ReSharper disable UnusedAutoPropertyAccessor.Local // ReSharper disable ClassNeverInstantiated.Local // ReSharper disable UnusedMember.Local // ReSharper disable UnusedTypeParameter namespace Microsoft.EntityFrameworkCore.Migrations { public class ModelSnapshotSqlServerTest { private class EntityWithManyProperties { public int Id { get; set; } public string String { get; set; } public byte[] Bytes { get; set; } public short Int16 { get; set; } public int Int32 { get; set; } public long Int64 { get; set; } public double Double { get; set; } public decimal Decimal { get; set; } public DateTime DateTime { get; set; } public DateTimeOffset DateTimeOffset { get; set; } public TimeSpan TimeSpan { get; set; } public float Single { get; set; } public bool Boolean { get; set; } public byte Byte { get; set; } public ushort UnsignedInt16 { get; set; } public uint UnsignedInt32 { get; set; } public ulong UnsignedInt64 { get; set; } public char Character { get; set; } public sbyte SignedByte { get; set; } public Enum64 Enum64 { get; set; } public Enum32 Enum32 { get; set; } public Enum16 Enum16 { get; set; } public Enum8 Enum8 { get; set; } public EnumU64 EnumU64 { get; set; } public EnumU32 EnumU32 { get; set; } public EnumU16 EnumU16 { get; set; } public EnumS8 EnumS8 { get; set; } public IGeometry SpatialBGeometryCollection { get; set; } public IGeometry SpatialBLineString { get; set; } public IGeometry SpatialBMultiLineString { get; set; } public IGeometry SpatialBMultiPoint{ get; set; } public IGeometry SpatialBMultiPolygon{ get; set; } public IGeometry SpatialBPoint{ get; set; } public IGeometry SpatialBPolygon{ get; set; } public GeometryCollection SpatialCGeometryCollection { get; set; } public LineString SpatialCLineString { get; set; } public MultiLineString SpatialCMultiLineString { get; set; } public MultiPoint SpatialCMultiPoint { get; set; } public MultiPolygon SpatialCMultiPolygon { get; set; } public Point SpatialCPoint { get; set; } public Polygon SpatialCPolygon { get; set; } public IGeometryCollection SpatialIGeometryCollection { get; set; } public ILineString SpatialILineString { get; set; } public IMultiLineString SpatialIMultiLineString { get; set; } public IMultiPoint SpatialIMultiPoint { get; set; } public IMultiPolygon SpatialIMultiPolygon { get; set; } public IPoint SpatialIPoint { get; set; } public IPolygon SpatialIPolygon { get; set; } } private enum Enum64 : long { SomeValue = 1 } private enum Enum32 { SomeValue = 1 } private enum Enum16 : short { SomeValue = 1 } private enum Enum8 : byte { SomeValue = 1 } private enum EnumU64 : ulong { SomeValue = 1234567890123456789UL } private enum EnumU32 : uint { SomeValue = uint.MaxValue } private enum EnumU16 : ushort { SomeValue = ushort.MaxValue } private enum EnumS8 : sbyte { SomeValue = sbyte.MinValue } private class EntityWithOneProperty { public int Id { get; set; } public EntityWithTwoProperties EntityWithTwoProperties { get; set; } } private class EntityWithTwoProperties { public int Id { get; set; } public int AlternateId { get; set; } public EntityWithOneProperty EntityWithOneProperty { get; set; } [NotMapped] public EntityWithStringKey EntityWithStringKey { get; set; } } private class EntityWithStringProperty { public int Id { get; set; } public string Name { get; set; } [NotMapped] public EntityWithOneProperty EntityWithOneProperty { get; set; } } private class EntityWithStringKey { public string Id { get; set; } public ICollection<EntityWithStringProperty> Properties { get; set; } } private class EntityWithGenericKey<TKey> { public Guid Id { get; set; } } private class EntityWithGenericProperty<TProperty> { public int Id { get; set; } public TProperty Property { get; set; } } private class BaseEntity { public int Id { get; set; } public string Discriminator { get; set; } } private class DerivedEntity : BaseEntity { public string Name { get; set; } } private class AnotherDerivedEntity : BaseEntity { public string Title { get; set; } } private class BaseType { public int Id { get; set; } public EntityWithOneProperty Navigation { get; set; } } private class DerivedType : BaseType { } private enum Days : long { Sun, Mon, Tue, Wed, Thu, Fri, Sat } private class EntityWithEnumType { public int Id { get; set; } public Days Day { get; set; } } private class EntityWithNullableEnumType { public int Id { get; set; } public Days? Day { get; set; } } private class CustomValueGenerator : ValueGenerator<int> { public override int Next(EntityEntry entry) => throw new NotImplementedException(); public override bool GeneratesTemporaryValues => false; } #region Model [Fact] public virtual void Model_annotations_are_stored_in_snapshot() { Test( builder => { builder.HasAnnotation("AnnotationName", "AnnotationValue"); }, AddBoilerPlate(@" modelBuilder .HasAnnotation(""AnnotationName"", ""AnnotationValue"") .HasAnnotation(""ChangeDetector.SkipDetectChanges"", ""true"") .HasAnnotation(""Relational:MaxIdentifierLength"", 128) .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn);"), o => { Assert.Equal(4, o.GetAnnotations().Count()); Assert.Equal("AnnotationValue", o["AnnotationName"]); }); } [Fact] public virtual void Model_default_schema_annotation_is_stored_in_snapshot_as_fluent_api() { Test( builder => { builder.HasDefaultSchema("DefaultSchema"); builder.HasAnnotation("AnnotationName", "AnnotationValue"); }, AddBoilerPlate(@" modelBuilder .HasDefaultSchema(""DefaultSchema"") .HasAnnotation(""AnnotationName"", ""AnnotationValue"") .HasAnnotation(""ChangeDetector.SkipDetectChanges"", ""true"") .HasAnnotation(""Relational:MaxIdentifierLength"", 128) .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn);"), o => { Assert.Equal(5, o.GetAnnotations().Count()); Assert.Equal("AnnotationValue", o["AnnotationName"]); Assert.Equal("DefaultSchema", o[RelationalAnnotationNames.DefaultSchema]); }); } [Fact] public virtual void Entities_are_stored_in_model_snapshot() { Test( builder => { builder.Entity<EntityWithOneProperty>().Ignore(e => e.EntityWithTwoProperties); builder.Entity<EntityWithTwoProperties>().Ignore(e => e.EntityWithOneProperty); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.HasKey(""Id""); b.ToTable(""EntityWithOneProperty""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.ToTable(""EntityWithTwoProperties""); });"), o => { Assert.Equal(2, o.GetEntityTypes().Count()); Assert.Collection( o.GetEntityTypes(), t => Assert.Equal("Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty", t.Name), t => Assert.Equal("Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties", t.Name)); }); } #endregion #region EntityType [Fact] public virtual void EntityType_annotations_are_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithOneProperty>().HasAnnotation("AnnotationName", "AnnotationValue"); builder.Ignore<EntityWithTwoProperties>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.HasKey(""Id""); b.ToTable(""EntityWithOneProperty""); b.HasAnnotation(""AnnotationName"", ""AnnotationValue""); });"), o => { Assert.Equal(2, o.GetEntityTypes().First().GetAnnotations().Count()); Assert.Equal("AnnotationValue", o.GetEntityTypes().First()["AnnotationName"]); }); } [Fact] public virtual void BaseType_is_stored_in_snapshot() { Test( builder => { builder.Entity<DerivedEntity>().HasBaseType<BaseEntity>(); builder.Entity<AnotherDerivedEntity>().HasBaseType<BaseEntity>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+BaseEntity"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>(""Discriminator"") .IsRequired(); b.HasKey(""Id""); b.ToTable(""BaseEntity""); b.HasDiscriminator<string>(""Discriminator"").HasValue(""BaseEntity""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+AnotherDerivedEntity"", b => { b.HasBaseType(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+BaseEntity""); b.Property<string>(""Title""); b.HasDiscriminator().HasValue(""AnotherDerivedEntity""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+DerivedEntity"", b => { b.HasBaseType(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+BaseEntity""); b.Property<string>(""Name""); b.HasDiscriminator().HasValue(""DerivedEntity""); });"), o => { Assert.Equal(3, o.GetEntityTypes().Count()); Assert.Collection( o.GetEntityTypes(), t => Assert.Equal("Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+AnotherDerivedEntity", t.Name), t => Assert.Equal("Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+BaseEntity", t.Name), t => Assert.Equal("Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+DerivedEntity", t.Name) ); }); } [Fact] public virtual void Discriminator_annotations_are_stored_in_snapshot() { Test( builder => { builder.Entity<DerivedEntity>().HasBaseType<BaseEntity>(); builder.Entity<AnotherDerivedEntity>().HasBaseType<BaseEntity>(); builder.Entity<BaseEntity>() .HasDiscriminator(e => e.Discriminator) .HasValue(typeof(BaseEntity), typeof(BaseEntity).Name) .HasValue(typeof(DerivedEntity), typeof(DerivedEntity).Name) .HasValue(typeof(AnotherDerivedEntity), typeof(AnotherDerivedEntity).Name); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+BaseEntity"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>(""Discriminator"") .IsRequired(); b.HasKey(""Id""); b.ToTable(""BaseEntity""); b.HasDiscriminator<string>(""Discriminator"").HasValue(""BaseEntity""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+AnotherDerivedEntity"", b => { b.HasBaseType(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+BaseEntity""); b.Property<string>(""Title""); b.HasDiscriminator().HasValue(""AnotherDerivedEntity""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+DerivedEntity"", b => { b.HasBaseType(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+BaseEntity""); b.Property<string>(""Name""); b.HasDiscriminator().HasValue(""DerivedEntity""); });"), o => { Assert.Equal("Discriminator", o.FindEntityType(typeof(BaseEntity))[RelationalAnnotationNames.DiscriminatorProperty]); Assert.Equal("BaseEntity", o.FindEntityType(typeof(BaseEntity))[RelationalAnnotationNames.DiscriminatorValue]); Assert.Equal("AnotherDerivedEntity", o.FindEntityType(typeof(AnotherDerivedEntity))[RelationalAnnotationNames.DiscriminatorValue]); Assert.Equal("DerivedEntity", o.FindEntityType(typeof(DerivedEntity))[RelationalAnnotationNames.DiscriminatorValue]); }); } [Fact] public virtual void Properties_are_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithTwoProperties>(); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.ToTable(""EntityWithTwoProperties""); });"), o => { Assert.Equal(2, o.GetEntityTypes().First().GetProperties().Count()); Assert.Collection( o.GetEntityTypes().First().GetProperties(), t => Assert.Equal("Id", t.Name), t => Assert.Equal("AlternateId", t.Name) ); }); } [Fact] public virtual void Primary_key_is_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithTwoProperties>().HasKey( t => new { t.Id, t.AlternateId }); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id""); b.Property<int>(""AlternateId""); b.HasKey(""Id"", ""AlternateId""); b.ToTable(""EntityWithTwoProperties""); });"), o => { Assert.Equal(2, o.GetEntityTypes().First().FindPrimaryKey().Properties.Count); Assert.Collection( o.GetEntityTypes().First().FindPrimaryKey().Properties, t => Assert.Equal("Id", t.Name), t => Assert.Equal("AlternateId", t.Name) ); }); } [Fact] public virtual void Alternate_keys_are_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithTwoProperties>().HasAlternateKey( t => new { t.Id, t.AlternateId }); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.HasAlternateKey(""Id"", ""AlternateId""); b.ToTable(""EntityWithTwoProperties""); });"), o => { Assert.Collection( o.GetEntityTypes().First().GetDeclaredKeys().First(k => k.Properties.Count == 2).Properties, t => Assert.Equal("Id", t.Name), t => Assert.Equal("AlternateId", t.Name) ); }); } [Fact] public virtual void Indexes_are_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithTwoProperties>().HasIndex(t => t.AlternateId); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.HasIndex(""AlternateId""); b.ToTable(""EntityWithTwoProperties""); });"), o => { Assert.Equal(1, o.GetEntityTypes().First().GetIndexes().Count()); Assert.Equal("AlternateId", o.GetEntityTypes().First().GetIndexes().First().Properties[0].Name); }); } [Fact] public virtual void Indexes_are_stored_in_snapshot_including_composite_index() { Test( builder => { builder.Entity<EntityWithTwoProperties>().HasIndex( t => new { t.Id, t.AlternateId }); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.HasIndex(""Id"", ""AlternateId""); b.ToTable(""EntityWithTwoProperties""); });"), o => { Assert.Equal(1, o.GetEntityTypes().First().GetIndexes().Count()); Assert.Collection( o.GetEntityTypes().First().GetIndexes().First().Properties, t => Assert.Equal("Id", t.Name), t => Assert.Equal("AlternateId", t.Name)); }); } [Fact] public virtual void Foreign_keys_are_stored_in_snapshot() { Test( builder => { builder .Entity<EntityWithTwoProperties>() .HasOne(e => e.EntityWithOneProperty) .WithOne(e => e.EntityWithTwoProperties) .HasForeignKey<EntityWithTwoProperties>(e => e.AlternateId); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.HasKey(""Id""); b.ToTable(""EntityWithOneProperty""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.HasIndex(""AlternateId"") .IsUnique(); b.ToTable(""EntityWithTwoProperties""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", ""EntityWithOneProperty"") .WithOne(""EntityWithTwoProperties"") .HasForeignKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", ""AlternateId"") .OnDelete(DeleteBehavior.Cascade); });"), o => { var foreignKey = o.FindEntityType(typeof(EntityWithTwoProperties)).GetForeignKeys().Single(); Assert.Equal("AlternateId", foreignKey.Properties[0].Name); Assert.Equal("EntityWithTwoProperties", foreignKey.PrincipalToDependent.Name); Assert.Equal("EntityWithOneProperty", foreignKey.DependentToPrincipal.Name); }); } [Fact] public virtual void TableName_preserved_when_generic() { IModel originalModel = null; Test( builder => { builder.Entity<EntityWithGenericKey<Guid>>(); originalModel = builder.Model; }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithGenericKey<System.Guid>"", b => { b.Property<Guid>(""Id"") .ValueGeneratedOnAdd(); b.HasKey(""Id""); b.ToTable(""EntityWithGenericKey<Guid>""); });", usingSystem: true), model => { var originalEntity = originalModel.FindEntityType(typeof(EntityWithGenericKey<Guid>)); var entity = model.FindEntityType(originalEntity.Name); Assert.NotNull(entity); Assert.Equal(originalEntity.Relational().TableName, entity.Relational().TableName); }); } [Fact] public virtual void PrimaryKey_name_preserved_when_generic() { IModel originalModel = null; Test( builder => { builder.Entity<EntityWithGenericKey<Guid>>(); originalModel = builder.Model; }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithGenericKey<System.Guid>"", b => { b.Property<Guid>(""Id"") .ValueGeneratedOnAdd(); b.HasKey(""Id""); b.ToTable(""EntityWithGenericKey<Guid>""); });", usingSystem: true), model => { var originalEntity = originalModel.FindEntityType(typeof(EntityWithGenericKey<Guid>)); var entity = model.FindEntityType(originalEntity.Name); Assert.NotNull(entity); var originalPrimaryKey = originalEntity.FindPrimaryKey(); var primaryKey = entity.FindPrimaryKey(); Assert.Equal(originalPrimaryKey.Relational().Name, primaryKey.Relational().Name); }); } [Fact] public virtual void AlternateKey_name_preserved_when_generic() { IModel originalModel = null; Test( builder => { builder.Entity<EntityWithGenericProperty<Guid>>().HasAlternateKey(e => e.Property); originalModel = builder.Model; }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithGenericProperty<System.Guid>"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<Guid>(""Property""); b.HasKey(""Id""); b.HasAlternateKey(""Property""); b.ToTable(""EntityWithGenericProperty<Guid>""); });", usingSystem: true), model => { var originalEntity = originalModel.FindEntityType(typeof(EntityWithGenericProperty<Guid>)); var entity = model.FindEntityType(originalEntity.Name); Assert.NotNull(entity); var originalAlternateKey = originalEntity.FindKey(originalEntity.FindProperty("Property")); var alternateKey = entity.FindKey(entity.FindProperty("Property")); Assert.Equal(originalAlternateKey.Relational().Name, alternateKey.Relational().Name); }); } [Fact] public virtual void Discriminator_of_enum() { Test( builder => builder.Entity<EntityWithEnumType>().HasDiscriminator(e => e.Day), AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithEnumType"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<long>(""Day""); b.HasKey(""Id""); b.ToTable(""EntityWithEnumType""); b.HasDiscriminator<long>(""Day""); });"), model => Assert.Equal(typeof(long), model.GetEntityTypes().First().Relational().DiscriminatorProperty.ClrType)); } [Fact] public virtual void Discriminator_of_enum_to_string() { Test( builder => builder.Entity<EntityWithEnumType>( x => { x.Property(e => e.Day).HasConversion<string>(); x.HasDiscriminator(e => e.Day); }), AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithEnumType"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>(""Day"") .IsRequired(); b.HasKey(""Id""); b.ToTable(""EntityWithEnumType""); b.HasDiscriminator<string>(""Day""); });"), model => { var discriminatorProperty = model.GetEntityTypes().First().Relational().DiscriminatorProperty; Assert.Equal(typeof(string), discriminatorProperty.ClrType); Assert.False(discriminatorProperty.IsNullable); }); } #endregion #region Owned types [Fact] public virtual void Owned_types_are_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithOneProperty>(b => { b.HasKey(e => e.Id).HasName("PK_Custom"); b.OwnsOne(eo => eo.EntityWithTwoProperties, eb => { eb.HasKey(e => e.AlternateId).HasName("PK_Custom"); eb.HasForeignKey(e => e.AlternateId).HasConstraintName("FK_Custom"); eb.HasOne(e => e.EntityWithOneProperty) .WithOne(e => e.EntityWithTwoProperties); eb.HasIndex(e => e.Id); eb.HasOne(e => e.EntityWithStringKey).WithOne(); eb.HasData(new EntityWithTwoProperties { AlternateId = 1, Id = -1 }); }); b.HasData(new EntityWithOneProperty { Id = 1 }); }); builder.Entity<EntityWithStringKey>(b => { b.OwnsMany(es => es.Properties, es => { es.HasOne(e => e.EntityWithOneProperty).WithOne(); }); }); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.HasKey(""Id"") .HasName(""PK_Custom""); b.ToTable(""EntityWithOneProperty""); b.HasData( new { Id = 1 }); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringKey"", b => { b.Property<string>(""Id"") .ValueGeneratedOnAdd(); b.HasKey(""Id""); b.ToTable(""EntityWithStringKey""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.OwnsOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", ""EntityWithTwoProperties"", b1 => { b1.Property<int>(""AlternateId"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b1.Property<string>(""EntityWithStringKeyId""); b1.Property<int>(""Id""); b1.HasKey(""AlternateId"") .HasName(""PK_Custom""); b1.HasIndex(""EntityWithStringKeyId"") .IsUnique() .HasFilter(""[EntityWithTwoProperties_EntityWithStringKeyId] IS NOT NULL""); b1.HasIndex(""Id""); b1.ToTable(""EntityWithOneProperty""); b1.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", ""EntityWithOneProperty"") .WithOne(""EntityWithTwoProperties"") .HasForeignKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", ""AlternateId"") .HasConstraintName(""FK_Custom"") .OnDelete(DeleteBehavior.Cascade); b1.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringKey"", ""EntityWithStringKey"") .WithOne() .HasForeignKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", ""EntityWithStringKeyId""); b1.HasData( new { AlternateId = 1, Id = -1 }); }); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringKey"", b => { b.OwnsMany(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringProperty"", ""Properties"", b1 => { b1.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b1.Property<int?>(""EntityWithOnePropertyId""); b1.Property<string>(""EntityWithStringKeyId"") .IsRequired(); b1.Property<string>(""Name""); b1.HasKey(""Id""); b1.HasIndex(""EntityWithOnePropertyId"") .IsUnique() .HasFilter(""[EntityWithOnePropertyId] IS NOT NULL""); b1.HasIndex(""EntityWithStringKeyId""); b1.ToTable(""EntityWithStringProperty""); b1.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", ""EntityWithOneProperty"") .WithOne() .HasForeignKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringProperty"", ""EntityWithOnePropertyId""); b1.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringKey"") .WithMany(""Properties"") .HasForeignKey(""EntityWithStringKeyId"") .OnDelete(DeleteBehavior.Cascade); }); });", usingSystem: true), o => { var entityWithOneProperty = o.FindEntityType(typeof(EntityWithOneProperty)); Assert.Equal("PK_Custom", entityWithOneProperty.GetKeys().Single().Relational().Name); Assert.Equal(new object[] { 1 }, entityWithOneProperty.GetData().Single().Values); var ownership1 = entityWithOneProperty.FindNavigation(nameof(EntityWithOneProperty.EntityWithTwoProperties)) .ForeignKey; Assert.Equal(nameof(EntityWithTwoProperties.AlternateId), ownership1.Properties[0].Name); Assert.Equal(nameof(EntityWithTwoProperties.EntityWithOneProperty), ownership1.DependentToPrincipal.Name); Assert.True(ownership1.IsRequired); Assert.Equal(DeleteBehavior.Cascade, ownership1.DeleteBehavior); Assert.Equal("FK_Custom", ownership1.Relational().Name); var ownedType1 = ownership1.DeclaringEntityType; Assert.Equal(nameof(EntityWithTwoProperties.AlternateId), ownedType1.FindPrimaryKey().Properties[0].Name); Assert.Equal("PK_Custom", ownedType1.GetKeys().Single().Relational().Name); Assert.Equal(2, ownedType1.GetIndexes().Count()); var owned1index1 = ownedType1.GetIndexes().First(); Assert.Equal("EntityWithStringKeyId", owned1index1.Properties[0].Name); Assert.True(owned1index1.IsUnique); Assert.Equal("[EntityWithTwoProperties_EntityWithStringKeyId] IS NOT NULL", owned1index1.Relational().Filter); var owned1index2 = ownedType1.GetIndexes().Last(); Assert.Equal("Id", owned1index2.Properties[0].Name); Assert.False(owned1index2.IsUnique); Assert.Null(owned1index2.Relational().Filter); Assert.Equal(new object[] { 1, -1 }, ownedType1.GetData().Single().Values); Assert.Equal(nameof(EntityWithOneProperty), ownedType1.Relational().TableName); var entityWithStringKey = o.FindEntityType(typeof(EntityWithStringKey)); Assert.Same(entityWithStringKey, ownedType1.FindNavigation(nameof(EntityWithTwoProperties.EntityWithStringKey)).GetTargetType()); Assert.Equal(nameof(EntityWithStringKey), entityWithStringKey.Relational().TableName); var ownership2 = entityWithStringKey.FindNavigation(nameof(EntityWithStringKey.Properties)).ForeignKey; Assert.Equal(DeleteBehavior.Cascade, ownership2.DeleteBehavior); Assert.Equal("EntityWithStringKeyId", ownership2.Properties[0].Name); Assert.Null(ownership2.DependentToPrincipal); Assert.True(ownership2.IsRequired); var ownedType2 = ownership2.DeclaringEntityType; Assert.Equal(nameof(EntityWithStringProperty.Id), ownedType2.FindPrimaryKey().Properties[0].Name); Assert.Equal(1, ownedType2.GetKeys().Count()); Assert.Equal(2, ownedType2.GetIndexes().Count()); var owned2index1 = ownedType2.GetIndexes().First(); Assert.Equal("EntityWithOnePropertyId", owned2index1.Properties[0].Name); Assert.True(owned2index1.IsUnique); Assert.Equal("[EntityWithOnePropertyId] IS NOT NULL", owned2index1.Relational().Filter); var owned2index2 = ownedType2.GetIndexes().Last(); Assert.Equal("EntityWithStringKeyId", owned2index2.Properties[0].Name); Assert.False(owned2index2.IsUnique); Assert.Null(owned2index2.Relational().Filter); Assert.Equal(nameof(EntityWithStringProperty), ownedType2.Relational().TableName); Assert.Same(entityWithOneProperty, ownedType2.GetNavigations().Single().GetTargetType()); }); } [Fact] public virtual void Weak_owned_types_are_stored_in_snapshot() { Test( builder => { builder.Entity<Order>().OwnsOne(p => p.OrderBillingDetails, od => { od.OwnsOne(c => c.StreetAddress); }); builder.Entity<Order>().OwnsOne(p => p.OrderShippingDetails, od => { od.OwnsOne(c => c.StreetAddress); }); builder.Entity<Order>().OwnsOne(p => p.OrderInfo, od => { od.OwnsOne(c => c.StreetAddress); }); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+Order"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.HasKey(""Id""); b.ToTable(""Order""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+Order"", b => { b.OwnsOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+OrderInfo"", ""OrderInfo"", b1 => { b1.Property<int>(""OrderId"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b1.HasKey(""OrderId""); b1.ToTable(""Order""); b1.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+Order"") .WithOne(""OrderInfo"") .HasForeignKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+OrderInfo"", ""OrderId"") .OnDelete(DeleteBehavior.Cascade); b1.OwnsOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+StreetAddress"", ""StreetAddress"", b2 => { b2.Property<int>(""OrderInfoOrderId"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b2.Property<string>(""City""); b2.HasKey(""OrderInfoOrderId""); b2.ToTable(""Order""); b2.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+OrderInfo"") .WithOne(""StreetAddress"") .HasForeignKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+StreetAddress"", ""OrderInfoOrderId"") .OnDelete(DeleteBehavior.Cascade); }); }); b.OwnsOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+OrderDetails"", ""OrderBillingDetails"", b1 => { b1.Property<int>(""OrderId"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b1.HasKey(""OrderId""); b1.ToTable(""Order""); b1.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+Order"") .WithOne(""OrderBillingDetails"") .HasForeignKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+OrderDetails"", ""OrderId"") .OnDelete(DeleteBehavior.Cascade); b1.OwnsOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+StreetAddress"", ""StreetAddress"", b2 => { b2.Property<int>(""OrderDetailsOrderId"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b2.Property<string>(""City""); b2.HasKey(""OrderDetailsOrderId""); b2.ToTable(""Order""); b2.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+OrderDetails"") .WithOne(""StreetAddress"") .HasForeignKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+StreetAddress"", ""OrderDetailsOrderId"") .OnDelete(DeleteBehavior.Cascade); }); }); b.OwnsOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+OrderDetails"", ""OrderShippingDetails"", b1 => { b1.Property<int>(""OrderId"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b1.HasKey(""OrderId""); b1.ToTable(""Order""); b1.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+Order"") .WithOne(""OrderShippingDetails"") .HasForeignKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+OrderDetails"", ""OrderId"") .OnDelete(DeleteBehavior.Cascade); b1.OwnsOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+StreetAddress"", ""StreetAddress"", b2 => { b2.Property<int>(""OrderDetailsOrderId"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b2.Property<string>(""City""); b2.HasKey(""OrderDetailsOrderId""); b2.ToTable(""Order""); b2.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+OrderDetails"") .WithOne(""StreetAddress"") .HasForeignKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+StreetAddress"", ""OrderDetailsOrderId"") .OnDelete(DeleteBehavior.Cascade); }); }); });"), o => { Assert.Equal(7, o.GetEntityTypes().Count()); var order = o.FindEntityType(typeof(Order).FullName); Assert.Equal(1, order.PropertyCount()); var orderInfo = order.FindNavigation(nameof(Order.OrderInfo)).GetTargetType(); Assert.Equal(1, orderInfo.PropertyCount()); var orderInfoAddress = orderInfo.FindNavigation(nameof(OrderInfo.StreetAddress)).GetTargetType(); Assert.Equal(2, orderInfoAddress.PropertyCount()); var orderBillingDetails = order.FindNavigation(nameof(Order.OrderBillingDetails)).GetTargetType(); Assert.Equal(1, orderBillingDetails.PropertyCount()); var orderBillingDetailsAddress = orderBillingDetails.FindNavigation(nameof(OrderDetails.StreetAddress)).GetTargetType(); Assert.Equal(2, orderBillingDetailsAddress.PropertyCount()); var orderShippingDetails = order.FindNavigation(nameof(Order.OrderShippingDetails)).GetTargetType(); Assert.Equal(1, orderShippingDetails.PropertyCount()); var orderShippingDetailsAddress = orderShippingDetails.FindNavigation(nameof(OrderDetails.StreetAddress)).GetTargetType(); Assert.Equal(2, orderShippingDetailsAddress.PropertyCount()); }); } private class Order { public int Id { get; set; } public OrderDetails OrderBillingDetails { get; set; } public OrderDetails OrderShippingDetails { get; set; } public OrderInfo OrderInfo { get; set; } } private class OrderDetails { public StreetAddress StreetAddress { get; set; } } private class OrderInfo { public StreetAddress StreetAddress { get; set; } } private class StreetAddress { public string City { get; set; } } #endregion #region Property [Fact] public virtual void Property_annotations_are_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithOneProperty>() .Property<int>("Id") .HasAnnotation("AnnotationName", "AnnotationValue") .HasAnnotation(CoreAnnotationNames.TypeMapping, new IntTypeMapping("int")); builder.Ignore<EntityWithTwoProperties>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""AnnotationName"", ""AnnotationValue"") .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.HasKey(""Id""); b.ToTable(""EntityWithOneProperty""); });"), o => { Assert.Equal("AnnotationValue", o.GetEntityTypes().First().FindProperty("Id")["AnnotationName"]); } ); } [Fact] public virtual void Custom_value_generator_is_ignored_in_snapshot() { Test( builder => { builder.Entity<EntityWithOneProperty>().Property<int>("Id").HasValueGenerator<CustomValueGenerator>(); builder.Ignore<EntityWithTwoProperties>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.HasKey(""Id""); b.ToTable(""EntityWithOneProperty""); });"), o => { Assert.Null(o.GetEntityTypes().First().FindProperty("Id")[CoreAnnotationNames.ValueGeneratorFactoryAnnotation]); } ); } [Fact] public virtual void Property_isNullable_is_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithStringProperty>().Property<string>("Name").IsRequired(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringProperty"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>(""Name"") .IsRequired(); b.HasKey(""Id""); b.ToTable(""EntityWithStringProperty""); });"), o => { Assert.False(o.GetEntityTypes().First().FindProperty("Name").IsNullable); }); } [Fact] public virtual void Property_ValueGenerated_value_is_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithTwoProperties>().Property<int>("AlternateId").HasDefaultValue(); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId"") .ValueGeneratedOnAdd() .HasDefaultValue(null); b.HasKey(""Id""); b.ToTable(""EntityWithTwoProperties""); });", usingSystem: true), o => { Assert.Equal(ValueGenerated.OnAdd, o.GetEntityTypes().First().FindProperty("AlternateId").ValueGenerated); }); } [Fact] public virtual void Property_maxLength_is_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithStringProperty>().Property<string>("Name").HasMaxLength(100); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringProperty"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>(""Name"") .HasMaxLength(100); b.HasKey(""Id""); b.ToTable(""EntityWithStringProperty""); });"), o => { Assert.Equal(100, o.GetEntityTypes().First().FindProperty("Name").GetMaxLength()); }); } [Fact] public virtual void Property_unicodeness_is_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithStringProperty>().Property<string>("Name").IsUnicode(false); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringProperty"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>(""Name"") .IsUnicode(false); b.HasKey(""Id""); b.ToTable(""EntityWithStringProperty""); });"), o => { Assert.False(o.GetEntityTypes().First().FindProperty("Name").IsUnicode()); }); } [Fact] public virtual void Property_fixedlengthness_is_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithStringProperty>().Property<string>("Name").IsFixedLength(true); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringProperty"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>(""Name"") .IsFixedLength(true); b.HasKey(""Id""); b.ToTable(""EntityWithStringProperty""); });"), o => { Assert.True(o.GetEntityTypes().First().FindProperty("Name").Relational().IsFixedLength); }); } [Fact] public virtual void Many_facets_chained_in_snapshot() { Test( builder => { builder.Entity<EntityWithStringProperty>() .Property<string>("Name") .HasMaxLength(100) .IsUnicode(false) .HasAnnotation("AnnotationName", "AnnotationValue"); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringProperty"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>(""Name"") .HasMaxLength(100) .IsUnicode(false) .HasAnnotation(""AnnotationName"", ""AnnotationValue""); b.HasKey(""Id""); b.ToTable(""EntityWithStringProperty""); });"), o => { var property = o.GetEntityTypes().First().FindProperty("Name"); Assert.Equal(100, property.GetMaxLength()); Assert.False(property.IsUnicode()); Assert.Equal("AnnotationValue", property["AnnotationName"]); }); } [Fact] public virtual void Property_concurrencyToken_is_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithTwoProperties>().Property<int>("AlternateId").IsConcurrencyToken(); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId"") .IsConcurrencyToken(); b.HasKey(""Id""); b.ToTable(""EntityWithTwoProperties""); });"), o => { Assert.True(o.GetEntityTypes().First().FindProperty("AlternateId").IsConcurrencyToken); }); } [Fact] public virtual void Property_column_name_annotation_is_stored_in_snapshot_as_fluent_api() { Test( builder => { builder.Entity<EntityWithTwoProperties>().Property<int>("AlternateId").HasColumnName("CName"); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId"") .HasColumnName(""CName""); b.HasKey(""Id""); b.ToTable(""EntityWithTwoProperties""); });"), o => { Assert.Equal("CName", o.GetEntityTypes().First().FindProperty("AlternateId")["Relational:ColumnName"]); }); } [Fact] public virtual void Property_column_type_annotation_is_stored_in_snapshot_as_fluent_api() { Test( builder => { builder.Entity<EntityWithTwoProperties>().Property<int>("AlternateId").HasColumnType("CType"); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId"") .HasColumnType(""CType""); b.HasKey(""Id""); b.ToTable(""EntityWithTwoProperties""); });"), o => { Assert.Equal("CType", o.GetEntityTypes().First().FindProperty("AlternateId")["Relational:ColumnType"]); }); } [Fact] public virtual void Property_default_value_annotation_is_stored_in_snapshot_as_fluent_api() { Test( builder => { builder.Entity<EntityWithTwoProperties>().Property<int>("AlternateId").HasDefaultValue(1); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId"") .ValueGeneratedOnAdd() .HasDefaultValue(1); b.HasKey(""Id""); b.ToTable(""EntityWithTwoProperties""); });"), o => { Assert.Equal(1, o.GetEntityTypes().First().FindProperty("AlternateId")["Relational:DefaultValue"]); }); } [Fact] public virtual void Property_default_value_sql_annotation_is_stored_in_snapshot_as_fluent_api() { Test( builder => { builder.Entity<EntityWithTwoProperties>().Property<int>("AlternateId").HasDefaultValueSql("SQL"); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId"") .ValueGeneratedOnAdd() .HasDefaultValueSql(""SQL""); b.HasKey(""Id""); b.ToTable(""EntityWithTwoProperties""); });"), o => { Assert.Equal("SQL", o.GetEntityTypes().First().FindProperty("AlternateId")["Relational:DefaultValueSql"]); }); } [Fact] public virtual void Property_computed_column_sql_annotation_is_stored_in_snapshot_as_fluent_api() { Test( builder => { builder.Entity<EntityWithTwoProperties>().Property<int>("AlternateId").HasComputedColumnSql("SQL"); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId"") .ValueGeneratedOnAddOrUpdate() .HasComputedColumnSql(""SQL""); b.HasKey(""Id""); b.ToTable(""EntityWithTwoProperties""); });"), o => { Assert.Equal("SQL", o.GetEntityTypes().First().FindProperty("AlternateId")["Relational:ComputedColumnSql"]); }); } [Fact] public virtual void Property_default_value_of_enum_type_is_stored_in_snapshot_without_actual_enum() { Test( builder => { builder.Entity<EntityWithEnumType>().Property(e => e.Day).HasDefaultValue(Days.Wed); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithEnumType"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<long>(""Day"") .ValueGeneratedOnAdd() .HasDefaultValue(3L); b.HasKey(""Id""); b.ToTable(""EntityWithEnumType""); });"), o => { Assert.Equal(3L, o.GetEntityTypes().First().FindProperty("Day")["Relational:DefaultValue"]); }); } [Fact] public virtual void Property_enum_type_is_stored_in_snapshot_with_custom_conversion_and_seed_data() { Test( builder => builder.Entity<EntityWithEnumType>( eb => { eb.Property(e => e.Day).HasDefaultValue(Days.Wed) .HasConversion(v => v.ToString(), v => (Days)Enum.Parse(typeof(Days), v)); eb.HasData( new { Id = 1, Day = Days.Fri }); }), AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithEnumType"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>(""Day"") .IsRequired() .ValueGeneratedOnAdd() .HasDefaultValue(""Wed""); b.HasKey(""Id""); b.ToTable(""EntityWithEnumType""); b.HasData( new { Id = 1, Day = ""Fri"" }); });"), o => { var property = o.GetEntityTypes().First().FindProperty("Day"); Assert.Equal(typeof(string), property.ClrType); Assert.Equal(Days.Wed.ToString(), property["Relational:DefaultValue"]); Assert.False(property.IsNullable); }); } [Fact] public virtual void Property_of_nullable_enum() { Test( builder => builder.Entity<EntityWithNullableEnumType>().Property(e => e.Day), AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithNullableEnumType"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<long?>(""Day""); b.HasKey(""Id""); b.ToTable(""EntityWithNullableEnumType""); });"), o => Assert.True(o.GetEntityTypes().First().FindProperty("Day").IsNullable)); } [Fact] public virtual void Property_of_enum_to_nullable() { Test( builder => builder.Entity<EntityWithEnumType>().Property(e => e.Day) .HasConversion(m => (long?)m, p => p.HasValue ? (Days)p.Value : default), AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithEnumType"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<long>(""Day""); b.HasKey(""Id""); b.ToTable(""EntityWithEnumType""); });", usingSystem: true), o => Assert.False(o.GetEntityTypes().First().FindProperty("Day").IsNullable)); } [Fact] public virtual void Property_of_nullable_enum_to_string() { Test( builder => builder.Entity<EntityWithNullableEnumType>().Property(e => e.Day).HasConversion<string>(), AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithNullableEnumType"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>(""Day""); b.HasKey(""Id""); b.ToTable(""EntityWithNullableEnumType""); });"), o => Assert.True(o.GetEntityTypes().First().FindProperty("Day").IsNullable)); } [Fact] public virtual void Property_multiple_annotations_are_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithTwoProperties>().Property<int>("AlternateId").HasColumnName("CName").HasAnnotation("AnnotationName", "AnnotationValue"); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId"") .HasColumnName(""CName"") .HasAnnotation(""AnnotationName"", ""AnnotationValue""); b.HasKey(""Id""); b.ToTable(""EntityWithTwoProperties""); });"), o => { var property = o.GetEntityTypes().First().FindProperty("AlternateId"); Assert.Equal(2, property.GetAnnotations().Count()); Assert.Equal("AnnotationValue", property["AnnotationName"]); Assert.Equal("CName", property["Relational:ColumnName"]); }); } #endregion #region HasKey [Fact] public virtual void Key_annotations_are_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithTwoProperties>().HasAlternateKey(t => t.AlternateId) .HasAnnotation("AnnotationName", "AnnotationValue"); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.HasAlternateKey(""AlternateId"") .HasAnnotation(""AnnotationName"", ""AnnotationValue""); b.ToTable(""EntityWithTwoProperties""); });"), o => { Assert.Equal("AnnotationValue", o.GetEntityTypes().First().GetKeys().Where(k => !k.IsPrimaryKey()).First()["AnnotationName"]); }); } [Fact] public virtual void Key_name_annotation_is_stored_in_snapshot_as_fluent_api() { Test( builder => { builder.Entity<EntityWithTwoProperties>().HasAlternateKey(t => t.AlternateId).HasName("KeyName"); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.HasAlternateKey(""AlternateId"") .HasName(""KeyName""); b.ToTable(""EntityWithTwoProperties""); });"), o => { Assert.Equal("KeyName", o.GetEntityTypes().First().GetKeys().Where(k => !k.IsPrimaryKey()).First()["Relational:Name"]); }); } [Fact] public virtual void Key_multiple_annotations_are_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithTwoProperties>().HasAlternateKey(t => t.AlternateId).HasName("IndexName").HasAnnotation("AnnotationName", "AnnotationValue"); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.HasAlternateKey(""AlternateId"") .HasName(""IndexName"") .HasAnnotation(""AnnotationName"", ""AnnotationValue""); b.ToTable(""EntityWithTwoProperties""); });"), o => { var key = o.GetEntityTypes().First().GetKeys().Where(k => !k.IsPrimaryKey()).First(); Assert.Equal(2, key.GetAnnotations().Count()); Assert.Equal("AnnotationValue", key["AnnotationName"]); Assert.Equal("IndexName", key["Relational:Name"]); }); } #endregion #region HasIndex [Fact] public virtual void Index_annotations_are_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithTwoProperties>().HasIndex(t => t.AlternateId) .HasAnnotation("AnnotationName", "AnnotationValue"); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.HasIndex(""AlternateId"") .HasAnnotation(""AnnotationName"", ""AnnotationValue""); b.ToTable(""EntityWithTwoProperties""); });"), o => { Assert.Equal("AnnotationValue", o.GetEntityTypes().First().GetIndexes().First()["AnnotationName"]); }); } [Fact] public virtual void Index_isUnique_is_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithTwoProperties>().HasIndex(t => t.AlternateId).IsUnique(); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.HasIndex(""AlternateId"") .IsUnique(); b.ToTable(""EntityWithTwoProperties""); });"), o => { Assert.True(o.GetEntityTypes().First().GetIndexes().First().IsUnique); }); } [Fact] public virtual void Index_name_annotation_is_stored_in_snapshot_as_fluent_api() { Test( builder => { builder.Entity<EntityWithTwoProperties>().HasIndex(t => t.AlternateId).HasName("IndexName"); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.HasIndex(""AlternateId"") .HasName(""IndexName""); b.ToTable(""EntityWithTwoProperties""); });"), o => { Assert.Equal("IndexName", o.GetEntityTypes().First().GetIndexes().First()["Relational:Name"]); }); } [Fact] public virtual void Index_filter_is_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithTwoProperties>().HasIndex(t => t.AlternateId) .HasFilter("AlternateId <> 0"); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.HasIndex(""AlternateId"") .HasFilter(""AlternateId <> 0""); b.ToTable(""EntityWithTwoProperties""); });"), o => Assert.Equal( "AlternateId <> 0", o.GetEntityTypes().First().GetIndexes().First().Relational().Filter)); } [Fact] public virtual void Index_multiple_annotations_are_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithTwoProperties>().HasIndex(t => t.AlternateId).HasName("IndexName").HasAnnotation("AnnotationName", "AnnotationValue"); builder.Ignore<EntityWithOneProperty>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.HasIndex(""AlternateId"") .HasName(""IndexName"") .HasAnnotation(""AnnotationName"", ""AnnotationValue""); b.ToTable(""EntityWithTwoProperties""); });"), o => { var index = o.GetEntityTypes().First().GetIndexes().First(); Assert.Equal(2, index.GetAnnotations().Count()); Assert.Equal("AnnotationValue", index["AnnotationName"]); Assert.Equal("IndexName", index["Relational:Name"]); }); } [Fact] public virtual void Index_with_default_constraint_name_exceeding_max() { Test( builder => builder.Entity<EntityWithStringProperty>( x => { const string propertyName = "SomePropertyWithAnExceedinglyLongIdentifierThatCausesTheDefaultIndexNameToExceedTheMaximumIdentifierLimit"; x.Property<string>(propertyName); x.HasIndex(propertyName); }), AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringProperty"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>(""Name""); b.Property<string>(""SomePropertyWithAnExceedinglyLongIdentifierThatCausesTheDefaultIndexNameToExceedTheMaximumIdentifierLimit""); b.HasKey(""Id""); b.HasIndex(""SomePropertyWithAnExceedinglyLongIdentifierThatCausesTheDefaultIndexNameToExceedTheMaximumIdentifierLimit""); b.ToTable(""EntityWithStringProperty""); });"), model => Assert.Equal(128, model.GetEntityTypes().First().GetIndexes().First().Relational().Name.Length)); } #endregion #region ForeignKey [Fact] public virtual void ForeignKey_annotations_are_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithTwoProperties>() .HasOne(e => e.EntityWithOneProperty) .WithOne(e => e.EntityWithTwoProperties) .HasForeignKey<EntityWithTwoProperties>(e => e.AlternateId) .HasAnnotation("AnnotationName", "AnnotationValue"); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.HasKey(""Id""); b.ToTable(""EntityWithOneProperty""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.HasIndex(""AlternateId"") .IsUnique(); b.ToTable(""EntityWithTwoProperties""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", ""EntityWithOneProperty"") .WithOne(""EntityWithTwoProperties"") .HasForeignKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", ""AlternateId"") .HasAnnotation(""AnnotationName"", ""AnnotationValue"") .OnDelete(DeleteBehavior.Cascade); });"), o => { Assert.Equal("AnnotationValue", o.FindEntityType(typeof(EntityWithTwoProperties)).GetForeignKeys().First()["AnnotationName"]); }); } [Fact] public virtual void ForeignKey_isRequired_is_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithStringKey>().Ignore(e => e.Properties); builder.Entity<EntityWithStringProperty>() .HasOne<EntityWithStringKey>() .WithOne() .HasForeignKey<EntityWithStringProperty>(e => e.Name) .IsRequired(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringKey"", b => { b.Property<string>(""Id"") .ValueGeneratedOnAdd(); b.HasKey(""Id""); b.ToTable(""EntityWithStringKey""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringProperty"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>(""Name"") .IsRequired(); b.HasKey(""Id""); b.HasIndex(""Name"") .IsUnique(); b.ToTable(""EntityWithStringProperty""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringProperty"", b => { b.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringKey"") .WithOne() .HasForeignKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringProperty"", ""Name"") .OnDelete(DeleteBehavior.Cascade); });"), o => { Assert.False(o.FindEntityType(typeof(EntityWithStringProperty)).FindProperty("Name").IsNullable); }); } [Fact] public virtual void ForeignKey_isUnique_is_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithStringProperty>() .HasOne<EntityWithStringKey>() .WithMany(e => e.Properties) .HasForeignKey(e => e.Name); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringKey"", b => { b.Property<string>(""Id"") .ValueGeneratedOnAdd(); b.HasKey(""Id""); b.ToTable(""EntityWithStringKey""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringProperty"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>(""Name""); b.HasKey(""Id""); b.HasIndex(""Name""); b.ToTable(""EntityWithStringProperty""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringProperty"", b => { b.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithStringKey"") .WithMany(""Properties"") .HasForeignKey(""Name""); });"), o => { Assert.False(o.FindEntityType(typeof(EntityWithStringProperty)).GetForeignKeys().First().IsUnique); }); } [Fact] public virtual void ForeignKey_deleteBehavior_is_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithOneProperty>() .HasOne(e => e.EntityWithTwoProperties) .WithMany() .HasForeignKey(e => e.Id); builder.Entity<EntityWithTwoProperties>().Ignore(e => e.EntityWithOneProperty); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.Property<int>(""Id""); b.HasKey(""Id""); b.ToTable(""EntityWithOneProperty""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.ToTable(""EntityWithTwoProperties""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", ""EntityWithTwoProperties"") .WithMany() .HasForeignKey(""Id"") .OnDelete(DeleteBehavior.Cascade); });"), o => { Assert.Equal(DeleteBehavior.Cascade, o.FindEntityType(typeof(EntityWithOneProperty)).GetForeignKeys().First().DeleteBehavior); }); } [Fact] public virtual void ForeignKey_deleteBehavior_is_stored_in_snapshot_for_one_to_one() { Test( builder => { builder.Entity<EntityWithOneProperty>() .HasOne(e => e.EntityWithTwoProperties) .WithOne(e => e.EntityWithOneProperty) .HasForeignKey<EntityWithOneProperty>(e => e.Id); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.Property<int>(""Id""); b.HasKey(""Id""); b.ToTable(""EntityWithOneProperty""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.ToTable(""EntityWithTwoProperties""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", ""EntityWithTwoProperties"") .WithOne(""EntityWithOneProperty"") .HasForeignKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", ""Id"") .OnDelete(DeleteBehavior.Cascade); });"), o => { Assert.Equal(DeleteBehavior.Cascade, o.FindEntityType(typeof(EntityWithOneProperty)).GetForeignKeys().First().DeleteBehavior); }); } [Fact] public virtual void ForeignKey_name_preserved_when_generic() { IModel originalModel = null; Test( builder => { builder.Entity<EntityWithGenericKey<Guid>>().HasMany<EntityWithGenericProperty<Guid>>().WithOne() .HasForeignKey(e => e.Property); originalModel = builder.Model; }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithGenericKey<System.Guid>"", b => { b.Property<Guid>(""Id"") .ValueGeneratedOnAdd(); b.HasKey(""Id""); b.ToTable(""EntityWithGenericKey<Guid>""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithGenericProperty<System.Guid>"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<Guid>(""Property""); b.HasKey(""Id""); b.HasIndex(""Property""); b.ToTable(""EntityWithGenericProperty<Guid>""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithGenericProperty<System.Guid>"", b => { b.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithGenericKey<System.Guid>"") .WithMany() .HasForeignKey(""Property"") .OnDelete(DeleteBehavior.Cascade); });", usingSystem: true), model => { var originalParent = originalModel.FindEntityType(typeof(EntityWithGenericKey<Guid>)); var parent = model.FindEntityType(originalParent.Name); Assert.NotNull(parent); var originalChild = originalModel.FindEntityType(typeof(EntityWithGenericProperty<Guid>)); var child = model.FindEntityType(originalChild.Name); Assert.NotNull(child); var originalForeignKey = originalChild.FindForeignKey( originalChild.FindProperty("Property"), originalParent.FindPrimaryKey(), originalParent); var foreignKey = child.FindForeignKey( child.FindProperty("Property"), parent.FindPrimaryKey(), parent); Assert.Equal(originalForeignKey.Relational().Name, foreignKey.Relational().Name); var originalIndex = originalChild.FindIndex(originalChild.FindProperty("Property")); var index = child.FindIndex(child.FindProperty("Property")); Assert.Equal(originalIndex.Relational().Name, index.Relational().Name); }); } [Fact] public virtual void ForeignKey_constraint_name_is_stored_in_snapshot_as_fluent_api() { Test( builder => { builder.Entity<EntityWithTwoProperties>() .HasOne(e => e.EntityWithOneProperty) .WithOne(e => e.EntityWithTwoProperties) .HasForeignKey<EntityWithTwoProperties>(e => e.AlternateId) .HasConstraintName("Constraint"); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.HasKey(""Id""); b.ToTable(""EntityWithOneProperty""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.HasIndex(""AlternateId"") .IsUnique(); b.ToTable(""EntityWithTwoProperties""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", ""EntityWithOneProperty"") .WithOne(""EntityWithTwoProperties"") .HasForeignKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", ""AlternateId"") .HasConstraintName(""Constraint"") .OnDelete(DeleteBehavior.Cascade); });"), o => { Assert.Equal("Constraint", o.FindEntityType(typeof(EntityWithTwoProperties)).GetForeignKeys().First()["Relational:Name"]); }); } [Fact] public virtual void ForeignKey_multiple_annotations_are_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithTwoProperties>() .HasOne(e => e.EntityWithOneProperty) .WithOne(e => e.EntityWithTwoProperties) .HasForeignKey<EntityWithTwoProperties>(e => e.AlternateId) .HasAnnotation("AnnotationName", "AnnotationValue") .HasConstraintName("Constraint"); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.HasKey(""Id""); b.ToTable(""EntityWithOneProperty""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.HasIndex(""AlternateId"") .IsUnique(); b.ToTable(""EntityWithTwoProperties""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", ""EntityWithOneProperty"") .WithOne(""EntityWithTwoProperties"") .HasForeignKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", ""AlternateId"") .HasConstraintName(""Constraint"") .HasAnnotation(""AnnotationName"", ""AnnotationValue"") .OnDelete(DeleteBehavior.Cascade); });"), o => { var fk = o.FindEntityType(typeof(EntityWithTwoProperties)).GetForeignKeys().First(); Assert.Equal(2, fk.GetAnnotations().Count()); Assert.Equal("AnnotationValue", fk["AnnotationName"]); Assert.Equal("Constraint", fk["Relational:Name"]); }); } [Fact] public virtual void Do_not_generate_entity_type_builder_again_if_no_foreign_key_is_defined_on_it() { Test( builder => { builder.Entity<BaseType>(); builder.Ignore<EntityWithTwoProperties>(); builder.Entity<DerivedType>(); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+BaseType"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>(""Discriminator"") .IsRequired(); b.Property<int?>(""NavigationId""); b.HasKey(""Id""); b.HasIndex(""NavigationId""); b.ToTable(""BaseType""); b.HasDiscriminator<string>(""Discriminator"").HasValue(""BaseType""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.HasKey(""Id""); b.ToTable(""EntityWithOneProperty""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+DerivedType"", b => { b.HasBaseType(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+BaseType""); b.HasDiscriminator().HasValue(""DerivedType""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+BaseType"", b => { b.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", ""Navigation"") .WithMany() .HasForeignKey(""NavigationId""); });", usingSystem: true), o => { }); } [Fact] public virtual void Relationship_principal_key_is_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithOneProperty>() .HasOne(e => e.EntityWithTwoProperties) .WithOne(e => e.EntityWithOneProperty) .HasForeignKey<EntityWithOneProperty>(e => e.Id) .HasPrincipalKey<EntityWithTwoProperties>(e => e.AlternateId); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.Property<int>(""Id""); b.HasKey(""Id""); b.ToTable(""EntityWithOneProperty""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.ToTable(""EntityWithTwoProperties""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", ""EntityWithTwoProperties"") .WithOne(""EntityWithOneProperty"") .HasForeignKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", ""Id"") .HasPrincipalKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", ""AlternateId"") .OnDelete(DeleteBehavior.Cascade); });"), o => { Assert.Equal(2, o.FindEntityType(typeof(EntityWithTwoProperties)).GetKeys().Count()); Assert.True(o.FindEntityType(typeof(EntityWithTwoProperties)).FindProperty("AlternateId").IsKey()); }); } [Fact] public virtual void Relationship_principal_key_with_non_default_name_is_stored_in_snapshot() { Test( builder => { builder.Entity<EntityWithOneProperty>() .HasOne(e => e.EntityWithTwoProperties) .WithOne(e => e.EntityWithOneProperty) .HasForeignKey<EntityWithOneProperty>(e => e.Id) .HasPrincipalKey<EntityWithTwoProperties>(e => e.AlternateId); builder.Entity<EntityWithTwoProperties>().HasAlternateKey(e => e.AlternateId).HasAnnotation("Name", "Value"); }, AddBoilerPlate(GetHeading() + @" modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.Property<int>(""Id""); b.HasKey(""Id""); b.ToTable(""EntityWithOneProperty""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>(""AlternateId""); b.HasKey(""Id""); b.HasAlternateKey(""AlternateId"") .HasAnnotation(""Name"", ""Value""); b.ToTable(""EntityWithTwoProperties""); }); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", b => { b.HasOne(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", ""EntityWithTwoProperties"") .WithOne(""EntityWithOneProperty"") .HasForeignKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithOneProperty"", ""Id"") .HasPrincipalKey(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithTwoProperties"", ""AlternateId"") .OnDelete(DeleteBehavior.Cascade); });"), o => { var entityType = o.FindEntityType(typeof(EntityWithTwoProperties)); Assert.Equal(2, entityType.GetKeys().Count()); Assert.Equal("Value", entityType.FindKey(entityType.FindProperty("AlternateId"))["Name"]); }); } #endregion #region SeedData #if !Test21 [Fact] public virtual void SeedData_annotations_are_stored_in_snapshot() { var lineString1 = new LineString( new[] { new Coordinate(1.1, 2.2), new Coordinate(2.2, 2.2), new Coordinate(2.2, 1.1), new Coordinate(7.1, 7.2) }); var lineString2 = new LineString( new[] { new Coordinate(7.1, 7.2), new Coordinate(20.2, 20.2), new Coordinate(20.20, 1.1), new Coordinate(70.1, 70.2) }); var multiPoint = new MultiPoint( new IPoint[] { new Point(1.1, 2.2), new Point(2.2, 2.2), new Point(2.2, 1.1) }); var polygon1 = new Polygon( new LinearRing( new[] { new Coordinate(1.1, 2.2), new Coordinate(2.2, 2.2), new Coordinate(2.2, 1.1), new Coordinate(1.1, 2.2) })); var polygon2 = new Polygon( new LinearRing( new[] { new Coordinate(10.1, 20.2), new Coordinate(20.2, 20.2), new Coordinate(20.2, 10.1), new Coordinate(10.1, 20.2) })); var point1 = new Point(1.1, 2.2, 3.3); var multiLineString = new MultiLineString( new ILineString[] { lineString1, lineString2, }); var multiPolygon = new MultiPolygon( new IPolygon[] { polygon2, polygon1, }); var geometryCollection = new GeometryCollection( new IGeometry[] { lineString1, lineString2, multiPoint, polygon1, polygon2, point1, multiLineString, multiPolygon }); Test( builder => { builder.Entity<EntityWithManyProperties>( eb => { eb.Property<decimal?>("OptionalProperty"); eb.HasData( new EntityWithManyProperties { Id = 42, String = "FortyThree", Bytes = new byte[] { 44, 45 }, Int16 = 46, Int32 = 47, Int64 = 48, Double = 49.0, Decimal = 50.0m, DateTime = new DateTime(1973, 9, 3, 12, 10, 42, 344, DateTimeKind.Utc), DateTimeOffset = new DateTimeOffset(new DateTime(1973, 9, 3, 12, 10, 42, 344), new TimeSpan(1, 0, 0)), TimeSpan = new TimeSpan(51, 52, 53), Single = 54.0f, Boolean = true, Byte = 55, UnsignedInt16 = 56, UnsignedInt32 = 57, UnsignedInt64 = 58, Character = '9', SignedByte = 60, Enum64 = Enum64.SomeValue, Enum32 = Enum32.SomeValue, Enum16 = Enum16.SomeValue, Enum8 = Enum8.SomeValue, EnumU64 = EnumU64.SomeValue, EnumU32 = EnumU32.SomeValue, EnumU16 = EnumU16.SomeValue, EnumS8 = EnumS8.SomeValue, SpatialBGeometryCollection = geometryCollection, SpatialBLineString = lineString1, SpatialBMultiLineString = multiLineString, SpatialBMultiPoint = multiPoint, SpatialBMultiPolygon = multiPolygon, SpatialBPoint = point1, SpatialBPolygon = polygon1, SpatialCGeometryCollection = geometryCollection, SpatialCLineString = lineString1, SpatialCMultiLineString = multiLineString, SpatialCMultiPoint = multiPoint, SpatialCMultiPolygon = multiPolygon, SpatialCPoint = point1, SpatialCPolygon = polygon1, SpatialIGeometryCollection = geometryCollection, SpatialILineString = lineString1, SpatialIMultiLineString = multiLineString, SpatialIMultiPoint = multiPoint, SpatialIMultiPolygon = multiPolygon, SpatialIPoint = point1, SpatialIPolygon = polygon1 }, new { Id = 43, String = "FortyThree", Bytes = new byte[] { 44, 45 }, Int16 = (short)-46, Int32 = -47, Int64 = (long)-48, Double = -49.0, Decimal = -50.0m, DateTime = new DateTime(1973, 9, 3, 12, 10, 42, 344, DateTimeKind.Utc), DateTimeOffset = new DateTimeOffset(new DateTime(1973, 9, 3, 12, 10, 42, 344), new TimeSpan(-1, 0, 0)), TimeSpan = new TimeSpan(-51, 52, 53), Single = -54.0f, Boolean = true, Byte = (byte)55, UnsignedInt16 = (ushort)56, UnsignedInt32 = (uint)57, UnsignedInt64 = (ulong)58, Character = '9', SignedByte = (sbyte)-60, Enum64 = Enum64.SomeValue, Enum32 = Enum32.SomeValue, Enum16 = Enum16.SomeValue, Enum8 = Enum8.SomeValue, EnumU64 = EnumU64.SomeValue, EnumU32 = EnumU32.SomeValue, EnumU16 = EnumU16.SomeValue, EnumS8 = EnumS8.SomeValue }); }); builder.Ignore<EntityWithTwoProperties>(); }, @"// <auto-generated /> using System; using GeoAPI.Geometries; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using NetTopologySuite.Geometries; namespace RootNamespace { [DbContext(typeof(DbContext))] partial class Snapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation(""Relational:MaxIdentifierLength"", 128) .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity(""Microsoft.EntityFrameworkCore.Migrations.ModelSnapshotSqlServerTest+EntityWithManyProperties"", b => { b.Property<int>(""Id"") .ValueGeneratedOnAdd() .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<bool>(""Boolean""); b.Property<byte>(""Byte""); b.Property<byte[]>(""Bytes""); b.Property<string>(""Character"") .IsRequired() .HasConversion(new ValueConverter<string, string>(v => default(string), v => default(string), new ConverterMappingHints(size: 1))); b.Property<DateTime>(""DateTime""); b.Property<DateTimeOffset>(""DateTimeOffset""); b.Property<decimal>(""Decimal""); b.Property<double>(""Double""); b.Property<short>(""Enum16""); b.Property<int>(""Enum32""); b.Property<long>(""Enum64""); b.Property<byte>(""Enum8""); b.Property<short>(""EnumS8""); b.Property<int>(""EnumU16""); b.Property<long>(""EnumU32""); b.Property<decimal>(""EnumU64"") .HasConversion(new ValueConverter<decimal, decimal>(v => default(decimal), v => default(decimal), new ConverterMappingHints(precision: 20, scale: 0))); b.Property<short>(""Int16""); b.Property<int>(""Int32""); b.Property<long>(""Int64""); b.Property<decimal?>(""OptionalProperty""); b.Property<short>(""SignedByte""); b.Property<float>(""Single""); b.Property<IGeometry>(""SpatialBGeometryCollection""); b.Property<IGeometry>(""SpatialBLineString""); b.Property<IGeometry>(""SpatialBMultiLineString""); b.Property<IGeometry>(""SpatialBMultiPoint""); b.Property<IGeometry>(""SpatialBMultiPolygon""); b.Property<IGeometry>(""SpatialBPoint""); b.Property<IGeometry>(""SpatialBPolygon""); b.Property<GeometryCollection>(""SpatialCGeometryCollection""); b.Property<LineString>(""SpatialCLineString""); b.Property<MultiLineString>(""SpatialCMultiLineString""); b.Property<MultiPoint>(""SpatialCMultiPoint""); b.Property<MultiPolygon>(""SpatialCMultiPolygon""); b.Property<Point>(""SpatialCPoint""); b.Property<Polygon>(""SpatialCPolygon""); b.Property<IGeometryCollection>(""SpatialIGeometryCollection""); b.Property<ILineString>(""SpatialILineString""); b.Property<IMultiLineString>(""SpatialIMultiLineString""); b.Property<IMultiPoint>(""SpatialIMultiPoint""); b.Property<IMultiPolygon>(""SpatialIMultiPolygon""); b.Property<IPoint>(""SpatialIPoint""); b.Property<IPolygon>(""SpatialIPolygon""); b.Property<string>(""String""); b.Property<TimeSpan>(""TimeSpan""); b.Property<int>(""UnsignedInt16""); b.Property<long>(""UnsignedInt32""); b.Property<decimal>(""UnsignedInt64"") .HasConversion(new ValueConverter<decimal, decimal>(v => default(decimal), v => default(decimal), new ConverterMappingHints(precision: 20, scale: 0))); b.HasKey(""Id""); b.ToTable(""EntityWithManyProperties""); b.HasData( new { Id = 42, Boolean = true, Byte = (byte)55, Bytes = new byte[] { 44, 45 }, Character = ""9"", DateTime = new DateTime(1973, 9, 3, 12, 10, 42, 344, DateTimeKind.Utc), DateTimeOffset = new DateTimeOffset(new DateTime(1973, 9, 3, 12, 10, 42, 344, DateTimeKind.Unspecified), new TimeSpan(0, 1, 0, 0, 0)), Decimal = 50.0m, Double = 49.0, Enum16 = (short)1, Enum32 = 1, Enum64 = 1L, Enum8 = (byte)1, EnumS8 = (short)-128, EnumU16 = 65535, EnumU32 = 4294967295L, EnumU64 = 1234567890123456789m, Int16 = (short)46, Int32 = 47, Int64 = 48L, SignedByte = (short)60, Single = 54f, SpatialBGeometryCollection = (GeometryCollection)new NetTopologySuite.IO.WKTReader().Read(""GEOMETRYCOLLECTION (LINESTRING (1.1 2.2, 2.2 2.2, 2.2 1.1, 7.1 7.2), LINESTRING (7.1 7.2, 20.2 20.2, 20.2 1.1, 70.1 70.2), MULTIPOINT ((1.1 2.2), (2.2 2.2), (2.2 1.1)), POLYGON ((1.1 2.2, 2.2 2.2, 2.2 1.1, 1.1 2.2)), POLYGON ((10.1 20.2, 20.2 20.2, 20.2 10.1, 10.1 20.2)), POINT (1.1 2.2 3.3), MULTILINESTRING ((1.1 2.2, 2.2 2.2, 2.2 1.1, 7.1 7.2), (7.1 7.2, 20.2 20.2, 20.2 1.1, 70.1 70.2)), MULTIPOLYGON (((10.1 20.2, 20.2 20.2, 20.2 10.1, 10.1 20.2)), ((1.1 2.2, 2.2 2.2, 2.2 1.1, 1.1 2.2))))""), SpatialBLineString = (LineString)new NetTopologySuite.IO.WKTReader().Read(""LINESTRING (1.1 2.2, 2.2 2.2, 2.2 1.1, 7.1 7.2)""), SpatialBMultiLineString = (MultiLineString)new NetTopologySuite.IO.WKTReader().Read(""MULTILINESTRING ((1.1 2.2, 2.2 2.2, 2.2 1.1, 7.1 7.2), (7.1 7.2, 20.2 20.2, 20.2 1.1, 70.1 70.2))""), SpatialBMultiPoint = (MultiPoint)new NetTopologySuite.IO.WKTReader().Read(""MULTIPOINT ((1.1 2.2), (2.2 2.2), (2.2 1.1))""), SpatialBMultiPolygon = (MultiPolygon)new NetTopologySuite.IO.WKTReader().Read(""MULTIPOLYGON (((10.1 20.2, 20.2 20.2, 20.2 10.1, 10.1 20.2)), ((1.1 2.2, 2.2 2.2, 2.2 1.1, 1.1 2.2)))""), SpatialBPoint = (Point)new NetTopologySuite.IO.WKTReader().Read(""POINT (1.1 2.2 3.3)""), SpatialBPolygon = (Polygon)new NetTopologySuite.IO.WKTReader().Read(""POLYGON ((1.1 2.2, 2.2 2.2, 2.2 1.1, 1.1 2.2))""), SpatialCGeometryCollection = (GeometryCollection)new NetTopologySuite.IO.WKTReader().Read(""GEOMETRYCOLLECTION (LINESTRING (1.1 2.2, 2.2 2.2, 2.2 1.1, 7.1 7.2), LINESTRING (7.1 7.2, 20.2 20.2, 20.2 1.1, 70.1 70.2), MULTIPOINT ((1.1 2.2), (2.2 2.2), (2.2 1.1)), POLYGON ((1.1 2.2, 2.2 2.2, 2.2 1.1, 1.1 2.2)), POLYGON ((10.1 20.2, 20.2 20.2, 20.2 10.1, 10.1 20.2)), POINT (1.1 2.2 3.3), MULTILINESTRING ((1.1 2.2, 2.2 2.2, 2.2 1.1, 7.1 7.2), (7.1 7.2, 20.2 20.2, 20.2 1.1, 70.1 70.2)), MULTIPOLYGON (((10.1 20.2, 20.2 20.2, 20.2 10.1, 10.1 20.2)), ((1.1 2.2, 2.2 2.2, 2.2 1.1, 1.1 2.2))))""), SpatialCLineString = (LineString)new NetTopologySuite.IO.WKTReader().Read(""LINESTRING (1.1 2.2, 2.2 2.2, 2.2 1.1, 7.1 7.2)""), SpatialCMultiLineString = (MultiLineString)new NetTopologySuite.IO.WKTReader().Read(""MULTILINESTRING ((1.1 2.2, 2.2 2.2, 2.2 1.1, 7.1 7.2), (7.1 7.2, 20.2 20.2, 20.2 1.1, 70.1 70.2))""), SpatialCMultiPoint = (MultiPoint)new NetTopologySuite.IO.WKTReader().Read(""MULTIPOINT ((1.1 2.2), (2.2 2.2), (2.2 1.1))""), SpatialCMultiPolygon = (MultiPolygon)new NetTopologySuite.IO.WKTReader().Read(""MULTIPOLYGON (((10.1 20.2, 20.2 20.2, 20.2 10.1, 10.1 20.2)), ((1.1 2.2, 2.2 2.2, 2.2 1.1, 1.1 2.2)))""), SpatialCPoint = (Point)new NetTopologySuite.IO.WKTReader().Read(""POINT (1.1 2.2 3.3)""), SpatialCPolygon = (Polygon)new NetTopologySuite.IO.WKTReader().Read(""POLYGON ((1.1 2.2, 2.2 2.2, 2.2 1.1, 1.1 2.2))""), SpatialIGeometryCollection = (GeometryCollection)new NetTopologySuite.IO.WKTReader().Read(""GEOMETRYCOLLECTION (LINESTRING (1.1 2.2, 2.2 2.2, 2.2 1.1, 7.1 7.2), LINESTRING (7.1 7.2, 20.2 20.2, 20.2 1.1, 70.1 70.2), MULTIPOINT ((1.1 2.2), (2.2 2.2), (2.2 1.1)), POLYGON ((1.1 2.2, 2.2 2.2, 2.2 1.1, 1.1 2.2)), POLYGON ((10.1 20.2, 20.2 20.2, 20.2 10.1, 10.1 20.2)), POINT (1.1 2.2 3.3), MULTILINESTRING ((1.1 2.2, 2.2 2.2, 2.2 1.1, 7.1 7.2), (7.1 7.2, 20.2 20.2, 20.2 1.1, 70.1 70.2)), MULTIPOLYGON (((10.1 20.2, 20.2 20.2, 20.2 10.1, 10.1 20.2)), ((1.1 2.2, 2.2 2.2, 2.2 1.1, 1.1 2.2))))""), SpatialILineString = (LineString)new NetTopologySuite.IO.WKTReader().Read(""LINESTRING (1.1 2.2, 2.2 2.2, 2.2 1.1, 7.1 7.2)""), SpatialIMultiLineString = (MultiLineString)new NetTopologySuite.IO.WKTReader().Read(""MULTILINESTRING ((1.1 2.2, 2.2 2.2, 2.2 1.1, 7.1 7.2), (7.1 7.2, 20.2 20.2, 20.2 1.1, 70.1 70.2))""), SpatialIMultiPoint = (MultiPoint)new NetTopologySuite.IO.WKTReader().Read(""MULTIPOINT ((1.1 2.2), (2.2 2.2), (2.2 1.1))""), SpatialIMultiPolygon = (MultiPolygon)new NetTopologySuite.IO.WKTReader().Read(""MULTIPOLYGON (((10.1 20.2, 20.2 20.2, 20.2 10.1, 10.1 20.2)), ((1.1 2.2, 2.2 2.2, 2.2 1.1, 1.1 2.2)))""), SpatialIPoint = (Point)new NetTopologySuite.IO.WKTReader().Read(""POINT (1.1 2.2 3.3)""), SpatialIPolygon = (Polygon)new NetTopologySuite.IO.WKTReader().Read(""POLYGON ((1.1 2.2, 2.2 2.2, 2.2 1.1, 1.1 2.2))""), String = ""FortyThree"", TimeSpan = new TimeSpan(2, 3, 52, 53, 0), UnsignedInt16 = 56, UnsignedInt32 = 57L, UnsignedInt64 = 58m }, new { Id = 43, Boolean = true, Byte = (byte)55, Bytes = new byte[] { 44, 45 }, Character = ""9"", DateTime = new DateTime(1973, 9, 3, 12, 10, 42, 344, DateTimeKind.Utc), DateTimeOffset = new DateTimeOffset(new DateTime(1973, 9, 3, 12, 10, 42, 344, DateTimeKind.Unspecified), new TimeSpan(0, -1, 0, 0, 0)), Decimal = -50.0m, Double = -49.0, Enum16 = (short)1, Enum32 = 1, Enum64 = 1L, Enum8 = (byte)1, EnumS8 = (short)-128, EnumU16 = 65535, EnumU32 = 4294967295L, EnumU64 = 1234567890123456789m, Int16 = (short)-46, Int32 = -47, Int64 = -48L, SignedByte = (short)-60, Single = -54f, String = ""FortyThree"", TimeSpan = new TimeSpan(-2, -2, -7, -7, 0), UnsignedInt16 = 56, UnsignedInt32 = 57L, UnsignedInt64 = 58m }); }); #pragma warning restore 612, 618 } } } ", o => Assert.Collection( o.GetEntityTypes().SelectMany(e => e.GetData()), seed => { Assert.Equal(42, seed["Id"]); Assert.Equal("FortyThree", seed["String"]); Assert.Equal(new byte[] { 44, 45 }, seed["Bytes"]); Assert.Equal((short)46, seed["Int16"]); Assert.Equal((int)47, seed["Int32"]); Assert.Equal((long)48, seed["Int64"]); Assert.Equal(49.0, seed["Double"]); Assert.Equal(50.0m, seed["Decimal"]); Assert.Equal(new DateTime(1973, 9, 3, 12, 10, 42, 344, DateTimeKind.Utc), seed["DateTime"]); Assert.Equal(new DateTimeOffset(new DateTime(1973, 9, 3, 12, 10, 42, 344), new TimeSpan(1, 0, 0)), seed["DateTimeOffset"]); Assert.Equal(new TimeSpan(51, 52, 53), seed["TimeSpan"]); Assert.Equal(54.0f, seed["Single"]); Assert.Equal(true, seed["Boolean"]); Assert.Equal((byte)55, seed["Byte"]); Assert.Equal(56, seed["UnsignedInt16"]); Assert.Equal((long)57, seed["UnsignedInt32"]); Assert.Equal((decimal)58, seed["UnsignedInt64"]); Assert.Equal("9", seed["Character"]); Assert.Equal((short)60, seed["SignedByte"]); Assert.Equal(1L, seed["Enum64"]); Assert.Equal(1, seed["Enum32"]); Assert.Equal((short)1, seed["Enum16"]); Assert.Equal((byte)1, seed["Enum8"]); Assert.Equal(1234567890123456789m, seed["EnumU64"]); Assert.Equal(4294967295L, seed["EnumU32"]); Assert.Equal(65535, seed["EnumU16"]); Assert.Equal((short)-128, seed["EnumS8"]); Assert.Equal(geometryCollection, seed["SpatialBGeometryCollection"]); Assert.Equal(lineString1, seed["SpatialBLineString"]); Assert.Equal(multiLineString, seed["SpatialBMultiLineString"]); Assert.Equal(multiPoint, seed["SpatialBMultiPoint"]); Assert.Equal(multiPolygon, seed["SpatialBMultiPolygon"]); Assert.Equal(point1, seed["SpatialBPoint"]); Assert.Equal(polygon1, seed["SpatialBPolygon"]); Assert.Equal(geometryCollection, seed["SpatialCGeometryCollection"]); Assert.Equal(lineString1, seed["SpatialCLineString"]); Assert.Equal(multiLineString, seed["SpatialCMultiLineString"]); Assert.Equal(multiPoint, seed["SpatialCMultiPoint"]); Assert.Equal(multiPolygon, seed["SpatialCMultiPolygon"]); Assert.Equal(point1, seed["SpatialCPoint"]); Assert.Equal(polygon1, seed["SpatialCPolygon"]); Assert.Equal(geometryCollection, seed["SpatialIGeometryCollection"]); Assert.Equal(lineString1, seed["SpatialILineString"]); Assert.Equal(multiLineString, seed["SpatialIMultiLineString"]); Assert.Equal(multiPoint, seed["SpatialIMultiPoint"]); Assert.Equal(multiPolygon, seed["SpatialIMultiPolygon"]); Assert.Equal(point1, seed["SpatialIPoint"]); Assert.Equal(polygon1, seed["SpatialIPolygon"]); }, seed => { Assert.Equal(43, seed["Id"]); Assert.Equal("FortyThree", seed["String"]); Assert.Equal(new byte[] { 44, 45 }, seed["Bytes"]); Assert.Equal((short)-46, seed["Int16"]); Assert.Equal((int)-47, seed["Int32"]); Assert.Equal((long)-48, seed["Int64"]); Assert.Equal(-49.0, seed["Double"]); Assert.Equal(-50.0m, seed["Decimal"]); Assert.Equal(new DateTime(1973, 9, 3, 12, 10, 42, 344, DateTimeKind.Utc), seed["DateTime"]); Assert.Equal(new DateTimeOffset(new DateTime(1973, 9, 3, 12, 10, 42, 344), new TimeSpan(-1, 0, 0)), seed["DateTimeOffset"]); Assert.Equal(new TimeSpan(-51, 52, 53), seed["TimeSpan"]); Assert.Equal(-54.0f, seed["Single"]); Assert.Equal(true, seed["Boolean"]); Assert.Equal((byte)55, seed["Byte"]); Assert.Equal(56, seed["UnsignedInt16"]); Assert.Equal((long)57, seed["UnsignedInt32"]); Assert.Equal((decimal)58, seed["UnsignedInt64"]); Assert.Equal("9", seed["Character"]); Assert.Equal((short)-60, seed["SignedByte"]); Assert.Equal(1L, seed["Enum64"]); Assert.Equal(1, seed["Enum32"]); Assert.Equal((short)1, seed["Enum16"]); Assert.Equal((byte)1, seed["Enum8"]); Assert.Equal(1234567890123456789m, seed["EnumU64"]); Assert.Equal(4294967295L, seed["EnumU32"]); Assert.Equal(65535, seed["EnumU16"]); Assert.Equal((short)-128, seed["EnumS8"]); })); } #endif #endregion protected virtual string GetHeading() => @" modelBuilder .HasAnnotation(""Relational:MaxIdentifierLength"", 128) .HasAnnotation(""SqlServer:ValueGenerationStrategy"", SqlServerValueGenerationStrategy.IdentityColumn); "; protected virtual ICollection<BuildReference> GetReferences() => new List<BuildReference> { BuildReference.ByName("System.Runtime.Extensions"), BuildReference.ByName("Microsoft.EntityFrameworkCore"), BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational"), BuildReference.ByName("Microsoft.EntityFrameworkCore.SqlServer"), #if !Test21 BuildReference.ByName("GeoAPI"), BuildReference.ByName("NetTopologySuite"), #endif }; protected virtual string AddBoilerPlate(string code, bool usingSystem = false) => $@"// <auto-generated /> {(usingSystem ? @"using System; " : "")}using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace RootNamespace {{ [DbContext(typeof(DbContext))] partial class Snapshot : ModelSnapshot {{ protected override void BuildModel(ModelBuilder modelBuilder) {{ #pragma warning disable 612, 618{code} #pragma warning restore 612, 618 }} }} }} "; protected void Test(Action<ModelBuilder> buildModel, string expectedCode, Action<IModel> assert) { var modelBuilder = CreateConventionalModelBuilder(); modelBuilder.HasChangeTrackingStrategy(ChangeTrackingStrategy.Snapshot); buildModel(modelBuilder); modelBuilder.GetInfrastructure().Metadata.Validate(); CreateModelValidator().Validate(modelBuilder.Model); var model = modelBuilder.Model; var codeHelper = new CSharpHelper(); var generator = new CSharpMigrationsGenerator( new MigrationsCodeGeneratorDependencies(), new CSharpMigrationsGeneratorDependencies( codeHelper, new CSharpMigrationOperationGenerator( new CSharpMigrationOperationGeneratorDependencies(codeHelper)), new CSharpSnapshotGenerator( new CSharpSnapshotGeneratorDependencies( codeHelper, new SqlServerTypeMappingSource( TestServiceFactory.Instance.Create<TypeMappingSourceDependencies>(), TestServiceFactory.Instance.Create<RelationalTypeMappingSourceDependencies>()))))); var code = generator.GenerateSnapshot("RootNamespace", typeof(DbContext), "Snapshot", model); Assert.Equal(expectedCode, code, ignoreLineEndingDifferences: true); var build = new BuildSource { Sources = { code } }; foreach (var buildReference in GetReferences()) { build.References.Add(buildReference); } var assembly = build.BuildInMemory(); var factoryType = assembly.GetType("RootNamespace.Snapshot"); var buildModelMethod = factoryType.GetTypeInfo().GetMethod( "BuildModel", BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(ModelBuilder)}, null); var builder = new ModelBuilder(new ConventionSet()); buildModelMethod.Invoke( Activator.CreateInstance(factoryType), new object[] { builder }); var value = builder.Model; Assert.NotNull(value); var reporter = new TestOperationReporter(); assert(new SnapshotModelProcessor(reporter).Process(value)); } protected ModelBuilder CreateConventionalModelBuilder() { var serviceProvider = new ServiceCollection() .AddEntityFrameworkSqlServer() .AddEntityFrameworkSqlServerNetTopologySuite() .AddDbContext<DbContext>(o => o.UseSqlServer("Server=.", b => b.UseNetTopologySuite())) .BuildServiceProvider(); using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope()) { using (var context = serviceScope.ServiceProvider.GetService<DbContext>()) { return new ModelBuilder(ConventionSet.CreateConventionSet(context)); } } } protected ModelValidator CreateModelValidator() => new SqlServerModelValidator( new ModelValidatorDependencies( new DiagnosticsLogger<DbLoggerCategory.Model.Validation>( new ListLoggerFactory(l => false), new LoggingOptions(), new DiagnosticListener("Fake")), new DiagnosticsLogger<DbLoggerCategory.Model>( new ListLoggerFactory(l => false), new LoggingOptions(), new DiagnosticListener("Fake"))), new RelationalModelValidatorDependencies( #pragma warning disable 618 TestServiceFactory.Instance.Create<ObsoleteRelationalTypeMapper>(), #pragma warning restore 618 new SqlServerTypeMappingSource( TestServiceFactory.Instance.Create<TypeMappingSourceDependencies>(), TestServiceFactory.Instance.Create<RelationalTypeMappingSourceDependencies>()))); } }
46.433251
619
0.517417
[ "Apache-2.0" ]
aprognimak/EntityFrameworkCore
test/EFCore.Design.Tests/Migrations/ModelSnapshotSqlServerTest.cs
150,260
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.Resources.MSGraph.Models.ApiV10 { using Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Runtime.PowerShell; /// <summary>Collection of directoryObject</summary> [System.ComponentModel.TypeConverter(typeof(CollectionOfDirectoryObjectTypeConverter))] public partial class CollectionOfDirectoryObject { /// <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> /// <c>OverrideToString</c> will be called if it is implemented. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="stringResult">/// instance serialized to a string, normally it is a Json</param> /// <param name="returnNow">/// set returnNow to true if you provide a customized OverrideToString function</param> partial void OverrideToString(ref string stringResult, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.CollectionOfDirectoryObject" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal CollectionOfDirectoryObject(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("Value")) { ((Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.ICollectionOfDirectoryObjectInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.IMicrosoftGraphDirectoryObject[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.ICollectionOfDirectoryObjectInternal)this).Value, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.IMicrosoftGraphDirectoryObject>(__y, Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.MicrosoftGraphDirectoryObjectTypeConverter.ConvertFrom)); } if (content.Contains("OdataNextLink")) { ((Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.ICollectionOfDirectoryObjectInternal)this).OdataNextLink = (string) content.GetValueForProperty("OdataNextLink",((Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.ICollectionOfDirectoryObjectInternal)this).OdataNextLink, global::System.Convert.ToString); } // this type is a dictionary; copy elements from source to here. CopyFrom(content); AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.CollectionOfDirectoryObject" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal CollectionOfDirectoryObject(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("Value")) { ((Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.ICollectionOfDirectoryObjectInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.IMicrosoftGraphDirectoryObject[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.ICollectionOfDirectoryObjectInternal)this).Value, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.IMicrosoftGraphDirectoryObject>(__y, Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.MicrosoftGraphDirectoryObjectTypeConverter.ConvertFrom)); } if (content.Contains("OdataNextLink")) { ((Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.ICollectionOfDirectoryObjectInternal)this).OdataNextLink = (string) content.GetValueForProperty("OdataNextLink",((Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.ICollectionOfDirectoryObjectInternal)this).OdataNextLink, global::System.Convert.ToString); } // this type is a dictionary; copy elements from source to here. CopyFrom(content); AfterDeserializePSObject(content); } /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.CollectionOfDirectoryObject" /// />. /// </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.Resources.MSGraph.Models.ApiV10.ICollectionOfDirectoryObject" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.ICollectionOfDirectoryObject DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new CollectionOfDirectoryObject(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.CollectionOfDirectoryObject" /// />. /// </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.Resources.MSGraph.Models.ApiV10.ICollectionOfDirectoryObject" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.Models.ApiV10.ICollectionOfDirectoryObject DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new CollectionOfDirectoryObject(content); } /// <summary> /// Creates a new instance of <see cref="CollectionOfDirectoryObject" />, 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.Resources.MSGraph.Models.ApiV10.ICollectionOfDirectoryObject FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Resources.MSGraph.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.Resources.MSGraph.Runtime.SerializationMode.IncludeAll)?.ToString(); public override string ToString() { var returnNow = false; var result = global::System.String.Empty; OverrideToString(ref result, ref returnNow); if (returnNow) { return result; } return ToJsonString(); } } /// Collection of directoryObject [System.ComponentModel.TypeConverter(typeof(CollectionOfDirectoryObjectTypeConverter))] public partial interface ICollectionOfDirectoryObject { } }
64.732955
667
0.691828
[ "MIT" ]
Agazoth/azure-powershell
src/Resources/MSGraph.Autorest/generated/api/Models/ApiV10/CollectionOfDirectoryObject.PowerShell.cs
11,218
C#
using NUnit.Framework; namespace Voorhees.Tests { [TestFixture] public class JsonReaderTest { [Test] public void Int() { var test = JsonReader.Read("1"); Assert.That(test.Type, Is.EqualTo(JsonType.Int)); Assert.That((int) test, Is.EqualTo(1)); } [Test] public void NegativeInt() { var test = JsonReader.Read("-1"); Assert.That(test.Type, Is.EqualTo(JsonType.Int)); Assert.That((int) test, Is.EqualTo(-1)); } [Test] public void Float() { var test = JsonReader.Read("1.5"); Assert.That(test.Type, Is.EqualTo(JsonType.Float)); Assert.That((float) test, Is.EqualTo(1.5f)); } [Test] public void NegativeFloat() { var test = JsonReader.Read("-1.5"); Assert.That(test.Type, Is.EqualTo(JsonType.Float)); Assert.That((float) test, Is.EqualTo(-1.5f)); } [Test] public void FloatPositiveE() { var test = JsonReader.Read("1.5e+1"); Assert.That(test.Type, Is.EqualTo(JsonType.Float)); Assert.That((float) test, Is.EqualTo(15f)); } [Test] public void FloatE() { var test = JsonReader.Read("1.5e2"); Assert.That(test.Type, Is.EqualTo(JsonType.Float)); Assert.That((float) test, Is.EqualTo(1.5e2f)); } [Test] public void FloatNegativeE() { var test = JsonReader.Read("1.5e-2"); Assert.That(test.Type, Is.EqualTo(JsonType.Float)); Assert.That((float) test, Is.EqualTo(1.5e-2f)); } [Test] public void NegativeFloatPositiveE() { var test = JsonReader.Read("-1.5e+1"); Assert.That(test.Type, Is.EqualTo(JsonType.Float)); Assert.That((float) test, Is.EqualTo(-15f)); } [Test] public void NegativeFloatE() { var test = JsonReader.Read("-1.5e2"); Assert.That(test.Type, Is.EqualTo(JsonType.Float)); Assert.That((float) test, Is.EqualTo(-1.5e2f)); } [Test] public void NegativeFloatNegativeE() { var test = JsonReader.Read("-1.5e-2"); Assert.That(test.Type, Is.EqualTo(JsonType.Float)); Assert.That((float) test, Is.EqualTo(-1.5e-2f)); } [Test] public void String() { var test = JsonReader.Read("\"test\""); Assert.That(test.Type, Is.EqualTo(JsonType.String)); Assert.That((string) test, Is.EqualTo("test")); } [Test] public void StringWithEscapedQuotes() { var test = JsonReader.Read("\"\\\\\""); Assert.That(test.Type, Is.EqualTo(JsonType.String)); Assert.That((string) test, Is.EqualTo("\\")); } [Test] public void True() { var test = JsonReader.Read("true"); Assert.That(test.Type, Is.EqualTo(JsonType.Boolean)); Assert.That((bool) test, Is.True); } [Test] public void False() { var test = JsonReader.Read("false"); Assert.That(test.Type, Is.EqualTo(JsonType.Boolean)); Assert.That((bool) test, Is.False); } [Test] public void Null() { var test = JsonReader.Read("null"); Assert.That(test.Type, Is.EqualTo(JsonType.Null)); Assert.That(test.IsNull); } [Test] public void EmptyArray() { var test = JsonReader.Read("[]"); Assert.That(test.Type, Is.EqualTo(JsonType.Array)); Assert.That(test.Count, Is.EqualTo(0)); } [Test] public void SimpleArray() { var test = JsonReader.Read("[1]"); Assert.That(test.Type, Is.EqualTo(JsonType.Array)); Assert.That(test.Count, Is.EqualTo(1)); Assert.That(test[0].Type, Is.EqualTo(JsonType.Int)); Assert.That((int) test[0], Is.EqualTo(1)); } [Test] public void MultivalueArray() { var test = JsonReader.Read("[1, 2, 3]"); Assert.That(test.Type, Is.EqualTo(JsonType.Array)); Assert.That(test.Count, Is.EqualTo(3)); for (int i = 0; i < 3; ++i) { Assert.That(test[i].Type, Is.EqualTo(JsonType.Int)); Assert.That((int) test[i], Is.EqualTo(i + 1)); } } [Test] public void NestedArray() { var test = JsonReader.Read("[[1, 2], [3, 4]]"); Assert.That(test.Type, Is.EqualTo(JsonType.Array)); Assert.That(test.Count, Is.EqualTo(2)); Assert.That(test[0].Type, Is.EqualTo(JsonType.Array)); Assert.That(test[0].Count, Is.EqualTo(2)); Assert.That(test[0][0].Type, Is.EqualTo(JsonType.Int)); Assert.That((int) test[0][0], Is.EqualTo(1)); Assert.That(test[0][1].Type, Is.EqualTo(JsonType.Int)); Assert.That((int) test[0][1], Is.EqualTo(2)); Assert.That(test[1][0].Type, Is.EqualTo(JsonType.Int)); Assert.That((int) test[1][0], Is.EqualTo(3)); Assert.That(test[1][1].Type, Is.EqualTo(JsonType.Int)); Assert.That((int) test[1][1], Is.EqualTo(4)); } [Test] public void MultipleNestedArrays() { var outer = JsonReader.Read("[[1, 2, 3], [4, [5]]]"); Assert.That(outer.Type, Is.EqualTo(JsonType.Array)); Assert.That(outer.Count, Is.EqualTo(2)); JsonValue test = outer[0]; Assert.That(test.Type, Is.EqualTo(JsonType.Array)); Assert.That(test.Count, Is.EqualTo(3)); for (int i = 0; i < 3; ++i) { Assert.That(test[i].Type, Is.EqualTo(JsonType.Int)); Assert.That((int) test[i], Is.EqualTo(i + 1)); } test = outer[1]; Assert.That(test.Type, Is.EqualTo(JsonType.Array)); Assert.That(test.Count, Is.EqualTo(2)); Assert.That(test[0].Type, Is.EqualTo(JsonType.Int)); Assert.That((int) test[0], Is.EqualTo(4)); test = test[1]; Assert.That(test.Type, Is.EqualTo(JsonType.Array)); Assert.That(test.Count, Is.EqualTo(1)); Assert.That(test[0].Type, Is.EqualTo(JsonType.Int)); Assert.That((int) test[0], Is.EqualTo(5)); } [Test] public void ArrayOfAllTypes() { var test = JsonReader.Read(@"[1, 1.5, ""test"", true, false, null, []]"); Assert.That(test.Type, Is.EqualTo(JsonType.Array)); Assert.That(test.Count, Is.EqualTo(7)); Assert.That(test[0].Type, Is.EqualTo(JsonType.Int)); Assert.That((int) test[0], Is.EqualTo(1)); Assert.That(test[1].Type, Is.EqualTo(JsonType.Float)); Assert.That((float) test[1], Is.EqualTo(1.5)); Assert.That(test[2].Type, Is.EqualTo(JsonType.String)); Assert.That((string) test[2], Is.EqualTo("test")); Assert.That(test[3].Type, Is.EqualTo(JsonType.Boolean)); Assert.That((bool) test[3], Is.True); Assert.That(test[4].Type, Is.EqualTo(JsonType.Boolean)); Assert.That((bool) test[4], Is.False); Assert.That(test[5].Type, Is.EqualTo(JsonType.Null)); Assert.That(test[6].Type, Is.EqualTo(JsonType.Array)); Assert.That(test[6].Count, Is.EqualTo(0)); } [Test] public void MissingComma() { Assert.Throws<InvalidJsonException>(() => { JsonReader.Read("[1 2]"); }); } [Test] public void ExtraLeadingComma() { Assert.Throws<InvalidJsonException>(() => { JsonReader.Read("[,1, 2]"); }); } [Test] public void ExtraSeparatingComma() { Assert.Throws<InvalidJsonException>(() => { JsonReader.Read("[1,, 2]"); }); } [Test] public void ExtraTrailingComma() { Assert.Throws<InvalidJsonException>(() => { JsonReader.Read("[1, 2,]"); }); } [Test] public void TooManyClosingArrays() { Assert.Throws<InvalidJsonException>(() => { JsonReader.Read("[1, 2]]"); }); } [Test] public void TooFewClosingArrays() { Assert.Throws<InvalidJsonException>(() => { JsonReader.Read("[1, 2"); }); } [Test] public void EmptyObject() { var test = JsonReader.Read("{}"); Assert.That(test.Type, Is.EqualTo(JsonType.Object)); Assert.That(test.Count, Is.EqualTo(0)); } [Test] public void SimpleObject() { var test = JsonReader.Read("{\"test\": 1}"); Assert.That(test.Type, Is.EqualTo(JsonType.Object)); Assert.That(test.Count, Is.EqualTo(1)); Assert.That(test.ContainsKey("test"), Is.True); Assert.That(test["test"].Type, Is.EqualTo(JsonType.Int)); Assert.That((int) test["test"], Is.EqualTo(1)); } [Test] public void MultiObject() { var test = JsonReader.Read("{\"test\": 1, \"test2\": 2}"); Assert.That(test.Type, Is.EqualTo(JsonType.Object)); Assert.That(test.Count, Is.EqualTo(2)); Assert.That(test.ContainsKey("test"), Is.True); Assert.That(test["test"].Type, Is.EqualTo(JsonType.Int)); Assert.That((int) test["test"], Is.EqualTo(1)); Assert.That(test.ContainsKey("test2"), Is.True); Assert.That(test["test2"].Type, Is.EqualTo(JsonType.Int)); Assert.That((int) test["test2"], Is.EqualTo(2)); } [Test] public void NestedObject() { var test = JsonReader.Read("{\"test\": {\"test2\": 1}}"); Assert.That(test.Type, Is.EqualTo(JsonType.Object)); Assert.That(test.Count, Is.EqualTo(1)); Assert.That(test.ContainsKey("test"), Is.True); Assert.That(test["test"].Type, Is.EqualTo(JsonType.Object)); Assert.That(test["test"].ContainsKey("test2"), Is.True); Assert.That(test["test"]["test2"].Type, Is.EqualTo(JsonType.Int)); Assert.That((int) test["test"]["test2"], Is.EqualTo(1)); } [Test] public void ObjectMappingToArray() { var test = JsonReader.Read("{\"test\": [1, 2, 3]}"); Assert.That(test.Type, Is.EqualTo(JsonType.Object)); Assert.That(test.Count, Is.EqualTo(1)); Assert.That(test.ContainsKey("test"), Is.True); Assert.That(test["test"].Type, Is.EqualTo(JsonType.Array)); Assert.That(test["test"].Count, Is.EqualTo(3)); for (int i = 0; i < 3; ++i) { Assert.That(test["test"][i].Type, Is.EqualTo(JsonType.Int)); Assert.That((int) test["test"][i], Is.EqualTo(i + 1)); } } [Test] public void SpecialCharacters() { var test = JsonReader.Read("\"\\\\\""); Assert.That(test.Type, Is.EqualTo(JsonType.String)); Assert.That((string) test, Is.EqualTo("\\")); test = JsonReader.Read("\"\\\"\""); Assert.That(test.Type, Is.EqualTo(JsonType.String)); Assert.That((string) test, Is.EqualTo("\"")); test = JsonReader.Read("\"\\/\""); Assert.That(test.Type, Is.EqualTo(JsonType.String)); Assert.That((string) test, Is.EqualTo("/")); test = JsonReader.Read("\"\\b\""); Assert.That(test.Type, Is.EqualTo(JsonType.String)); Assert.That((string) test, Is.EqualTo("\b")); test = JsonReader.Read("\"\\b\""); Assert.That(test.Type, Is.EqualTo(JsonType.String)); Assert.That((string) test, Is.EqualTo("\b")); test = JsonReader.Read("\"\\f\""); Assert.That(test.Type, Is.EqualTo(JsonType.String)); Assert.That((string) test, Is.EqualTo("\f")); test = JsonReader.Read("\"\\n\""); Assert.That(test.Type, Is.EqualTo(JsonType.String)); Assert.That((string) test, Is.EqualTo("\n")); test = JsonReader.Read("\"\\r\""); Assert.That(test.Type, Is.EqualTo(JsonType.String)); Assert.That((string) test, Is.EqualTo("\r")); test = JsonReader.Read("\"\\t\""); Assert.That(test.Type, Is.EqualTo(JsonType.String)); Assert.That((string) test, Is.EqualTo("\t")); // ☃ test = JsonReader.Read("\"\\u2603\""); Assert.That(test.Type, Is.EqualTo(JsonType.String)); Assert.That((string) test, Is.EqualTo("\u2603")); } [Test] public void DisallowControlCharacters() { for (int i = 0; i < 0x20; i++) { string controlChar = char.ConvertFromUtf32(i); Assert.Throws<InvalidJsonException>(() => { JsonReader.Read($"\"{controlChar}\""); }); } Assert.Throws<InvalidJsonException>(() => { JsonReader.Read($"\"{char.ConvertFromUtf32(0x7F)}\""); }); for (int i = 0x80; i <= 0x9F; i++) { string controlChar = char.ConvertFromUtf32(i); Assert.Throws<InvalidJsonException>(() => { JsonReader.Read($"\"{controlChar}\""); }); } } } }
31.495775
105
0.6359
[ "MIT" ]
grahamboree/Voorhees
voorhees_tests/JsonReaderTest.cs
11,185
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Net; using System.Text; using System.Windows.Forms; namespace CrashHandler { public partial class Form1 : Form { string data = ""; string nick = "Unknown"; static string ReadAllText(string path) { using (var r = new StreamReader(path)) { return r.ReadToEnd(); } } public Form1(string input) { data = input; try { nick = ReadAllText(@"lhmp\nickname.txt"); } catch { nick = "Unknown"; } InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { textBox1.Text = nick; textBox1.ReadOnly = true; label5.Text += "0x"+data.Split('|')[0] + " at Module: " + data.Split('|')[2] + "\n" + ("EAX: " + data.Split('|')[1].Split('@')[0] + " ECX: " + data.Split('|')[1].Split('@')[1] + " EDX: " + data.Split('|')[1].Split('@')[2] + " EBX: " + data.Split('|')[1].Split('@')[3] + "\n" + " ESP: " + data.Split('|')[1].Split('@')[4] + "EBP: " + data.Split('|')[1].Split('@')[5] + " ESI: " + data.Split('|')[1].Split('@')[6] + " EDI: " + data.Split('|')[1].Split('@')[7]); textBox2.Focus(); this.Text = "LH:MP Crash Sender"; } private void button2_Click(object sender, EventArgs e) { Application.ExitThread(); } private void button1_Click(object sender, EventArgs e) { string popis = "", rep = ""; popis = textBox2.Text.Replace("|", "").Replace("#", ""); rep = textBox3.Text.Replace("|", "").Replace("#", ""); string send = data + "|" + nick + "|" + popis + "|" + rep; send = send.Replace(' ', '+'); //MessageBox.Show(send); using (var wb = new WebClient()) { var d = new NameValueCollection(); d["data"] = send; // ASCIIEncoding a = new ASCIIEncoding(); var response = wb.UploadValues(new Uri("http://www.lh-mp.eu/query/crash.php"), "POST", d); //MessageBox.Show(a.GetString((byte[])response.GetValue(0),0,response.Length)); panel1.Visible = true; timer1.Start(); } } private void timer1_Tick(object sender, EventArgs e) { Application.ExitThread(); } private void label1_Click(object sender, EventArgs e) { } private void label5_Click(object sender, EventArgs e) { } } }
29.588235
187
0.461895
[ "Apache-2.0" ]
LHMPTeam/lhmp-old
Others/CrashHandler/Form1.cs
3,020
C#
using System.Windows; namespace WinTOTAL_Quick_List_Copier.ui { public static class UiUtilities { public static void ShowErrorMessage(string message) { MessageBox.Show(message, "Error"); } } }
18.692308
59
0.633745
[ "MIT" ]
onstottj/WinTOTAL-Quick-List-Copier
WinTOTAL Quick List Copier/ui/UiUtilities.cs
245
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 Xunit; namespace System.Xml.Tests { public class NameTableTests { [Fact] public static void RespectManuallyAddedReference() { // Test depends that the string used here is also automatically added to XmlDocument XmlNameTable string targetStr = "#DoCument".ToLowerInvariant(); // Avoid interning var d = new XmlDocument(); string defaultXmlDocumentTargetStr = d.NameTable.Get(targetStr); Assert.NotSame(targetStr, defaultXmlDocumentTargetStr); Assert.Equal(targetStr, defaultXmlDocumentTargetStr); // Create a NameTable to be shared and ensure that it is using the same reference as the test var nt = new NameTable(); nt.Add(targetStr); Assert.Same(targetStr, nt.Get(targetStr)); // The one added earlier should be the actual reference d = new XmlDocument(nt); Assert.Same(targetStr, d.Name); } [Fact] public static void RespectTypesDerivedFromNameTable() { var customNameTable = new CustomNameTable(); var xmlDocument = new XmlDocument(customNameTable); Assert.True(customNameTable.NumberOfCallsToAddStringMethod > 0); } // We expect users to derive from XmlNameTable but since NameTable it not sealed // it is possible for someone to derive from it, override its methods and so on. // This type is used to test that XmlDocument is properly handling this case. internal class CustomNameTable : NameTable { public int NumberOfCallsToAddStringMethod { get; private set; } public override string Add(string key) { ++NumberOfCallsToAddStringMethod; return base.Add(key); } } } }
38.648148
109
0.636799
[ "MIT" ]
06needhamt/runtime
src/libraries/System.Private.Xml/tests/XmlDocument/XmlDocumentTests/NameTableTests.cs
2,089
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version: 17.0.0.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ namespace LlvmBindingsGenerator.Templates { using System.Linq; using System.Text; using System.Collections.Generic; using System; /// <summary> /// Class to produce the template output /// </summary> #line 1 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")] internal partial class PerHeaderInteropTemplate : PerHeaderInteropTemplateBase { #line hidden /// <summary> /// Create the template output /// </summary> public virtual string TransformText() { this.Write("// ------------------------------------------------------------------------------" + "\r\n// <auto-generated>\r\n// This code was generated by a tool.\r\n// Runtime" + " Version: "); #line 9 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(ToolVersion)); #line default #line hidden this.Write("\r\n//\r\n// Changes to this file may cause incorrect behavior and will be lost i" + "f\r\n// the code is regenerated.\r\n// </auto-generated>\r\n// -------------------" + "-----------------------------------------------------------\r\n#nullable disable\r\n" + "\r\n"); #line 17 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" foreach(var import in Imports ) { #line default #line hidden this.Write("using "); #line 18 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(import)); #line default #line hidden this.Write(";\r\n"); #line 19 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" } #line default #line hidden this.Write("\r\nnamespace Ubiquity.NET.Llvm.Interop\r\n{\r\n"); #line 23 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" foreach(var e in Enums){ #line default #line hidden this.Write(" /// <include file=\""); #line 24 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(XDocIncludePath)); #line default #line hidden this.Write("\" path=\'LibLlvmAPI/Enumeration[@name=\""); #line 24 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(e.Name)); #line default #line hidden this.Write("\"]/*[not(self::Item)]\' />\r\n [GeneratedCode(\"LlvmBindingsGenerator\",\""); #line 25 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(ToolVersion)); #line default #line hidden this.Write("\")]\r\n public enum "); #line 26 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(e.Name)); #line default #line hidden this.Write(" : "); #line 26 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(e.BaseType)); #line default #line hidden this.Write("\r\n {\r\n"); #line 28 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" foreach(var m in e.Members) { #line default #line hidden #line 29 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" foreach(var commentLine in e.Comments){ #line default #line hidden this.Write(" // "); #line 30 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(commentLine)); #line default #line hidden this.Write("\r\n"); #line 31 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" } #line default #line hidden this.Write(" /// <include file=\""); #line 32 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(XDocIncludePath)); #line default #line hidden this.Write("\" path=\'LibLlvmAPI/Enumeration[@name=\""); #line 32 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(e.Name)); #line default #line hidden this.Write("\"]/Item[@name=\""); #line 32 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(m.Name)); #line default #line hidden this.Write("\"]/*\' />\r\n "); #line 33 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(m.Name)); #line default #line hidden this.Write(" = "); #line 33 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(m.Value)); #line default #line hidden this.Write(",\r\n"); #line 34 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" } #line default #line hidden this.Write(" }\r\n\r\n"); #line 37 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" } foreach(var d in Delegates) { #line default #line hidden #line 39 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" foreach(var commentLine in d.Comments){ #line default #line hidden this.Write(" // "); #line 40 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(commentLine)); #line default #line hidden this.Write("\r\n"); #line 41 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" } #line default #line hidden this.Write(" /// <include file=\""); #line 42 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(XDocIncludePath)); #line default #line hidden this.Write("\" path=\'LibLlvmAPI/Delegate[@name=\""); #line 42 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(d.Name)); #line default #line hidden this.Write("\"]/*\' />\r\n"); #line 43 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" foreach( var attrib in d.Attributes) { #line default #line hidden this.Write(" "); #line 44 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(attrib.AsString())); #line default #line hidden this.Write("\r\n"); #line 45 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" } #line default #line hidden this.Write(" "); #line 46 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(d)); #line default #line hidden this.Write("\r\n"); #line 47 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" } #line default #line hidden #line 48 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" foreach(var s in ValueTypes){ var parsedComment = new ParsedComment(s); foreach(var commentLine in parsedComment){ #line default #line hidden this.Write(" // "); #line 51 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(commentLine)); #line default #line hidden this.Write("\r\n"); #line 52 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" } #line default #line hidden this.Write(" /// <include file=\""); #line 53 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(XDocIncludePath)); #line default #line hidden this.Write("\" path=\'LibLlvmAPI/Struct[@name=\""); #line 53 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(s.Name)); #line default #line hidden this.Write("\"]/*[not(self::Field)]\' />\r\n"); #line 54 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" foreach(var sa in s.Attributes) { #line default #line hidden this.Write(" "); #line 55 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(sa.AsString())); #line default #line hidden this.Write("\r\n"); #line 56 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" } #line default #line hidden this.Write(" public struct "); #line 57 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(s.Name)); #line default #line hidden this.Write("\r\n {\r\n"); #line 59 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" foreach(var fld in s.Fields){ #line default #line hidden this.Write(" /// <include file=\""); #line 60 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(XDocIncludePath)); #line default #line hidden this.Write("\" path=\'LibLlvmAPI/struct[@name=\""); #line 60 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(s.Name)); #line default #line hidden this.Write("\"]/Field[@name=\""); #line 60 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(fld.Name)); #line default #line hidden this.Write("\"]/*\' />\r\n"); #line 61 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" foreach(var fa in fld.Attributes) { #line default #line hidden this.Write(" "); #line 62 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(fa.AsString())); #line default #line hidden this.Write("\r\n"); #line 63 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" } #line default #line hidden this.Write(" public "); #line 64 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(GetManagedName(fld.Type))); #line default #line hidden this.Write(" "); #line 64 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(fld.Name)); #line default #line hidden this.Write(";\r\n"); #line 65 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" } #line default #line hidden this.Write(" }\r\n\r\n"); #line 68 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" } #line default #line hidden this.Write(" public static partial class NativeMethods\r\n {\r\n"); #line 71 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" foreach(var f in Functions) { #line default #line hidden this.Write(" /// <include file=\""); #line 72 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(XDocIncludePath)); #line default #line hidden this.Write("\" path=\'LibLlvmAPI/Function[@name=\""); #line 72 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(f.Name)); #line default #line hidden this.Write("\"]/*\' />\r\n"); #line 73 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" foreach(var a in f.Attributes) { #line default #line hidden this.Write(" "); #line 74 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(a.AsString())); #line default #line hidden this.Write("\r\n"); #line 75 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" } #line default #line hidden this.Write(" "); #line 76 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" this.Write(this.ToStringHelper.ToStringWithCulture(f)); #line default #line hidden this.Write("\r\n"); #line 77 "D:\GitHub\Ubiquity.NET\Llvm.Net\src\Interop\LlvmBindingsGenerator\Templates\T4\PerHeaderInteropTemplate.tt" } #line default #line hidden this.Write(" }\r\n}\r\n"); return this.GenerationEnvironment.ToString(); } } #line default #line hidden #region Base class /// <summary> /// Base class for this transformation /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")] internal class PerHeaderInteropTemplateBase { #region Fields private global::System.Text.StringBuilder generationEnvironmentField; private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField; private global::System.Collections.Generic.List<int> indentLengthsField; private string currentIndentField = ""; private bool endsWithNewline; private global::System.Collections.Generic.IDictionary<string, object> sessionField; #endregion #region Properties /// <summary> /// The string builder that generation-time code is using to assemble generated output /// </summary> protected System.Text.StringBuilder GenerationEnvironment { get { if ((this.generationEnvironmentField == null)) { this.generationEnvironmentField = new global::System.Text.StringBuilder(); } return this.generationEnvironmentField; } set { this.generationEnvironmentField = value; } } /// <summary> /// The error collection for the generation process /// </summary> public System.CodeDom.Compiler.CompilerErrorCollection Errors { get { if ((this.errorsField == null)) { this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection(); } return this.errorsField; } } /// <summary> /// A list of the lengths of each indent that was added with PushIndent /// </summary> private System.Collections.Generic.List<int> indentLengths { get { if ((this.indentLengthsField == null)) { this.indentLengthsField = new global::System.Collections.Generic.List<int>(); } return this.indentLengthsField; } } /// <summary> /// Gets the current indent we use when adding lines to the output /// </summary> public string CurrentIndent { get { return this.currentIndentField; } } /// <summary> /// Current transformation session /// </summary> public virtual global::System.Collections.Generic.IDictionary<string, object> Session { get { return this.sessionField; } set { this.sessionField = value; } } #endregion #region Transform-time helpers /// <summary> /// Write text directly into the generated output /// </summary> public void Write(string textToAppend) { if (string.IsNullOrEmpty(textToAppend)) { return; } // If we're starting off, or if the previous text ended with a newline, // we have to append the current indent first. if (((this.GenerationEnvironment.Length == 0) || this.endsWithNewline)) { this.GenerationEnvironment.Append(this.currentIndentField); this.endsWithNewline = false; } // Check if the current text ends with a newline if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture)) { this.endsWithNewline = true; } // This is an optimization. If the current indent is "", then we don't have to do any // of the more complex stuff further down. if ((this.currentIndentField.Length == 0)) { this.GenerationEnvironment.Append(textToAppend); return; } // Everywhere there is a newline in the text, add an indent after it textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField)); // If the text ends with a newline, then we should strip off the indent added at the very end // because the appropriate indent will be added when the next time Write() is called if (this.endsWithNewline) { this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length)); } else { this.GenerationEnvironment.Append(textToAppend); } } /// <summary> /// Write text directly into the generated output /// </summary> public void WriteLine(string textToAppend) { this.Write(textToAppend); this.GenerationEnvironment.AppendLine(); this.endsWithNewline = true; } /// <summary> /// Write formatted text directly into the generated output /// </summary> public void Write(string format, params object[] args) { this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args)); } /// <summary> /// Write formatted text directly into the generated output /// </summary> public void WriteLine(string format, params object[] args) { this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args)); } /// <summary> /// Raise an error /// </summary> public void Error(string message) { System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError(); error.ErrorText = message; this.Errors.Add(error); } /// <summary> /// Raise a warning /// </summary> public void Warning(string message) { System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError(); error.ErrorText = message; error.IsWarning = true; this.Errors.Add(error); } /// <summary> /// Increase the indent /// </summary> public void PushIndent(string indent) { if ((indent == null)) { throw new global::System.ArgumentNullException("indent"); } this.currentIndentField = (this.currentIndentField + indent); this.indentLengths.Add(indent.Length); } /// <summary> /// Remove the last indent that was added with PushIndent /// </summary> public string PopIndent() { string returnValue = ""; if ((this.indentLengths.Count > 0)) { int indentLength = this.indentLengths[(this.indentLengths.Count - 1)]; this.indentLengths.RemoveAt((this.indentLengths.Count - 1)); if ((indentLength > 0)) { returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength)); this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength)); } } return returnValue; } /// <summary> /// Remove any indentation /// </summary> public void ClearIndent() { this.indentLengths.Clear(); this.currentIndentField = ""; } #endregion #region ToString Helpers /// <summary> /// Utility class to produce culture-oriented representation of an object as a string. /// </summary> public class ToStringInstanceHelper { private System.IFormatProvider formatProviderField = global::System.Globalization.CultureInfo.InvariantCulture; /// <summary> /// Gets or sets format provider to be used by ToStringWithCulture method. /// </summary> public System.IFormatProvider FormatProvider { get { return this.formatProviderField ; } set { if ((value != null)) { this.formatProviderField = value; } } } /// <summary> /// This is called from the compile/run appdomain to convert objects within an expression block to a string /// </summary> public string ToStringWithCulture(object objectToConvert) { if ((objectToConvert == null)) { throw new global::System.ArgumentNullException("objectToConvert"); } System.Type t = objectToConvert.GetType(); System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] { typeof(System.IFormatProvider)}); if ((method == null)) { return objectToConvert.ToString(); } else { return ((string)(method.Invoke(objectToConvert, new object[] { this.formatProviderField }))); } } } private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper(); /// <summary> /// Helper to produce culture-oriented representation of an object as a string /// </summary> public ToStringInstanceHelper ToStringHelper { get { return this.toStringHelperField; } } #endregion } #endregion }
41.209877
148
0.556388
[ "Apache-2.0" ]
UbiquityDotNET/Llvm.NET
src/Interop/LlvmBindingsGenerator/Templates/T4/PerHeaderInteropTemplate.cs
30,044
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.AspNet.SignalR; using System.Threading.Tasks; using Newtonsoft.Json; using System.Diagnostics; namespace VLN2_H27.Hubs { public class EditorHub : Hub { public void sendChat(string name, string message, string projectId) { Clients.Group(projectId).addNewMessageToPage(name, message); } public void sendLineDelete(string filePath, int startColumn, int endColumn, int startLineNumber, int endLineNumber) { Clients.OthersInGroup(Clients.Caller.projectId).receiveLineDelete(filePath, startColumn, endColumn, startLineNumber, endLineNumber); } public void sendEditorUpdates(List<string> filePaths, List<editOperation> editOperations) { Clients.OthersInGroup(Clients.Caller.projectId).receiveUpdateSet(filePaths, editOperations); } public void sendEditorUpdatedLine(string file, string text, Range range) { Clients.OthersInGroup(Clients.Caller.projectId).receiveUpdatedLine(file, text, range); } public void sendNewline(string file, Range range) { Clients.OthersInGroup(Clients.Caller.projectId).receiveNewline(file, range); } public void sendDeleteUpdate(string file, int startLineNumber, int startColumn, int offset) { Clients.OthersInGroup(Clients.Caller.projectId).receiveDeleteUpdate(file, startLineNumber, startColumn, offset); } public void sendFile(string file, string text) { Clients.OthersInGroup(Clients.Caller.projectId).receiveFile(file, text); } public async Task userConnected(string userName) { await Groups.Add(Context.ConnectionId, Clients.Caller.projectId); Clients.OthersInGroup(Clients.CallerState.projectId).newUserConnected(userName); } public void requestFile(string file) { Clients.OthersInGroup(Clients.CallerState.projectId).userHasRequestedFile(file, Context.ConnectionId); } public void sendRequestedFile(string file, string text, string connectionId) { Clients.Client(connectionId).receiveRequestedFile(file, text); } public void pollUsersInProject(string projectId) { Clients.Group(projectId).receiveProjectPoll(Context.ConnectionId); } public void pollUsersInProjects(List<string> projectIds) { Clients.Groups(projectIds).receiveProjectPoll(Context.ConnectionId); } public void answerProjectPoll(string projectId, string connectionId) { Clients.Client(connectionId).userAnsweredProjectPoll(projectId); } public void sendCursorPosition(int lineNumber, string filePath) { Clients.OthersInGroup(Clients.CallerState.projectId).receiveCursorPosition(lineNumber, filePath, Clients.CallerState.userName); } } public class Range { [JsonProperty("endColumn")] public int endColumn { get; set; } [JsonProperty("endLineNumber")] public int endLineNumber { get; set; } [JsonProperty("startColumn")] public int startColumn { get; set; } [JsonProperty("startLineNumber")] public int startLineNumber { get; set; } } public class editOperation { [JsonProperty("eol")] public string eol { get; set; } [JsonProperty("isRedoing")] public Boolean isRedoing { get; set; } [JsonProperty("isUndoing")] public Boolean isUndoing { get; set; } [JsonProperty("range")] public Range range { get; set; } [JsonProperty("rangeLength")] public int rangeLength { get; set; } [JsonProperty("text")] public string text { get; set; } [JsonProperty("versionId")] public string versionId { get; set; } } }
32.448
144
0.653353
[ "MIT" ]
ribombee/VLN2-27-mothman
VLN2-H27/VLN2-H27/Hubs/EditorHub.cs
4,058
C#
using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Xunit; namespace Mundane.Tests.Tests_RouteConfiguration; [ExcludeFromCodeCoverage] public static class Adding_An_Endpoint_Throws_ArgumentException { [Fact] public static void When_The_Method_Parameter_Is_Empty() { var noParamsSync = (MundaneEndpointNoParametersSync)Response.Ok; var endpointSync = (MundaneEndpointSync)(_ => Response.Ok()); var noParams = (MundaneEndpointNoParameters)(() => ValueTask.FromResult(Response.Ok())); var endpoint = (MundaneEndpoint)(_ => ValueTask.FromResult(Response.Ok())); static void Test(RouteConfigurationBuilder routeConfigurationBuilder) { var exception = Assert.ThrowsAny<ArgumentException>(() => new Routing(routeConfigurationBuilder)); Assert.Equal("method", exception.ParamName!); Assert.StartsWith("Method must have a value.", exception.Message, StringComparison.Ordinal); } Test(o => o.Endpoint(string.Empty, "/", noParamsSync)); Test(o => o.Endpoint(string.Empty, "/", endpointSync)); Test(o => o.Endpoint(string.Empty, "/", noParams)); Test(o => o.Endpoint(string.Empty, "/", endpoint)); } [Theory] [InlineData("")] [InlineData(" ")] [InlineData("\\Blah")] [InlineData("Blah")] public static void When_The_Route_Parameter_Does_Not_Begin_With_A_Forward_Slash(string route) { var noParamsSync = (MundaneEndpointNoParametersSync)Response.Ok; var endpointSync = (MundaneEndpointSync)(_ => Response.Ok()); var noParameters = (MundaneEndpointNoParameters)(() => ValueTask.FromResult(Response.Ok())); var endpoint = (MundaneEndpoint)(_ => ValueTask.FromResult(Response.Ok())); static void Test(RouteConfigurationBuilder routeConfigurationBuilder) { var exception = Assert.ThrowsAny<ArgumentException>(() => new Routing(routeConfigurationBuilder)); Assert.Equal("route", exception.ParamName!); Assert.Equal("Route must start with a forward slash \"/\". (Parameter 'route')", exception.Message); } Test(o => o.Delete(route, noParamsSync)); Test(o => o.Delete(route, endpointSync)); Test(o => o.Delete(route, noParameters)); Test(o => o.Delete(route, endpoint)); Test(o => o.Endpoint("m", route, noParamsSync)); Test(o => o.Endpoint("m", route, endpointSync)); Test(o => o.Endpoint("m", route, noParameters)); Test(o => o.Endpoint("m", route, endpoint)); Test(o => o.Get(route, noParamsSync)); Test(o => o.Get(route, endpointSync)); Test(o => o.Get(route, noParameters)); Test(o => o.Get(route, endpoint)); Test(o => o.Post(route, noParamsSync)); Test(o => o.Post(route, endpointSync)); Test(o => o.Post(route, noParameters)); Test(o => o.Post(route, endpoint)); Test(o => o.Put(route, noParamsSync)); Test(o => o.Put(route, endpointSync)); Test(o => o.Put(route, noParameters)); Test(o => o.Put(route, endpoint)); } }
38.12
103
0.712487
[ "MIT" ]
adambarclay/mundane
tests/Mundane.Tests/Tests_RouteConfiguration/Adding_An_Endpoint_Throws_ArgumentException.cs
2,859
C#
using Assets.Events; using System; using System.Collections.Generic; using UnityEngine; using Random = UnityEngine.Random; public class World { private readonly List<Character> _characters; private readonly Tile[,] _tiles; public event EventHandler<CharacterCreatedEventArgs> CharacterCreated; public event EventHandler<FurnitureCreatedEventArgs> FurnitureCreated; public event EventHandler<TileChangedEventArgs> TileChanged; private Dictionary<string, Furniture> _furniturePrototypes; public JobQueue JobQueue; public int Width { get; } public int Height { get; } public World(int width = 100, int height = 100) { JobQueue = new JobQueue(); _characters = new List<Character>(); _tiles = new Tile[width, height]; Width = width; Height = height; for (var x = 0; x < width; x++) for (var y = 0; y < height; y++) { _tiles[x, y] = new Tile(this, x, y); _tiles[x, y].TileChanged += OnTileChanged; } Debug.Log("World created with " + width * height + " tiles."); CreateFurniturePrototypes(); } private void OnCharacterCreated(Character character) => CharacterCreated.Invoke(this, new CharacterCreatedEventArgs { Character = character }); private void OnFurnitureCreated(Furniture furniture) => FurnitureCreated.Invoke(this, new FurnitureCreatedEventArgs { Furniture = furniture }); private void OnTileChanged(object sender, TileChangedEventArgs args) => TileChanged.Invoke(sender, args); public void Update(float deltaTime) { foreach (var c in _characters) c.Update(deltaTime); } public Character CreateCharacter(Tile tile) { var character = new Character(tile); _characters.Add(character); OnCharacterCreated(character); return character; } private void CreateFurniturePrototypes() { _furniturePrototypes = new Dictionary<string, Furniture>(); var wallPrototype = Furniture.CreatePrototype( "greyWall", 0, // Impassable 1, // Width 1, // Height true // Links to neighbor walls ); _furniturePrototypes.Add("greyWall", wallPrototype); Debug.Log("Prototype has been created: " + wallPrototype.ObjectType); wallPrototype = Furniture.CreatePrototype( "darkgreyWall", 0, // Impassable 1, // Width 1, // Height true // Links to neighbor walls ); _furniturePrototypes.Add("darkgreyWall", wallPrototype); Debug.Log("Prototype has been created: " + wallPrototype.ObjectType); } public Tile GetTileAt(int x, int y) { // if requested tile is out of world coordinates if (x > Width || x < 0 || y > Height || y < 0) { Debug.LogError("Requested tile is out of range."); return null; } var tile = _tiles[x, y]; if (tile == null) Debug.LogError("Missing tile at position (" + x + ", " + y + ")"); return tile; } public void PlaceFurniture(string objectType, Tile tile) { // Check if we have a prototype for the given objectType string if (_furniturePrototypes.ContainsKey(objectType) == false) { Debug.LogError("FurniturePrototypes does not contain a prototype for key: " + objectType); return; } var furniture = Furniture.PlaceInstance(_furniturePrototypes[objectType], tile); // Create the visual GameObject if we placed the object successfully if (furniture != null) OnFurnitureCreated(furniture); } public void RandomizeTiles() { for (var x = 0; x < Width; x++) for (var y = 0; y < Height; y++) if (Random.Range(0, 2) == 0) _tiles[x, y].Type = TileType.Ground; else _tiles[x, y].Type = TileType.Gras; Debug.Log("World has been randomized."); } public bool IsFurniturePlacementValid(string furnitureType, Tile tile) { return _furniturePrototypes[furnitureType].IsValidPosition(tile); } public Furniture GetFurniturePrototype(string objectType) { if (_furniturePrototypes.ContainsKey(objectType) == false) Debug.LogError("No furniture with type: " + objectType); return _furniturePrototypes[objectType]; } }
32.161972
147
0.612218
[ "MIT" ]
ChrisLeeBearger/TileBaseBuilder
Assets/CSharp/Models/World.cs
4,569
C#
namespace AfxGui.Tools { partial class CustomLoaderForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.buttonSelectProgram = new System.Windows.Forms.Button(); this.buttonAbort = new System.Windows.Forms.Button(); this.buttonOk = new System.Windows.Forms.Button(); this.labelCmdLine = new System.Windows.Forms.Label(); this.textCmdLine = new System.Windows.Forms.TextBox(); this.labelProgram = new System.Windows.Forms.Label(); this.textProgram = new System.Windows.Forms.TextBox(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.groupBoxInjectDlls = new System.Windows.Forms.GroupBox(); this.labelDllsHint = new System.Windows.Forms.Label(); this.listBoxHookDlls = new System.Windows.Forms.ListBox(); this.buttonHookDelete = new System.Windows.Forms.Button(); this.buttonHookUp = new System.Windows.Forms.Button(); this.buttonHookDown = new System.Windows.Forms.Button(); this.buttonHookBrowse = new System.Windows.Forms.Button(); this.groupEnv = new System.Windows.Forms.GroupBox(); this.textEnv = new System.Windows.Forms.TextBox(); this.groupBoxInjectDlls.SuspendLayout(); this.groupEnv.SuspendLayout(); this.SuspendLayout(); // // buttonSelectProgram // this.buttonSelectProgram.Location = new System.Drawing.Point(468, 11); this.buttonSelectProgram.Name = "buttonSelectProgram"; this.buttonSelectProgram.Size = new System.Drawing.Size(104, 22); this.buttonSelectProgram.TabIndex = 15; this.buttonSelectProgram.Text = "L10n Browse ..."; this.buttonSelectProgram.UseVisualStyleBackColor = true; this.buttonSelectProgram.Click += new System.EventHandler(this.buttonSelectProgram_Click); // // buttonAbort // this.buttonAbort.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonAbort.Location = new System.Drawing.Point(452, 317); this.buttonAbort.Name = "buttonAbort"; this.buttonAbort.Size = new System.Drawing.Size(120, 32); this.buttonAbort.TabIndex = 19; this.buttonAbort.Text = "L10n &Abort"; this.buttonAbort.UseVisualStyleBackColor = true; // // buttonOk // this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.buttonOk.Location = new System.Drawing.Point(12, 317); this.buttonOk.Name = "buttonOk"; this.buttonOk.Size = new System.Drawing.Size(120, 32); this.buttonOk.TabIndex = 18; this.buttonOk.Text = "L10n &Ok"; this.buttonOk.UseVisualStyleBackColor = true; // // labelCmdLine // this.labelCmdLine.AutoSize = true; this.labelCmdLine.Location = new System.Drawing.Point(12, 41); this.labelCmdLine.Name = "labelCmdLine"; this.labelCmdLine.Size = new System.Drawing.Size(103, 13); this.labelCmdLine.TabIndex = 16; this.labelCmdLine.Text = "L10 n Commandline:"; // // textCmdLine // this.textCmdLine.Location = new System.Drawing.Point(116, 38); this.textCmdLine.Name = "textCmdLine"; this.textCmdLine.Size = new System.Drawing.Size(456, 20); this.textCmdLine.TabIndex = 17; // // labelProgram // this.labelProgram.AutoSize = true; this.labelProgram.Location = new System.Drawing.Point(12, 15); this.labelProgram.Name = "labelProgram"; this.labelProgram.Size = new System.Drawing.Size(100, 13); this.labelProgram.TabIndex = 13; this.labelProgram.Text = "L10n Program path:"; // // textProgram // this.textProgram.Location = new System.Drawing.Point(116, 12); this.textProgram.Name = "textProgram"; this.textProgram.Size = new System.Drawing.Size(346, 20); this.textProgram.TabIndex = 14; // // openFileDialog // this.openFileDialog.Title = "Select ..."; // // groupBoxInjectDlls // this.groupBoxInjectDlls.Controls.Add(this.labelDllsHint); this.groupBoxInjectDlls.Controls.Add(this.listBoxHookDlls); this.groupBoxInjectDlls.Controls.Add(this.buttonHookDelete); this.groupBoxInjectDlls.Controls.Add(this.buttonHookUp); this.groupBoxInjectDlls.Controls.Add(this.buttonHookDown); this.groupBoxInjectDlls.Controls.Add(this.buttonHookBrowse); this.groupBoxInjectDlls.Location = new System.Drawing.Point(2, 65); this.groupBoxInjectDlls.Name = "groupBoxInjectDlls"; this.groupBoxInjectDlls.Size = new System.Drawing.Size(579, 158); this.groupBoxInjectDlls.TabIndex = 20; this.groupBoxInjectDlls.TabStop = false; this.groupBoxInjectDlls.Text = "L10n DLLs to inject"; // // labelDllsHint // this.labelDllsHint.AutoSize = true; this.labelDllsHint.Location = new System.Drawing.Point(6, 108); this.labelDllsHint.Name = "labelDllsHint"; this.labelDllsHint.Size = new System.Drawing.Size(246, 13); this.labelDllsHint.TabIndex = 20; this.labelDllsHint.Text = "Hint: You can Drag && Drop DLLs in the box above."; // // listBoxHookDlls // this.listBoxHookDlls.AllowDrop = true; this.listBoxHookDlls.HorizontalScrollbar = true; this.listBoxHookDlls.Location = new System.Drawing.Point(6, 49); this.listBoxHookDlls.Name = "listBoxHookDlls"; this.listBoxHookDlls.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple; this.listBoxHookDlls.Size = new System.Drawing.Size(548, 56); this.listBoxHookDlls.TabIndex = 19; this.listBoxHookDlls.DragDrop += new System.Windows.Forms.DragEventHandler(this.listBoxHookDlls_DragDrop); this.listBoxHookDlls.DragEnter += new System.Windows.Forms.DragEventHandler(this.listBoxHookDlls_DragEnter); this.listBoxHookDlls.KeyDown += new System.Windows.Forms.KeyEventHandler(this.listBoxHookDlls_KeyDown); // // buttonHookDelete // this.buttonHookDelete.Location = new System.Drawing.Point(214, 19); this.buttonHookDelete.Name = "buttonHookDelete"; this.buttonHookDelete.Size = new System.Drawing.Size(104, 22); this.buttonHookDelete.TabIndex = 17; this.buttonHookDelete.Text = "L10n Delete"; this.buttonHookDelete.UseVisualStyleBackColor = true; this.buttonHookDelete.Click += new System.EventHandler(this.buttonHookDelete_Click); // // buttonHookUp // this.buttonHookUp.Location = new System.Drawing.Point(340, 19); this.buttonHookUp.Name = "buttonHookUp"; this.buttonHookUp.Size = new System.Drawing.Size(104, 22); this.buttonHookUp.TabIndex = 16; this.buttonHookUp.Text = "L10n Up"; this.buttonHookUp.UseVisualStyleBackColor = true; this.buttonHookUp.Click += new System.EventHandler(this.buttonHookUp_Click); // // buttonHookDown // this.buttonHookDown.Location = new System.Drawing.Point(450, 19); this.buttonHookDown.Name = "buttonHookDown"; this.buttonHookDown.Size = new System.Drawing.Size(104, 22); this.buttonHookDown.TabIndex = 15; this.buttonHookDown.Text = "Down"; this.buttonHookDown.UseVisualStyleBackColor = true; this.buttonHookDown.Click += new System.EventHandler(this.buttonHookDown_Click); // // buttonHookBrowse // this.buttonHookBrowse.Location = new System.Drawing.Point(6, 19); this.buttonHookBrowse.Name = "buttonHookBrowse"; this.buttonHookBrowse.Size = new System.Drawing.Size(104, 22); this.buttonHookBrowse.TabIndex = 14; this.buttonHookBrowse.Text = "L10n Browse ..."; this.buttonHookBrowse.UseVisualStyleBackColor = true; this.buttonHookBrowse.Click += new System.EventHandler(this.buttonHookBrowse_Click); // // groupEnv // this.groupEnv.Controls.Add(this.textEnv); this.groupEnv.Location = new System.Drawing.Point(2, 229); this.groupEnv.Name = "groupEnv"; this.groupEnv.Size = new System.Drawing.Size(579, 82); this.groupEnv.TabIndex = 21; this.groupEnv.TabStop = false; this.groupEnv.Text = "L10n Add Environment Variables: Name=Value"; // // textEnv // this.textEnv.Location = new System.Drawing.Point(6, 19); this.textEnv.Multiline = true; this.textEnv.Name = "textEnv"; this.textEnv.Size = new System.Drawing.Size(567, 57); this.textEnv.TabIndex = 0; this.textEnv.Enter += new System.EventHandler(this.textEnv_Enter); this.textEnv.Leave += new System.EventHandler(this.textEnv_Leave); // // CustomLoaderForm // this.AcceptButton = this.buttonOk; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.buttonAbort; this.ClientSize = new System.Drawing.Size(584, 361); this.Controls.Add(this.groupEnv); this.Controls.Add(this.groupBoxInjectDlls); this.Controls.Add(this.buttonSelectProgram); this.Controls.Add(this.buttonAbort); this.Controls.Add(this.buttonOk); this.Controls.Add(this.labelCmdLine); this.Controls.Add(this.textCmdLine); this.Controls.Add(this.labelProgram); this.Controls.Add(this.textProgram); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "CustomLoaderForm"; this.Text = "L10n Custom Loader"; this.groupBoxInjectDlls.ResumeLayout(false); this.groupBoxInjectDlls.PerformLayout(); this.groupEnv.ResumeLayout(false); this.groupEnv.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button buttonSelectProgram; private System.Windows.Forms.Button buttonAbort; private System.Windows.Forms.Button buttonOk; private System.Windows.Forms.Label labelCmdLine; private System.Windows.Forms.TextBox textCmdLine; private System.Windows.Forms.Label labelProgram; private System.Windows.Forms.TextBox textProgram; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.GroupBox groupBoxInjectDlls; private System.Windows.Forms.Button buttonHookDelete; private System.Windows.Forms.Button buttonHookUp; private System.Windows.Forms.Button buttonHookDown; private System.Windows.Forms.Button buttonHookBrowse; private System.Windows.Forms.Label labelDllsHint; private System.Windows.Forms.ListBox listBoxHookDlls; private System.Windows.Forms.GroupBox groupEnv; private System.Windows.Forms.TextBox textEnv; } }
49.966038
121
0.598671
[ "MIT" ]
advancedfx/advancedfx
hlae/Tools/CustomLoaderForm.Designer.cs
13,243
C#
using EPiServer.Core; using EPiServer.DataAnnotations; using ImageVault.EPiServer; namespace Meriworks.Examples.ImageVault.Epi.MediaList { [ContentType(DisplayName = "MediaBlock", Description = "A block type with a single media property", GUID = "0C2F7101-DA9F-4646-B52E-4DBCB2E8406E")] public class MediaBlock : BlockData { public virtual MediaReference Media { get; set; } } }
36.454545
151
0.74813
[ "MIT" ]
meriworks/examples
imagevault/epi/medialist/MediaBlock.cs
403
C#
using System; using UnityEngine; /// <summary> /// Propriétés des entrées (qubits) /// </summary> public class EntryObject : MonoBehaviour { public QCS.Circuit.EntryStruct entryStruct; public GameObject root; public GameObject entry; public GameObject collar; public void Destroy() { UnityEngine.Object.Destroy(root); UnityEngine.Object.Destroy(entry); UnityEngine.Object.Destroy(collar); } public void Select() { foreach(Renderer renderer in collar.GetComponentsInChildren<Renderer>()) renderer.material = ObjectFactory.pipeSelectedMaterial; } public void Deselect() { foreach (Renderer renderer in collar.GetComponentsInChildren<Renderer>()) renderer.material = ObjectFactory.pipeMaterial; } public void FadeOutAndDestroy() { AnimationManager.Fade(root, 0f, GridBoard.animationTime, Destroy); } }
24.763158
81
0.676939
[ "MIT" ]
Pseudonyme7/QuantumGateV2
QuantumGate/Assets/01_Scripts/02_Objects/EntryObject.cs
946
C#
using System; using NetRuntimeSystem = System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.ComponentModel; using System.Reflection; using System.Collections.Generic; using NetOffice; namespace NetOffice.WordApi { ///<summary> /// DispatchInterface DropDown /// SupportByVersion Word, 9,10,11,12,14,15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff196004.aspx ///</summary> [SupportByVersionAttribute("Word", 9,10,11,12,14,15)] [EntityTypeAttribute(EntityType.IsDispatchInterface)] public class DropDown : COMObject { #pragma warning disable #region Type Information private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(DropDown); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public DropDown(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public DropDown(COMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public DropDown(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public DropDown(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public DropDown(COMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public DropDown() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public DropDown(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff193722.aspx /// </summary> [SupportByVersionAttribute("Word", 9,10,11,12,14,15)] public NetOffice.WordApi.Application Application { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Application", paramsArray); NetOffice.WordApi.Application newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.WordApi.Application.LateBindingApiWrapperType) as NetOffice.WordApi.Application; return newObject; } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff844894.aspx /// </summary> [SupportByVersionAttribute("Word", 9,10,11,12,14,15)] public Int32 Creator { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Creator", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff196567.aspx /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("Word", 9,10,11,12,14,15)] public object Parent { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray); COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff192753.aspx /// </summary> [SupportByVersionAttribute("Word", 9,10,11,12,14,15)] public bool Valid { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Valid", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15 /// Get/Set /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff836103.aspx /// </summary> [SupportByVersionAttribute("Word", 9,10,11,12,14,15)] public Int32 Default { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Default", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Default", paramsArray); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15 /// Get/Set /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff834815.aspx /// </summary> [SupportByVersionAttribute("Word", 9,10,11,12,14,15)] public Int32 Value { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Value", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Value", paramsArray); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff822394.aspx /// </summary> [SupportByVersionAttribute("Word", 9,10,11,12,14,15)] public NetOffice.WordApi.ListEntries ListEntries { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ListEntries", paramsArray); NetOffice.WordApi.ListEntries newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.WordApi.ListEntries.LateBindingApiWrapperType) as NetOffice.WordApi.ListEntries; return newObject; } } #endregion #region Methods #endregion #pragma warning restore } }
32.982456
191
0.671144
[ "MIT" ]
NetOffice/NetOffice
Source/Word/DispatchInterfaces/DropDown.cs
7,520
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("Aula1AspNetMvc")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Aula1AspNetMvc")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("68f4111c-f0a1-48c0-a8fb-868a8fef526a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.666667
84
0.752212
[ "MIT" ]
wesley2018/Aula1AspNetMvc
Aula1AspNetMvc/Aula1AspNetMvc/Properties/AssemblyInfo.cs
1,359
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PathPlacer : MonoBehaviour { public float spacing = .1f; public float resolution = 1; private void Start() { Vector3[] points = FindObjectOfType<PathCreator>().path.CalculateEvenlySpacedPoints(spacing, resolution); foreach (Vector3 p in points) { GameObject g = GameObject.CreatePrimitive(PrimitiveType.Sphere); g.transform.position = p; g.transform.localScale = Vector3.one * spacing * .5f; g.transform.parent = transform; } } }
28.454545
113
0.651757
[ "MIT" ]
RafaelFreita/ComputationalAnimation
Assets/Modules/Paths/Scripts/PathPlacer.cs
628
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using TextHelper; namespace EAScriptAddin { public partial class TextHelperControl : UserControl { private MainTextHelperForm mainTextHelperForm { get; set; } public TextHelperControl() { InitializeComponent(); this.mainTextHelperForm = new MainTextHelperForm(); this.mainTextHelperForm.TopLevel = false; this.mainTextHelperForm.FormBorderStyle = FormBorderStyle.None; this.mainPanel.Controls.Add(mainTextHelperForm); this.mainTextHelperForm.Dock = DockStyle.Fill; this.mainTextHelperForm.Show(); } } }
29.607143
75
0.694813
[ "BSD-2-Clause" ]
CuchulainX/Enterprise-Architect-Toolpack
EAScriptAddin/TextHelperControl.cs
831
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace DailyMeeting.Migrations { public partial class Upgraded_To_Abp_5_9 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropIndex( name: "IX_AbpOrganizationUnits_TenantId_Code", table: "AbpOrganizationUnits"); migrationBuilder.CreateIndex( name: "IX_AbpOrganizationUnits_TenantId_Code", table: "AbpOrganizationUnits", columns: new[] { "TenantId", "Code" }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropIndex( name: "IX_AbpOrganizationUnits_TenantId_Code", table: "AbpOrganizationUnits"); migrationBuilder.CreateIndex( name: "IX_AbpOrganizationUnits_TenantId_Code", table: "AbpOrganizationUnits", columns: new[] { "TenantId", "Code" }, unique: true, filter: "[TenantId] IS NOT NULL"); } } }
33.529412
71
0.59386
[ "MIT" ]
MarkXuan/Vatek-DailyMeeting
aspnet-core/src/DailyMeeting.EntityFrameworkCore/Migrations/20200604091046_Upgraded_To_Abp_5_9.cs
1,142
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the email-2010-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.SimpleEmail.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.SimpleEmail.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for S3Action Object /// </summary> public class S3ActionUnmarshaller : IUnmarshaller<S3Action, XmlUnmarshallerContext>, IUnmarshaller<S3Action, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public S3Action Unmarshall(XmlUnmarshallerContext context) { S3Action unmarshalledObject = new S3Action(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("BucketName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.BucketName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("KmsKeyArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.KmsKeyArn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ObjectKeyPrefix", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ObjectKeyPrefix = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("TopicArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.TopicArn = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return unmarshalledObject; } } return unmarshalledObject; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <returns></returns> public S3Action Unmarshall(JsonUnmarshallerContext context) { return null; } private static S3ActionUnmarshaller _instance = new S3ActionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static S3ActionUnmarshaller Instance { get { return _instance; } } } }
37.078261
138
0.559099
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/SimpleEmail/Generated/Model/Internal/MarshallTransformations/S3ActionUnmarshaller.cs
4,264
C#
/* * Prime Developer Trial * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: v1 * 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 = FactSet.SDK.ETFProfileandPrices.Client.OpenAPIDateConverter; namespace FactSet.SDK.ETFProfileandPrices.Model { /// <summary> /// InlineResponse2009 /// </summary> [DataContract(Name = "inline_response_200_9")] public partial class InlineResponse2009 : IEquatable<InlineResponse2009>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="InlineResponse2009" /> class. /// </summary> /// <param name="data">data.</param> /// <param name="meta">meta.</param> public InlineResponse2009(InlineResponse2009Data data = default(InlineResponse2009Data), InlineResponse2001Meta meta = default(InlineResponse2001Meta)) { this.Data = data; this.Meta = meta; } /// <summary> /// Gets or Sets Data /// </summary> [DataMember(Name = "data", EmitDefaultValue = false)] public InlineResponse2009Data Data { get; set; } /// <summary> /// Gets or Sets Meta /// </summary> [DataMember(Name = "meta", EmitDefaultValue = false)] public InlineResponse2001Meta Meta { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class InlineResponse2009 {\n"); sb.Append(" Data: ").Append(Data).Append("\n"); sb.Append(" Meta: ").Append(Meta).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 InlineResponse2009); } /// <summary> /// Returns true if InlineResponse2009 instances are equal /// </summary> /// <param name="input">Instance of InlineResponse2009 to be compared</param> /// <returns>Boolean</returns> public bool Equals(InlineResponse2009 input) { if (input == null) { return false; } return ( this.Data == input.Data || (this.Data != null && this.Data.Equals(input.Data)) ) && ( this.Meta == input.Meta || (this.Meta != null && this.Meta.Equals(input.Meta)) ); } /// <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.Data != null) { hashCode = (hashCode * 59) + this.Data.GetHashCode(); } if (this.Meta != null) { hashCode = (hashCode * 59) + this.Meta.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
32.959184
159
0.562436
[ "Apache-2.0" ]
factset/enterprise-sdk
code/dotnet/ETFProfileandPrices/v2/src/FactSet.SDK.ETFProfileandPrices/Model/InlineResponse2009.cs
4,845
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal sealed partial class SolutionCrawlerRegistrationService { private sealed partial class WorkCoordinator { private sealed partial class IncrementalAnalyzerProcessor { private sealed class LowPriorityProcessor : AbstractPriorityProcessor { private readonly AsyncProjectWorkItemQueue _workItemQueue; public LowPriorityProcessor( IAsynchronousOperationListener listener, IncrementalAnalyzerProcessor processor, Lazy<ImmutableArray<IIncrementalAnalyzer>> lazyAnalyzers, IGlobalOperationNotificationService globalOperationNotificationService, int backOffTimeSpanInMs, CancellationToken shutdownToken) : base(listener, processor, lazyAnalyzers, globalOperationNotificationService, backOffTimeSpanInMs, shutdownToken) { _workItemQueue = new AsyncProjectWorkItemQueue(processor._registration.ProgressReporter, processor._registration.Workspace); Start(); } public int WorkItemCount => _workItemQueue.WorkItemCount; protected override Task WaitAsync(CancellationToken cancellationToken) { return _workItemQueue.WaitAsync(cancellationToken); } protected override async Task ExecuteAsync() { try { // we wait for global operation, higher and normal priority processor to finish its working await WaitForHigherPriorityOperationsAsync().ConfigureAwait(false); // process any available project work, preferring the active project. if (_workItemQueue.TryTakeAnyWork( Processor.GetActiveProjectId(), Processor.DependencyGraph, Processor.DiagnosticAnalyzerService, out var workItem, out var projectCancellation)) { await ProcessProjectAsync(Analyzers, workItem, projectCancellation).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } protected override Task HigherQueueOperationTask { get { return Task.WhenAll(Processor._highPriorityProcessor.Running, Processor._normalPriorityProcessor.Running); } } protected override bool HigherQueueHasWorkItem { get { return Processor._highPriorityProcessor.HasAnyWork || Processor._normalPriorityProcessor.HasAnyWork; } } protected override void PauseOnGlobalOperation() { base.PauseOnGlobalOperation(); _workItemQueue.RequestCancellationOnRunningTasks(); } public void Enqueue(WorkItem item) { UpdateLastAccessTime(); // Project work item = item.ToProjectWorkItem(Processor._listener.BeginAsyncOperation("WorkItem")); var added = _workItemQueue.AddOrReplace(item); // lower priority queue gets lowest time slot possible. if there is any activity going on in higher queue, it drop whatever it has // and let higher work item run CancelRunningTaskIfHigherQueueHasWorkItem(); Logger.Log(FunctionId.WorkCoordinator_Project_Enqueue, s_enqueueLogger, Environment.TickCount, item.ProjectId, !added); SolutionCrawlerLogger.LogWorkItemEnqueue(Processor._logAggregator, item.ProjectId); } private void CancelRunningTaskIfHigherQueueHasWorkItem() { if (!HigherQueueHasWorkItem) { return; } _workItemQueue.RequestCancellationOnRunningTasks(); } private async Task ProcessProjectAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationToken cancellationToken) { if (CancellationToken.IsCancellationRequested) { return; } // we do have work item for this project var projectId = workItem.ProjectId; var processedEverything = false; var processingSolution = Processor.CurrentSolution; try { using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessProjectAsync, w => w.ToString(), workItem, cancellationToken)) { var project = processingSolution.GetProject(projectId); if (project != null) { var reasons = workItem.InvocationReasons; var semanticsChanged = reasons.Contains(PredefinedInvocationReasons.SemanticChanged) || reasons.Contains(PredefinedInvocationReasons.SolutionRemoved); using (Processor.EnableCaching(project.Id)) { await Processor.RunAnalyzersAsync(analyzers, project, workItem, (a, p, c) => a.AnalyzeProjectAsync(p, semanticsChanged, reasons, c), cancellationToken).ConfigureAwait(false); } } else { SolutionCrawlerLogger.LogProcessProjectNotExist(Processor._logAggregator); await RemoveProjectAsync(projectId, cancellationToken).ConfigureAwait(false); } if (!cancellationToken.IsCancellationRequested) { processedEverything = true; } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } finally { // we got cancelled in the middle of processing the project. // let's make sure newly enqueued work item has all the flag needed. // Avoid retry attempts after cancellation is requested, since work will not be processed // after that point. if (!processedEverything && !CancellationToken.IsCancellationRequested) { _workItemQueue.AddOrReplace(workItem.Retry(Listener.BeginAsyncOperation("ReenqueueWorkItem"))); } SolutionCrawlerLogger.LogProcessProject(Processor._logAggregator, projectId.Id, processedEverything); // remove one that is finished running _workItemQueue.MarkWorkItemDoneFor(projectId); } } private async Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken) { foreach (var analyzer in Analyzers) { await analyzer.RemoveProjectAsync(projectId, cancellationToken).ConfigureAwait(false); } } public override void Shutdown() { base.Shutdown(); _workItemQueue.Dispose(); } internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> analyzers, List<WorkItem> items) { var uniqueIds = new HashSet<ProjectId>(); foreach (var item in items) { if (uniqueIds.Add(item.ProjectId)) { ProcessProjectAsync(analyzers, item, CancellationToken.None).Wait(); } } } internal void WaitUntilCompletion_ForTestingPurposesOnly() { // this shouldn't happen. would like to get some diagnostic while (_workItemQueue.HasAnyWork) { Environment.FailFast("How?"); } } } } } } }
47.102222
214
0.496603
[ "MIT" ]
missymessa/roslyn
src/Features/Core/Portable/SolutionCrawler/WorkCoordinator.LowPriorityProcessor.cs
10,600
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace GrpcJsonTranscoder.Internal.Http { internal static class HttpContextExtensions { public static JObject ParseRequestData(this HttpContext context, IDictionary<string, string> upstreamHeaders = null) { var o = new JObject(); if (upstreamHeaders != null && upstreamHeaders.ContainsKey("x-grpc-route-data")) { var nameValues = JsonConvert.DeserializeObject<List<NameAndValue>>(upstreamHeaders["x-grpc-route-data"]); // work with ocelot foreach (var nameValue in nameValues) { o.Add(nameValue.Name.Replace("{", "").Replace("}", ""), nameValue.Value); } } if (upstreamHeaders != null && upstreamHeaders.ContainsKey("x-grpc-body-data")) { var json = upstreamHeaders["x-grpc-body-data"]; if (json != string.Empty) { o = MergeJsonObjects(o, JsonConvert.DeserializeObject<JObject>(json)); } } // query string foreach (var q in context.Request.Query) { o.Add(q.Key, q.Value.ToString()); } return o; } public static string ParseGetJsonRequestOnAggregateService(this HttpContext context) { var o = new JObject(); if (context.Request.Headers.ContainsKey("x-grpc-route-data")) { // route data var nameValues = JsonConvert.DeserializeObject<List<NameAndValue>>(context.Request.Headers["x-grpc-route-data"]); // work with ocelot foreach (var nameValue in nameValues) { o.Add(nameValue.Name.Replace("{", "").Replace("}", ""), nameValue.Value); } } // query string foreach (var q in context.Request.Query) { o.Add(q.Key, q.Value.ToString()); } return JsonConvert.SerializeObject(o); } public static async Task<string> ParseOtherJsonRequestOnAggregateService(this HttpContext context) { // ref at https://stackoverflow.com/questions/43403941/how-to-read-asp-net-core-response-body var encoding = context.Request.GetTypedHeaders().ContentType?.Encoding ?? Encoding.UTF8; var stream = new StreamReader(context.Request.Body, encoding); var json = await stream.ReadToEndAsync(); return json == string.Empty ? "{}" : json; } public static IDictionary<string, string> GetRequestHeaders(this HttpContext context) { var headers = new Dictionary<string, string>(); foreach (var key in context.Request.Headers.Keys) { if (key.StartsWith(":")) { continue; } if (key.StartsWith("grpc-", StringComparison.OrdinalIgnoreCase)) { continue; } if (key.ToLowerInvariant() != "content-type" && key.ToLowerInvariant() != "authorization") continue; //todo: investigate it more var value = context.Request.Headers[key]; headers.Add(key, value.FirstOrDefault()); } if (!string.IsNullOrEmpty(context.TraceIdentifier)) { headers.Add("X-Correlation-ID", context.TraceIdentifier); } return headers; } private static JObject MergeJsonObjects(params JObject[] objects) { var json = new JObject(); foreach (var jsonObject in objects) { foreach (var (key, value) in jsonObject) { if (!json.ContainsKey(key)) { json.Add(key, value); } } } return json; } } }
32.847328
149
0.530792
[ "MIT" ]
sidinwillis/GrpcJsonTranscoder
src/GrpcJsonTranscoder/Internal/Http/HttpContextExtensions.cs
4,303
C#
namespace Cosmos.System.FileSystem.FAT.Listing; /// <summary> /// Fat directory entry metadata class. /// </summary> public sealed class FatDirectoryEntryMetadata { /// <summary> /// Directory entry first byte matadata. This is filename first byte. /// </summary> public static readonly FatDirectoryEntryMetadata FirstByte = new(0x00, 1); /// <summary> /// Directory entry short name matadata. This is the filename + filename extension. /// The dot '.' separate filename and filename extention is implied. /// </summary> public static readonly FatDirectoryEntryMetadata ShortName = new(0x00, 11); /// <summary> /// Directory entry attributes matadata. This contains information about the directory. /// </summary> public static readonly FatDirectoryEntryMetadata Attributes = new(0x0B, 1); /// <summary> /// Directory entry reserved matadata. /// </summary> public static readonly FatDirectoryEntryMetadata NTReserved = new(0x0C, 1); /// <summary> /// Directory entry creation time tenths of a second matadata. /// </summary> public static readonly FatDirectoryEntryMetadata CreationTimeTenthsOfASecond = new(0x0D, 1); /// <summary> /// Directory entry creation time matadata. /// </summary> public static readonly FatDirectoryEntryMetadata CreationTime = new(0x0E, 2); /// <summary> /// Directory entry creation date matadata. /// </summary> public static readonly FatDirectoryEntryMetadata CreationDate = new(0x10, 2); /// <summary> /// Directory entry last accessed date matadata. /// </summary> public static readonly FatDirectoryEntryMetadata AccessedDate = new(0x12, 2); /// <summary> /// Directory entry first cluster high matadata. /// </summary> public static readonly FatDirectoryEntryMetadata FirstClusterHigh = new(0x14, 2); /// <summary> /// Directory entry last modified time matadata. /// </summary> public static readonly FatDirectoryEntryMetadata ModifiedTime = new(0x16, 2); /// <summary> /// Directory entry last modified date matadata. /// </summary> public static readonly FatDirectoryEntryMetadata ModifiedDate = new(0x18, 2); /// <summary> /// Directory entry first cluster low matadata. /// </summary> public static readonly FatDirectoryEntryMetadata FirstClusterLow = new(0x1A, 2); /// <summary> /// Directory entry drectory size matadata. /// </summary> public static readonly FatDirectoryEntryMetadata Size = new(0x1C, 4); /// <summary> /// Entry data length. /// </summary> public readonly uint DataLength; /// <summary> /// Entry data offset. /// </summary> public readonly uint DataOffset; private FatDirectoryEntryMetadata(uint aDataOffset, uint aDataLength) { DataOffset = aDataOffset; DataLength = aDataLength; } /// <summary> /// Long filename entry metadata class. This class can not be inherited. /// </summary> public sealed class LongFilenameEntryMetadata { /// <summary> /// Directory entry sequence number and allocation status matadata. /// </summary> public static readonly FatDirectoryEntryMetadata SequenceNumberAndAllocationStatus = new(0x00, 1); /// <summary> /// Directory entry LongName1 matadata. /// </summary> public static readonly FatDirectoryEntryMetadata LongName1 = new(0x01, 10); /// <summary> /// Directory entry attributes matadata. /// </summary> public static readonly FatDirectoryEntryMetadata Attributes = new(0x0B, 1); //public static readonly FatDirectoryEntryMetadata Reserved1 = new FatDirectoryEntryMetadata(0x0C, 1); /// <summary> /// Directory entry checksum matadata. /// </summary> public static readonly FatDirectoryEntryMetadata Checksum = new(0x0D, 1); /// <summary> /// Directory entry LongName2 matadata. /// </summary> public static readonly FatDirectoryEntryMetadata LongName2 = new(0x0E, 12); //public static readonly FatDirectoryEntryMetadata Reserved2 = new FatDirectoryEntryMetadata(0x1A, 2); /// <summary> /// Directory entry LongName3 matadata. /// </summary> public static readonly FatDirectoryEntryMetadata LongName3 = new(0x1C, 4); } }
35.523438
110
0.652518
[ "BSD-3-Clause" ]
Kiirx/Cosmos
source/Cosmos.System2/FileSystem/FAT/Listing/FatDirectoryEntryMetadata.cs
4,549
C#
using System; using System.Collections.Generic; using System.Text.RegularExpressions; namespace mgt_parser { public static class ScheduleParser { private static readonly Dictionary<string, int> _months = new Dictionary<string, int> { {"января", 1}, {"февраля", 2}, {"марта", 3}, {"апреля", 4}, {"мая", 5}, {"июня", 6}, {"июля", 7}, {"августа", 8}, {"сентября", 9}, {"октября", 10}, {"ноября", 11}, {"декабря", 12} }; private const string DateTimeRegexPattern = @"(\d+) (\w+) (\d+)"; private const string ColorsRegexPattern = "<p class=\"helpfile\"><b style=\"color: ([#a-zA-Z0-9]+)\">(.*?)<\\/b>(.*?)<\\/p>"; private const string ValidityTimeSearchStr = "c</h3></td><td><h3>"; private const string LegendHeaderStr = "<h3>Легенда</h3>"; private const string TagBeginning = "<"; private const string TdClosingTag = "</td>"; private const string SpanClosingTag = "</span>"; //const string NoDataForLegend = "Нет особых данных для легенды"; private const string From = "от"; private const string HourSearchStr = "<span class=\"hour\">"; private const string HourRegexPattern = "<span class=\"hour\">(\\d+)</span>"; //" < span class=\"hour\">(\\d+)</span></td><td align=.*>(.*)</td>"; private const string MinutesSearchStr = "<span class=\"minutes\""; private const string MinutesRegexPattern = "<span class=\"minutes\"( |.*color: ([a-zA-z0-9#]+).*)>(\\d+)</span>"; //I know that parsing HTML by regex is a bad idea, but objective is not to use third-party parsers public static Schedule Parse(string htmlData, ScheduleInfo si) { var schedule = new Schedule(si); var index = 0; //Current position of htmlData processing (shifts if some item is found and parsed) var searchIndex = 0; //Curent position of search ahead of index //<span class=\"hour\">(\d+)</span></td><td align=.*>(.*)</td> var hourRegex = new Regex(HourRegexPattern); //<span class="minutes" >02</span> //<span class="minutes" style="color: red; font-weight: bold;">37</span><br> var minuteRegex = new Regex(MinutesRegexPattern); //Starting routine searchIndex = htmlData.IndexOf(ValidityTimeSearchStr, index); if (searchIndex == -1) throw new Exception("Validity time not found!"); index = searchIndex + ValidityTimeSearchStr.Length; searchIndex = htmlData.IndexOf(TagBeginning, index); if (searchIndex == -1) throw new Exception("Validity time border not found!"); var validityStr = htmlData.Substring(index, searchIndex - index); var date = ParseDateTime(validityStr); schedule.ValidityTime = date; //Console.WriteLine("Schedule valid from: " + date.ToString()); index = searchIndex; //Iterative hours and minutes parsing do { //Parsing hours searchIndex = htmlData.IndexOf(HourSearchStr, index); if (searchIndex == -1) break; index = searchIndex; searchIndex = htmlData.IndexOf(TdClosingTag, index); //Grey hours will be ignored because they doesn't match to regexp sbyte hour = -1; var hourStr = htmlData.Substring(index, searchIndex - index); var hourMatch = hourRegex.Match(hourStr); if (hourMatch.Length == 0) { throw new Exception("Failed to find hour info!"); } else { hour = Convert.ToSByte(hourMatch.Groups[1].Value); } //Getting substring for all minutes in hour, then searching for all of it //Parsing minutes searchIndex = htmlData.IndexOf(MinutesSearchStr, index); index = searchIndex; var minutesBorderIndex = htmlData.IndexOf(TdClosingTag, index); var allMinutesStr = htmlData.Substring(index, minutesBorderIndex - index); var minuteIndex = 0; //local varibles for searching inside minutes substring var minuteSearchIndex = 0; while (minuteSearchIndex != -1) { minuteSearchIndex = allMinutesStr.IndexOf(SpanClosingTag, minuteIndex); if (minuteSearchIndex == -1) break; var minuteStr = allMinutesStr.Substring(minuteIndex, minuteSearchIndex - minuteIndex + SpanClosingTag.Length); minuteIndex = minuteSearchIndex + SpanClosingTag.Length; var minuteMatch = minuteRegex.Match(minuteStr); if (minuteMatch.Length == 0) { throw new Exception("Failed to find minute info!"); } else { if (hour == -1) throw new Exception("Hours parser fucked up!"); var minute = Convert.ToSByte(minuteMatch.Groups[3].Value); var specialRoute = minuteMatch.Groups[2].Value; if (specialRoute.Length > 1) { var type = RouteTypeProvider.GetRouteType(specialRoute); schedule.AddEntry(new ScheduleEntry(hour, minute, type)); //special route } else schedule.AddEntry(new ScheduleEntry(hour, minute)); //regular route } } //all minutes for current hour found, skipping to next hour index = minutesBorderIndex; searchIndex = index; } while (searchIndex > 0); //Parsing the legend searchIndex = htmlData.IndexOf(LegendHeaderStr, index); if (searchIndex != 0) { index = searchIndex + LegendHeaderStr.Length; searchIndex = htmlData.IndexOf(TdClosingTag, index); if (searchIndex != 0) { var legendData = htmlData.Substring(index, searchIndex - index); //.*? for non-greedy match instead of greedy .* //const string noColorsRegexPattern = "<p class=\"helpfile\"><b>(.*)<\\/b>(.*)<\\/p>"; //regex pattern without colors: <p class="helpfile"><b>(.*)<\/b>(.*)<\/p> //group1: bold text, group2: non-bold text (check for empty!) //var noColorsRegex = new Regex(noColorsRegexPattern); //var matches = noColorsRegex.Matches(legendData); //Console.WriteLine("Matching non-colored legend..."); //if (matches.Count == 0) // Console.WriteLine("Non-colored regex not matched!"); //else //{ // if (legendData.IndexOf(NoDataForLegend) == -1) // { // //normally we shouldn't be there. This output just for debugging purposes and should be removed later (TODO) // foreach (Match match in matches) // { // //Console.WriteLine("Match: " + match.Value); // //GroupCollection groups = match.Groups; // //foreach (Group group in groups) // //{ // // Console.WriteLine("Group: " + group.Value); // //} // } // } //} //Console.WriteLine("Matching colored legend..."); //regex pattern with colors: <p class="helpfile"><b style="color: (\w+)">(.*)<\/b>(.*)<\/p> //should be multiple matches //group1: color name, group2: color name in russian (bold text), group3: non-bold text (description) var colorsRegex = new Regex(ColorsRegexPattern); var matches = colorsRegex.Matches(legendData); if (matches.Count != 0) { foreach (Match match in matches) { //Console.WriteLine("Match: " + match.Value); GroupCollection groups = match.Groups; var type = RouteTypeProvider.GetRouteType(groups[1].Value); var destinationRaw = groups[3].Value; //TODO: change regexp, no need in russian name of color var startIndex = destinationRaw.IndexOf(From); var destination = destinationRaw.Substring(startIndex); schedule.SetSpecialRoute(type, destination); } } } } return schedule; } private static DateTime ParseDateTime(string dateStr) { var regex = new Regex(DateTimeRegexPattern, RegexOptions.IgnoreCase); var match = regex.Match(dateStr); if (match.Groups.Count == 0) throw new Exception("Regex for date not matched!"); //Console.WriteLine(match.Value); GroupCollection groups = match.Groups; var day = Convert.ToInt32(groups[1].Value); var month = _months[groups[2].Value]; var year = Convert.ToInt32(groups[3].Value); return new DateTime(year, month, day); } } }
46.053812
154
0.498247
[ "MIT" ]
Snarkorel/mgt_parser
ScheduleParser.cs
10,376
C#
#nullable enable using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace Spectre.Console { internal static class TypeConverterHelper { public static string ConvertToString<T>(T input) => ConvertToString(input, typeof(T)); public static string ConvertToString(object input) { _ = input ?? throw new ArgumentException(nameof(input)); return ConvertToString(input, input.GetType()); } private static string ConvertToString(object? input, Type type) => GetTypeConverter(type).ConvertToInvariantString(input); public static bool TryConvertFromString<T>(string input, [MaybeNull] out T result) { if (TryConvertFromString(input, typeof(T), out object? resultObject)) { if (!(resultObject is T)) { throw new InvalidCastException(); } result = (T)resultObject; return true; } result = default; return false; } public static bool TryConvertFromString(string input, Type type, [MaybeNull] out object? result) { try { result = GetTypeConverter(type).ConvertFromInvariantString(input); return true; } catch { result = default; return false; } } public static TypeConverter GetTypeConverter<T>() => GetTypeConverter(typeof(T)); public static TypeConverter GetTypeConverter(Type type) { var converter = TypeDescriptor.GetConverter(type); if (converter != null) { return converter; } var attribute = type.GetCustomAttribute<TypeConverterAttribute>(); if (attribute != null) { var converterType = Type.GetType(attribute.ConverterTypeName, false, false); if (converterType != null) { converter = Activator.CreateInstance(converterType) as TypeConverter; if (converter != null) { return converter; } } } throw new InvalidOperationException("Could not find type converter"); } } }
30.845238
105
0.518719
[ "MIT" ]
koliyo/spectre.console
src/Spectre.Console/Internal/TypeConverterHelper.cs
2,591
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V6301 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="QUSC_MT000001UK02.TokenId", Namespace="urn:hl7-org:v3")] [System.Xml.Serialization.XmlRootAttribute("QUSC_MT000001UK02.TokenId", Namespace="urn:hl7-org:v3")] public partial class QUSC_MT000001UK02TokenId { private II valueField; private ST semanticsTextField; private string typeField; private string[] typeIDField; private string[] realmCodeField; private string nullFlavorField; private static System.Xml.Serialization.XmlSerializer serializer; public QUSC_MT000001UK02TokenId() { this.typeField = "ParameterItem"; } public II value { get { return this.valueField; } set { this.valueField = value; } } public ST semanticsText { get { return this.semanticsTextField; } set { this.semanticsTextField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string type { get { return this.typeField; } set { this.typeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string[] typeID { get { return this.typeIDField; } set { this.typeIDField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string[] realmCode { get { return this.realmCodeField; } set { this.realmCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string nullFlavor { get { return this.nullFlavorField; } set { this.nullFlavorField = value; } } private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(QUSC_MT000001UK02TokenId)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current QUSC_MT000001UK02TokenId object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an QUSC_MT000001UK02TokenId object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output QUSC_MT000001UK02TokenId object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out QUSC_MT000001UK02TokenId obj, out System.Exception exception) { exception = null; obj = default(QUSC_MT000001UK02TokenId); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out QUSC_MT000001UK02TokenId obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static QUSC_MT000001UK02TokenId Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((QUSC_MT000001UK02TokenId)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current QUSC_MT000001UK02TokenId object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an QUSC_MT000001UK02TokenId object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output QUSC_MT000001UK02TokenId object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out QUSC_MT000001UK02TokenId obj, out System.Exception exception) { exception = null; obj = default(QUSC_MT000001UK02TokenId); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out QUSC_MT000001UK02TokenId obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static QUSC_MT000001UK02TokenId LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this QUSC_MT000001UK02TokenId object /// </summary> public virtual QUSC_MT000001UK02TokenId Clone() { return ((QUSC_MT000001UK02TokenId)(this.MemberwiseClone())); } #endregion } }
40.886364
1,358
0.569112
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V6301/Generated/QUSC_MT000001UK02TokenId.cs
10,794
C#
namespace LinFx.Application.Models { /// <summary> /// This interface is defined to standardize to request a sorted result. /// </summary> public interface ISortedResultRequest { /// <summary> /// Sorting information. /// Should include sorting field and optionally a direction (ASC or DESC) /// Can contain more than one field separated by comma (,). /// </summary> /// <example> /// Examples: /// "Name" /// "Name DESC" /// "Name ASC, Age DESC" /// </example> string Sorting { get; set; } } }
29.285714
81
0.544715
[ "MIT" ]
linfx/LinFx
src/LinFx/Application/Models/ISortedResultRequest.cs
617
C#
using System; using LessPaper.Shared.Helper; using Xunit; namespace LessPaper.GuardService.UnitTest { public class UnitTest1 { [Fact] public async void Test1() { var kp = CryptoHelper.GenerateRsaKeyPair(); for (int i = 0; i < 10000; i++) { var e = CryptoHelper.RsaEncrypt(kp.PublicKey, CryptoHelper.GetSalt(32)); } Console.WriteLine("d"); //var x = new DatabaseManager(); //var userId = IdGenerator.NewId(IdType.UserId); //var rootId = IdGenerator.NewId(IdType.Directory); //var subDirId = IdGenerator.NewId(IdType.Directory); //var subDirId2 = IdGenerator.NewId(IdType.Directory); //await x.DbUserManager.InsertUser(userId, rootId, "a@b.de", "hash", "salt"); //await x.DbDirectoryManager.InsertDirectory(userId, rootId, "Dir1", subDirId); //await x.DbDirectoryManager.InsertDirectory(userId, rootId, "Dir2", subDirId2); //await x.DbDirectoryManager.GetDirectoryMetadata(userId, rootId, 0); //await x.DbDirectoryManager.GetDirectoryPermissions(userId, userId, new[] {rootId, subDirId2}); //var fileId = IdGenerator.NewId(IdType.File); //await x.DbFileManager.InsertFile( // userId, // rootId, // fileId, // "myblob", // "myDoc", // 10, // CryptoHelper.GetSalt(16), // DocumentLanguage.German, // ExtensionType.Docx); //var qq = await x.DbFileManager.GetFilePermissions(userId, userId, new[] {fileId}); //var res = await x.DbFileManager.GetFileMetadata(userId, fileId, 0); //await x.DbDirectoryManager.DeleteDirectory(userId, subDirId); } } }
31.098361
108
0.567211
[ "MIT" ]
LessPaperWork/LessPaperWork.Backend
LessPaper.GuardService.UnitTest/UnitTest1.cs
1,897
C#
using System; using System.Collections.Generic; using LDAPLibrary; using LDAPLibrary.Interfarces; namespace GUI_LDAPUnitTest.Tests.BusinessLogic { public class TestUserRepository { private string[] _usersToSearch; public TestUserRepository() { string testUserDn = string.IsNullOrEmpty(Config.LdapLibrary["LDAPAdminUserDN"]) ? "no User DN" : ( "cn=" + Constants.TestUserDefaultCn + Config.LdapLibrary["LDAPAdminUserDN"].Substring( Config.LdapLibrary["LDAPAdminUserDN"].IndexOf(",", StringComparison.Ordinal)) ); var testUserOtherAttribute = new Dictionary<string, List<string>> { //aggiungere inizializzare così il dizionario {"userPassword", new List<string> {Constants.TestUserDefaultPassword}}, {"description", new List<string> {Constants.TestUserDefaultDescription}} }; SetupTestUser(testUserDn, Constants.TestUserDefaultCn, Constants.TestUserDefaultSn, testUserOtherAttribute); TestUserNewPassword = Constants.TestUserDefaultNewPassword; TestUserNewDescription = Constants.TestUserDefaultNewDescription; SetupUsersToSearch(new[] {Constants.TestSearchUserDefaultCn}); } public string TestUserNewDescription { get; set; } public string TestUserNewPassword { get; set; } public ILdapUser TestUser { get; private set; } public void SetupTestUser(string testUserDn, string testUserCn, string testUserSn, Dictionary<string, List<string>> testUserOtherAttribute) { TestUser = new LdapUser(testUserDn, testUserCn, testUserSn, testUserOtherAttribute); } public string GetTestUserCn() { return TestUser.GetUserCn(); } public string GetTestUserDn() { return TestUser.GetUserDn(); } public string GetTestUserSn() { return TestUser.GetUserSn(); } public List<string> GetTestUserOtherAttributes(string attributeKey) { return TestUser.GetUserAttribute(attributeKey); } public string[] GetTestUserOtherAttributesKeys() { return TestUser.GetUserAttributeKeys(); } public void SetupUsersToSearch(string[] list) { _usersToSearch = list; } public string[] GetUserToSearch() { return _usersToSearch; } } }
32.875
120
0.613308
[ "MIT" ]
yesnomore/LDAP-Library
GUI_LDAPUnitTest/Tests/BusinessLogic/TestUserRepository.cs
2,633
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Diamond_from_Test { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); var first = DateTime.Now; Console.WriteLine("{0}{1}{0}", new string('.',n ), new string('*',3 * n)); for (int k = n - 1; k > 0; k--) { Console.WriteLine("{0}*{1}*{0}", new string('.', k), new string('.', ((5 * n - 2 - 2 * k)))); } Console.WriteLine("{0}", new string('*', 5 * n)); int i = 1; for ( i = 1; i <= 2 * n; i++) { Console.WriteLine("{0}*{1}*{0}", new string('.', i), new string('.', (5 * n - 2 - 2 * i))); } Console.WriteLine("{0}*{1}*{0}", new string('.', i), new string('*', (5 * n - 2 - 2 * i))); var second = DateTime.Now; Console.WriteLine(second - first); //00:12:14.9300356 for n = 1000 } } }
30.305556
109
0.452796
[ "MIT" ]
1ooIL40/FundamentalsRepo
new project 04.03/Programming Basics Exam - 17 July 2016/Diamond from Test/Program.cs
1,093
C#
using System; using System.Numerics; namespace _10._Snowballs { class Program { static void Main(string[] args) { byte number = byte.Parse(Console.ReadLine()); BigInteger bestSnowballValue = int.MinValue; short bestSnowballSnow = 0; short bestSnowballTime = 0; byte bestSnowballQuality = 0; for (int i = 0; i < number; i++) { short snowballSnow = short.Parse(Console.ReadLine()); short snowballTime = short.Parse(Console.ReadLine()); byte snowballQuality = byte.Parse(Console.ReadLine()); BigInteger snowballValue = BigInteger.Pow((snowballSnow /snowballTime), (snowballQuality)); if (snowballValue > bestSnowballValue) { bestSnowballValue = snowballValue; bestSnowballSnow = snowballSnow; bestSnowballTime = snowballTime; bestSnowballQuality = snowballQuality; } } Console.WriteLine($"{bestSnowballSnow} : {bestSnowballTime} = {bestSnowballValue} ({bestSnowballQuality})"); } } }
35.882353
120
0.559016
[ "MIT" ]
DeyanDanailov/SoftUniCSharpFundamentals
repos/10. Snowballs/Program.cs
1,222
C#
using System; using System.Collections.Generic; using System.Data; using System.Linq; using Deveel.Data.Index; using Deveel.Data.Query; using Deveel.Data.Transactions; namespace Deveel.Data.DbSystem { public class TestDatabase : IDatabase { private readonly Dictionary<ObjectName, ITable> tables; public TestDatabase() { tables = new Dictionary<ObjectName, ITable>(); CellCache = new FakeCellCache(); } public ICellCache CellCache { get; private set; } public ITable SingleRowTable { get; private set; } public IDatabaseConnection CreateConnection(string schema, string userName, string password) { return new DatabaseConnection(this, schema); } public TestTable CreateTable(DataTableInfo tableInfo) { var table = new TestTable(tableInfo); tables[tableInfo.TableName] = table; return table; } #region DatabaseConnection class DatabaseConnection : IDatabaseConnection { public DatabaseConnection(TestDatabase database, string currentSchema) { Database = database; CurrentSchema = currentSchema; Transaction = new FakeTransaction(this); } public bool TableExists(ObjectName name) { return Database.tables.ContainsKey(name); } public bool IsInCaseInsensitive { get { return true; } } public ObjectName ResolveTableName(ObjectName name) { if (name.Parent == null) name = new ObjectName(new ObjectName(CurrentSchema), name.Name); return name; } public ITableQueryInfo GetTableQueryInfo(ObjectName tableName, ObjectName givenName) { DataTableInfo tableInfo = GetTableInfo(tableName); // If the table is aliased, set a new DataTableInfo with the given name if (givenName != null) { var newTableInfo = new DataTableInfo(givenName.Clone()); for (int i = 0; i < tableInfo.ColumnCount; i++) { var columnInfo = tableInfo[i]; newTableInfo.AddColumn(columnInfo.Name, columnInfo.DataType, !columnInfo.IsNotNull); } newTableInfo.IsReadOnly = true; tableInfo = newTableInfo; } return new TableQueryInfo(this, tableInfo, tableName, givenName); } private DataTableInfo GetTableInfo(ObjectName tableName) { ITable table; if (!Database.tables.TryGetValue(tableName, out table)) return null; return table.TableInfo; } public string CurrentSchema { get; private set; } IDatabase IDatabaseConnection.Database { get { return Database; } } public TestDatabase Database { get; private set; } public ITransaction Transaction { get; private set; } public IQueryPlanNode CreateObjectFetchQueryPlan(ObjectName tableName, ObjectName aliasedAs) { return new FetchTableNode(tableName, aliasedAs); } private class TableQueryInfo : ITableQueryInfo { private readonly IDatabaseConnection conn; private readonly DataTableInfo tableInfo; private readonly ObjectName tableName; private readonly ObjectName aliasedAs; public TableQueryInfo(IDatabaseConnection conn, DataTableInfo tableInfo, ObjectName tableName, ObjectName aliasedAs) { this.conn = conn; this.tableInfo = tableInfo; this.aliasedAs = aliasedAs; this.tableName = tableName; } public DataTableInfo TableInfo { get { return tableInfo; } } public IQueryPlanNode QueryPlanNode { get { return conn.CreateObjectFetchQueryPlan(tableName, aliasedAs); } } } } #endregion #region FakeCellCache class FakeCellCache : ICellCache { public void Set(int id, long row, int column, DataObject value) { } public DataObject Get(int id, long row, int column) { return null; } } #endregion #region FakeTransaction class FakeTransaction : ITransaction { private DatabaseConnection connection; public FakeTransaction(DatabaseConnection connection) { this.connection = connection; } public ObjectName[] GetTables() { return connection.Database.tables.Keys.ToArray(); } public bool TableExists(ObjectName tableName) { return connection.Database.tables.ContainsKey(tableName); } public bool RealTableExists(ObjectName tableName) { return TableExists(tableName); } public ObjectName ResolveToTableName(string currentSchema, string name, bool caseInsensitive) { return new ObjectName(new ObjectName(currentSchema), name); } public ObjectName TryResolveCase(ObjectName tableName) { throw new NotImplementedException(); } public DataTableInfo GetTableInfo(ObjectName tableName) { ITable table; if (connection.Database.tables.TryGetValue(tableName, out table)) return table.TableInfo; return null; } public ITable GetTable(ObjectName tableName) { ITable table; if (connection.Database.tables.TryGetValue(tableName, out table)) return new DataTable(connection, table); return null; } public string GetTableType(ObjectName tableName) { return "SYSTEM"; } } #endregion } }
26.388298
122
0.722435
[ "Apache-2.0" ]
kaktusan/plsqlparser
src/PlSqlParser.NUnit/Deveel.Data.DbSystem/TestDatabase.cs
4,963
C#
using Microsoft.EntityFrameworkCore; using AspNetBase.Identity.Models; using AspNetBase.Domain.Models; using AspNetBase.Contracts.Persistence; using Datiss.Common.Gaurd; using MediatR; namespace AspNetBase.Identity.Query { public class GetAppClaimTypesQuery : IRequest<IEnumerable<AppClaimTypeResult>> { } public class GetAppClaimTypeQueryHandler : IRequestHandler<GetAppClaimTypesQuery, IEnumerable<AppClaimTypeResult>> { private readonly IAuditingDbContext _db; public GetAppClaimTypeQueryHandler(IAuditingDbContext db) { _db = db ?? throw new ArgumentNullException(nameof(db)); } public async Task<IEnumerable<AppClaimTypeResult>> Handle( GetAppClaimTypesQuery request, CancellationToken cancellationToken) { request.CheckArgumentIsNull(nameof(request)); var result = new List<AppClaimTypeResult>(); var query = _db.Set<AppClaimType>().AsNoTracking(); result = await query.OrderBy(_ => _.Id) .Select(_ => new AppClaimTypeResult { Id = _.Id, Name = _.Name, Title = _.Title, Description = _.Description }).ToListAsync(); return await Task.FromResult(result); } } }
32.152174
118
0.58215
[ "MIT" ]
imaun/AspNetBase
src/app/AspNetBase.Identity/Query/GetAppClaimTypesQuery.cs
1,481
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace projetEvents { static class Program { /// <summary> /// Point d'entrée principal de l'application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new formMain()); Application.Run(new formStartup()); } } }
23.541667
65
0.610619
[ "MIT" ]
jvondermarck/manage-event
projetEvents/Program.cs
568
C#
using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System; using System.Linq; using System.Reflection; namespace FinancialDocument.Api.Filters { [AttributeUsage(AttributeTargets.Property)] public class SwaggerExcludeAttribute : Attribute { } public class SwaggerExcludeFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { var type = context.Type; if (schema?.Properties == null && type == null) return; var excludedProperties = type .GetProperties() .Where(t => t.GetCustomAttribute<SwaggerExcludeAttribute>() != null); foreach (var excludedProperty in excludedProperties) { if (schema.Properties.ContainsKey(excludedProperty.Name.ToLower())) schema.Properties.Remove(excludedProperty.Name.ToLower()); } } } }
28.428571
85
0.629146
[ "MIT" ]
MurielRLima/FinancialSolution
FinancialDocument.Api/Filters/SwaggerExcludeFilter.cs
997
C#
using System; namespace FoodApi { public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string Summary { get; set; } } }
18
69
0.597222
[ "MIT" ]
Gardusio/Ecommerce-Api
FoodApi/WeatherForecast.cs
288
C#
// <copyright file="DefaultTokenValidationParameters.cs" company="Okta, Inc"> // Copyright (c) 2018-present Okta, Inc. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. // </copyright> using Microsoft.IdentityModel.Tokens; namespace Okta.AspNet.Abstractions { public class DefaultTokenValidationParameters : TokenValidationParameters { public DefaultTokenValidationParameters(OktaWebOptions options, string issuer) { RequireExpirationTime = true; RequireSignedTokens = true; ValidateIssuer = true; ValidIssuer = issuer; ValidateAudience = true; ValidateIssuerSigningKey = true; ValidateLifetime = true; ClockSkew = options.ClockSkew; } } }
34.36
112
0.678696
[ "Apache-2.0" ]
JABIL/okta-aspnet
Okta.AspNet.Abstractions/DefaultTokenValidationParameters.cs
861
C#
using CoursesApp.Data; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CoursesApp.Services { public interface ITrainerService { int Create(Trainer trainer); Trainer FindByEmail(string email); Trainer ReadById(int Id); IEnumerable<Trainer> ReadAll(); } public class TrainerService : ITrainerService { private readonly Courses_DBEntity db; public TrainerService() { db = new Courses_DBEntity(); } public int Create(Trainer trainer) { var existsTrainer = FindByEmail(trainer.Email); if(existsTrainer != null) { return -2; } trainer.Creation_Date = DateTime.Now; db.Trainers.Add(trainer); return db.SaveChanges(); } public Trainer FindByEmail(string email) { return db.Trainers.Where(t => t.Email == email).FirstOrDefault(); } public IEnumerable<Trainer> ReadAll() { return db.Trainers; } public Trainer ReadById(int Id) { throw new NotImplementedException(); } } }
23.980769
77
0.566159
[ "MIT" ]
ahmadomar/bosla-courses-app
App/CoursesApp/Services/TrainerService.cs
1,249
C#
using System; using System.Collections.Generic; using System.Linq; using ReactiveUI; using ReactiveUI.Legacy; #pragma warning disable CS0618 // Type or member is obsolete namespace GitHub.Services { public class ErrorMap { readonly ErrorMessage defaultMessage; readonly IEnumerable<Translation> translations; public ErrorMap( ErrorMessage defaultMessage, IEnumerable<Translation> translations, IEnumerable<IRecoveryCommand> recoveryCommands) { this.defaultMessage = defaultMessage; this.translations = translations; RecoveryCommands = recoveryCommands; } public IEnumerable<IRecoveryCommand> RecoveryCommands { get; private set; } public ErrorMessage GetErrorInfo(Exception exception) { if (exception != null && translations != null) { var translated = (from t in translations let result = t.Translate(exception) where result != null select result).FirstOrDefault(); if (translated != null) return translated; } return defaultMessage; } } }
26.632653
61
0.582375
[ "MIT" ]
123balu42/VisualStudio
src/GitHub.App/Services/ErrorMap.cs
1,307
C#
using System; using System.Collections.Generic; using System.Text; namespace KamersModel { ///Een spelomgeving public class Level { public Plaats StartPlaats { get; } public List<Plaats> Plaatsen { get; } public Level(Plaats plaats) { StartPlaats = plaats; Plaatsen = new List<Plaats>(); Plaatsen.Add(StartPlaats); } public void VoegSpelerToe(Speler speler) { StartPlaats.VoegSpelerToe(speler); } } }
19.851852
48
0.572761
[ "MIT" ]
carlodecraene/Kamers
KamersModel/Level.cs
538
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 06.12.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Funcs.String.SET_001.STD.Concat__obj2.Complete.DateOnly.Boolean{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.DateOnly; using T_DATA2 =System.Boolean; using T_DATA1_U=System.DateOnly; using T_DATA2_U=System.Boolean; //////////////////////////////////////////////////////////////////////////////// //class TestSet_001__fields public static class TestSet_001__fields { private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2"; private const string c_NameOf__COL_DATA1 ="COL_TYPE_DATE"; private const string c_NameOf__COL_DATA2 ="COL2_BOOLEAN"; private const string c_TypeNameOf__COL_DATA1 ="DATE"; private const string c_TypeNameOf__COL_DATA2 ="BOOLEAN"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_DATA1,TypeName=c_TypeNameOf__COL_DATA1)] public T_DATA1 COL_DATA1 { get; set; } [Column(c_NameOf__COL_DATA2,TypeName=c_TypeNameOf__COL_DATA2)] public T_DATA2 COL_DATA2 { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1_U c_value1=new T_DATA1_U(2021,12,6); const T_DATA2_U c_value2=true; System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => string.Concat(r.COL_DATA1,r.COL_DATA2)=="2021-12-06TRUE" && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE ((").N("t",c_NameOf__COL_DATA1).T("||").N("t",c_NameOf__COL_DATA2).T(") = _utf8 '2021-12-06TRUE') AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA1 valueForColData1, T_DATA2 valueForColData2) { var newRecord=new MyContext.TEST_RECORD(); newRecord.COL_DATA1 =valueForColData1; newRecord.COL_DATA2 =valueForColData2; db.testTable.Add(newRecord); db.SaveChanges(); db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";")); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet_001__fields //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Funcs.String.SET_001.STD.Concat__obj2.Complete.DateOnly.Boolean
30.645161
176
0.576211
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Funcs/String/SET_001/STD/Concat__obj2/Complete/DateOnly/Boolean/TestSet_001__fields.cs
4,752
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.Extensions.Logging.Testing; using Xunit; using Xunit.Sdk; namespace Microsoft.Extensions.Logging.Test { public class LoggerMessageTest { [Fact] public void LogMessage() { // Arrange var controller = "home"; var action = "index"; var testSink = new TestSink(); var testLogger = new TestLogger("testlogger", testSink, enabled: true); // Act testLogger.ActionMatched(controller, action); // Assert Assert.Single(testSink.Writes); var writeContext = testSink.Writes.First(); var actualLogValues = Assert.IsAssignableFrom<IReadOnlyList<KeyValuePair<string, object>>>(writeContext.State); AssertLogValues( new[] { new KeyValuePair<string, object>("{OriginalFormat}", TestLoggerExtensions.ActionMatchedInfo.NamedStringFormat), new KeyValuePair<string, object>("controller", controller), new KeyValuePair<string, object>("action", action) }, actualLogValues.ToArray()); Assert.Equal(LogLevel.Information, writeContext.LogLevel); Assert.Equal(1, writeContext.EventId); Assert.Null(writeContext.Exception); Assert.Equal( string.Format( TestLoggerExtensions.ActionMatchedInfo.FormatString, controller, action), actualLogValues.ToString()); } [Fact] public void LogScope_WithoutAnyParameters() { // Arrange var testSink = new TestSink(); var testLogger = new TestLogger("testlogger", testSink, enabled: true); // Act var disposable = testLogger.ScopeWithoutAnyParams(); // Assert Assert.NotNull(disposable); Assert.Empty(testSink.Writes); Assert.Single(testSink.Scopes); var scopeContext = testSink.Scopes.First(); var actualLogValues = Assert.IsAssignableFrom<IReadOnlyList<KeyValuePair<string, object>>>(scopeContext.Scope); AssertLogValues(new[] { new KeyValuePair<string, object>("{OriginalFormat}", TestLoggerExtensions.ScopeWithoutAnyParameters.Message) }, actualLogValues.ToArray()); Assert.Equal( TestLoggerExtensions.ScopeWithoutAnyParameters.Message, actualLogValues.ToString()); } [Fact] public void LogScope_WithOneParameter() { // Arrange var param1 = Guid.NewGuid().ToString(); var testSink = new TestSink(); var testLogger = new TestLogger("testlogger", testSink, enabled: true); // Act var disposable = testLogger.ScopeWithOneParam(param1); // Assert Assert.NotNull(disposable); Assert.Empty(testSink.Writes); Assert.Single(testSink.Scopes); var scopeContext = testSink.Scopes.First(); var actualLogValues = Assert.IsAssignableFrom<IReadOnlyList<KeyValuePair<string, object>>>(scopeContext.Scope); AssertLogValues(new[] { new KeyValuePair<string, object>("RequestId", param1), new KeyValuePair<string, object>("{OriginalFormat}", TestLoggerExtensions.ScopeWithOneParameter.NamedStringFormat) }, actualLogValues.ToArray()); Assert.Equal( string.Format(TestLoggerExtensions.ScopeWithOneParameter.FormatString, param1), actualLogValues.ToString()); } [Fact] public void LogScope_WithTwoParameters() { // Arrange var param1 = "foo"; var param2 = "bar"; var testSink = new TestSink(); var testLogger = new TestLogger("testlogger", testSink, enabled: true); // Act var disposable = testLogger.ScopeWithTwoParams(param1, param2); // Assert Assert.NotNull(disposable); Assert.Empty(testSink.Writes); Assert.Single(testSink.Scopes); var scopeContext = testSink.Scopes.First(); var actualLogValues = Assert.IsAssignableFrom<IReadOnlyList<KeyValuePair<string, object>>>(scopeContext.Scope); AssertLogValues(new[] { new KeyValuePair<string, object>("param1", param1), new KeyValuePair<string, object>("param2", param2), new KeyValuePair<string, object>("{OriginalFormat}", TestLoggerExtensions.ScopeInfoWithTwoParameters.NamedStringFormat) }, actualLogValues.ToArray()); Assert.Equal( string.Format(TestLoggerExtensions.ScopeInfoWithTwoParameters.FormatString, param1, param2), actualLogValues.ToString()); } [Fact] public void LogScope_WithThreeParameters() { // Arrange var param1 = "foo"; var param2 = "bar"; int param3 = 10; var testSink = new TestSink(); var testLogger = new TestLogger("testlogger", testSink, enabled: true); // Act var disposable = testLogger.ScopeWithThreeParams(param1, param2, param3); // Assert Assert.NotNull(disposable); Assert.Empty(testSink.Writes); Assert.Single(testSink.Scopes); var scopeContext = testSink.Scopes.First(); var actualLogValues = Assert.IsAssignableFrom<IReadOnlyList<KeyValuePair<string, object>>>(scopeContext.Scope); AssertLogValues(new[] { new KeyValuePair<string, object>("param1", param1), new KeyValuePair<string, object>("param2", param2), new KeyValuePair<string, object>("param3", param3), new KeyValuePair<string, object>("{OriginalFormat}", TestLoggerExtensions.ScopeInfoWithThreeParameters.NamedStringFormat) }, actualLogValues.ToArray()); Assert.Equal( string.Format(TestLoggerExtensions.ScopeInfoWithThreeParameters.FormatString, param1, param2, param3), actualLogValues.ToString()); } [Theory] [MemberData(nameof(LogMessagesData))] public void LogMessages(Delegate messageDelegate, int argumentCount) { // Arrange var testSink = new TestSink(); var testLogger = new TestLogger("testlogger", testSink, enabled: true); var exception = new Exception("TestException"); var parameterNames = Enumerable.Range(0, argumentCount).Select(i => "P" + i).ToArray(); var parameters = new List<object>(); parameters.Add(testLogger); parameters.AddRange(parameterNames); parameters.Add(exception); var expectedFormat = "Log " + string.Join(" ", parameterNames.Select(p => "{" + p + "}")); var expectedToString = "Log " + string.Join(" ", parameterNames); var expectedValues = parameterNames.Select(p => new KeyValuePair<string, object>(p, p)).ToList(); expectedValues.Add(new KeyValuePair<string, object>("{OriginalFormat}", expectedFormat)); // Act messageDelegate.DynamicInvoke(parameters.ToArray()); // Assert Assert.Single(testSink.Writes); var write = testSink.Writes.First(); var actualLogValues = Assert.IsAssignableFrom<IReadOnlyList<KeyValuePair<string, object>>>(write.State); AssertLogValues(expectedValues, actualLogValues.ToList()); Assert.Equal(expectedToString, actualLogValues.ToString()); } [Fact] public void LogMessage_WithNullParameter_DoesNotMutateArgument() { // Arrange string format = "TestMessage {param1} {param2} {param3}"; string param1 = "foo"; string param2 = null; int param3 = 10; var testSink = new TestSink(); var testLogger = new TestLogger("testlogger", testSink, enabled: true); // Act testLogger.LogInformation(format, param1, param2, param3); // Assert Assert.Single(testSink.Writes); var write = testSink.Writes.First(); var actualLogValues = Assert.IsAssignableFrom<IReadOnlyList<KeyValuePair<string, object>>>(write.State); AssertLogValues(new[] { new KeyValuePair<string, object>("param1", param1), new KeyValuePair<string, object>("param2", param2), new KeyValuePair<string, object>("param3", param3), new KeyValuePair<string, object>("{OriginalFormat}", format) }, actualLogValues.ToArray()); } [Fact] public void DefineMessage_WithNoParameters_ThrowsException_WhenFormatString_HasNamedParameters() { // Arrange var formatString = "Action with name {ActionName} not found."; var expectedMessage = $"The format string '{formatString}' does not have the expected number " + $"of named parameters. Expected 0 parameter(s) but found 1 parameter(s)."; // Act var exception = Assert.Throws<ArgumentException>(() => LoggerMessage.Define(LogLevel.Error, 0, formatString)); // Assert Assert.Equal(expectedMessage, exception.Message); } [Theory] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(5)] [InlineData(6)] public void DefineMessage_ThrowsException_WhenExpectedFormatStringParameterCount_NotFound( int expectedNamedParameterCount) { // Arrange var formatString = "Action with name ActionName not found."; var expectedMessage = $"The format string '{formatString}' does not have the expected number " + $"of named parameters. Expected {expectedNamedParameterCount} parameter(s) but found 0 parameter(s)."; // Act Exception exception = null; switch (expectedNamedParameterCount) { case 1: exception = Assert.Throws<ArgumentException>( () => LoggerMessage.Define<string>(LogLevel.Error, 0, formatString)); break; case 2: exception = Assert.Throws<ArgumentException>( () => LoggerMessage.Define<string, string>(LogLevel.Error, 0, formatString)); break; case 3: exception = Assert.Throws<ArgumentException>( () => LoggerMessage.Define<string, string, string>(LogLevel.Error, 0, formatString)); break; case 4: exception = Assert.Throws<ArgumentException>( () => LoggerMessage.Define<string, string, string, string>(LogLevel.Error, 0, formatString)); break; case 5: exception = Assert.Throws<ArgumentException>( () => LoggerMessage.Define<string, string, string, string, string>(LogLevel.Error, 0, formatString)); break; case 6: exception = Assert.Throws<ArgumentException>( () => LoggerMessage.Define<string, string, string, string, string, string>(LogLevel.Error, 0, formatString)); break; default: throw new ArgumentException($"Invalid value for '{nameof(expectedNamedParameterCount)}'"); } Assert.Equal(expectedMessage, exception.Message); } [Fact] public void DefineScope_WithNoParameters_ThrowsException_WhenFormatString_HasNamedParameters() { // Arrange var formatString = "Starting request scope for request id {RequestId}"; var expectedMessage = $"The format string '{formatString}' does not have the expected number " + $"of named parameters. Expected 0 parameter(s) but found 1 parameter(s)."; // Act var exception = Assert.Throws<ArgumentException>(() => LoggerMessage.DefineScope(formatString)); // Assert Assert.Equal(expectedMessage, exception.Message); } [Theory] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(5)] [InlineData(6)] public void DefineScope_ThrowsException_WhenExpectedFormatStringParameterCount_NotFound( int expectedNamedParameterCount) { // Arrange var formatString = "Starting request scope for request id RequestId"; var expectedMessage = $"The format string '{formatString}' does not have the expected number " + $"of named parameters. Expected {expectedNamedParameterCount} parameter(s) but found 0 parameter(s)."; // Act Exception exception = null; switch (expectedNamedParameterCount) { case 1: exception = Assert.Throws<ArgumentException>( () => LoggerMessage.DefineScope<string>(formatString)); break; case 2: exception = Assert.Throws<ArgumentException>( () => LoggerMessage.DefineScope<string, string>(formatString)); break; case 3: exception = Assert.Throws<ArgumentException>( () => LoggerMessage.DefineScope<string, string, string>(formatString)); break; case 4: exception = Assert.Throws<ArgumentException>( () => LoggerMessage.DefineScope<string, string, string, string>(formatString)); break; case 5: exception = Assert.Throws<ArgumentException>( () => LoggerMessage.DefineScope<string, string, string, string, string>(formatString)); break; case 6: exception = Assert.Throws<ArgumentException>( () => LoggerMessage.DefineScope<string, string, string, string, string, string>(formatString)); break; default: throw new ArgumentException($"Invalid value for '{nameof(expectedNamedParameterCount)}'"); } Assert.Equal(expectedMessage, exception.Message); } [Theory] [MemberData(nameof(DefineMethodsWithInvalidParametersData))] public void DefineAndDefineScope_ThrowsException_WhenFormatString_IsNull(Delegate method, object[] parameters) { // Act var exception = Assert.Throws<TargetInvocationException>( () => method.DynamicInvoke(parameters)); // Assert Assert.IsType<ArgumentNullException>(exception.InnerException); } public static IEnumerable<object[]> DefineMethodsWithInvalidParametersData => new[] { new object[] { (Define)LoggerMessage.Define, DefineInvalidParameters }, new object[] { (Define)LoggerMessage.Define<string>, DefineInvalidParameters }, new object[] { (Define)LoggerMessage.Define<string, string>, DefineInvalidParameters }, new object[] { (Define)LoggerMessage.Define<string, string, string>, DefineInvalidParameters }, new object[] { (Define)LoggerMessage.Define<string, string, string, string>, DefineInvalidParameters }, new object[] { (Define)LoggerMessage.Define<string, string, string, string, string>, DefineInvalidParameters }, new object[] { (Define)LoggerMessage.Define<string, string, string, string, string, string>, DefineInvalidParameters }, new object[] { (DefineScope)LoggerMessage.DefineScope, DefineScopeInvalidParameters }, new object[] { (DefineScope)LoggerMessage.DefineScope<string>, DefineScopeInvalidParameters }, new object[] { (DefineScope)LoggerMessage.DefineScope<string, string>, DefineScopeInvalidParameters }, new object[] { (DefineScope)LoggerMessage.DefineScope<string, string, string>, DefineScopeInvalidParameters }, new object[] { (DefineScope)LoggerMessage.DefineScope<string, string, string, string>, DefineScopeInvalidParameters }, new object[] { (DefineScope)LoggerMessage.DefineScope<string, string, string, string, string>, DefineScopeInvalidParameters }, new object[] { (DefineScope)LoggerMessage.DefineScope<string, string, string, string, string, string>, DefineScopeInvalidParameters } }; public static IEnumerable<object[]> LogMessagesData => new[] { new object[] { LoggerMessage.Define(LogLevel.Error, 0, "Log "), 0 }, new object[] { LoggerMessage.Define<string>(LogLevel.Error, 1, "Log {P0}"), 1 }, new object[] { LoggerMessage.Define<string, string>(LogLevel.Error, 2, "Log {P0} {P1}"), 2 }, new object[] { LoggerMessage.Define<string, string, string>(LogLevel.Error, 3, "Log {P0} {P1} {P2}"), 3 }, new object[] { LoggerMessage.Define<string, string, string, string>(LogLevel.Error, 4, "Log {P0} {P1} {P2} {P3}"), 4 }, new object[] { LoggerMessage.Define<string, string, string, string, string>(LogLevel.Error, 5, "Log {P0} {P1} {P2} {P3} {P4}"), 5 }, new object[] { LoggerMessage.Define<string, string, string, string, string, string>(LogLevel.Error, 6, "Log {P0} {P1} {P2} {P3} {P4} {P5}"), 6 }, }; private delegate Delegate Define(LogLevel logLevel, EventId eventId, string formatString); private delegate Delegate DefineScope(string formatString); private static object[] DefineInvalidParameters => new object[] { LogLevel.Error, new EventId(0), null }; private static object[] DefineScopeInvalidParameters => new object[] { null }; private void AssertLogValues( IEnumerable<KeyValuePair<string, object>> expected, IEnumerable<KeyValuePair<string, object>> actual) { if (expected == null && actual == null) { return; } if (expected == null || actual == null) { throw new EqualException(expected, actual); } if (ReferenceEquals(expected, actual)) { return; } Assert.Equal(expected.Count(), actual.Count()); // we do not care about the order of the log values expected = expected.OrderBy(kvp => kvp.Key); actual = actual.OrderBy(kvp => kvp.Key); Assert.Equal(expected, actual); } } }
45.822844
157
0.58714
[ "MIT" ]
LakshanF/runtime
src/libraries/Microsoft.Extensions.Logging/tests/Common/LoggerMessageTest.cs
19,658
C#
#if TEST_FRAMEWORK using System; using System.Text; using UnityEditor.TestTools.TestRunner.Api; using UnityEngine; namespace Packages.Rider.Editor.UnitTesting { public class TestsCallback : ScriptableObject, IErrorCallbacks { public void RunFinished(ITestResultAdaptor result) { CallbackData.instance.isRider = false; CallbackData.instance.events.Add( new TestEvent(EventType.RunFinished, "", "","", 0, ParseTestStatus(result.TestStatus), "")); CallbackData.instance.RaiseChangedEvent(); } public void RunStarted(ITestAdaptor testsToRun) { CallbackData.instance.events.Add( new TestEvent(EventType.RunStarted, "", "","", 0, NUnit.Framework.Interfaces.TestStatus.Passed, "")); CallbackData.instance.RaiseChangedEvent(); } public void TestStarted(ITestAdaptor result) { if (result.Method == null) return; CallbackData.instance.events.Add( new TestEvent(EventType.TestStarted, GetUniqueName(result), result.Method.TypeInfo.Assembly.GetName().Name, "", 0, NUnit.Framework.Interfaces.TestStatus.Passed, result.ParentFullName)); CallbackData.instance.RaiseChangedEvent(); } public void TestFinished(ITestResultAdaptor result) { if (result.Test.Method == null) return; CallbackData.instance.events.Add( new TestEvent(EventType.TestFinished, GetUniqueName(result.Test), result.Test.Method.TypeInfo.Assembly.GetName().Name, ExtractOutput(result), (result.EndTime-result.StartTime).Milliseconds, ParseTestStatus(result.TestStatus), result.Test.ParentFullName)); CallbackData.instance.RaiseChangedEvent(); } public void OnError(string message) { CallbackData.instance.isRider = false; CallbackData.instance.events.Add( new TestEvent(EventType.RunFinished, "", "",message, 0, NUnit.Framework.Interfaces.TestStatus.Failed, "")); CallbackData.instance.RaiseChangedEvent(); } // todo: reimplement JetBrains.Rider.Unity.Editor.AfterUnity56.UnitTesting.TestEventsSender.GetUniqueName private static string GetUniqueName(ITestAdaptor test) { string str = test.FullName; return str; } private static NUnit.Framework.Interfaces.TestStatus ParseTestStatus(TestStatus testStatus) { return (NUnit.Framework.Interfaces.TestStatus)Enum.Parse(typeof(NUnit.Framework.Interfaces.TestStatus), testStatus.ToString()); } private static string ExtractOutput(ITestResultAdaptor testResult) { var stringBuilder = new StringBuilder(); if (testResult.Message != null) { stringBuilder.AppendLine("Message: "); stringBuilder.AppendLine(testResult.Message); } if (!string.IsNullOrEmpty(testResult.Output)) { stringBuilder.AppendLine("Output: "); stringBuilder.AppendLine(testResult.Output); } if (!string.IsNullOrEmpty(testResult.StackTrace)) { stringBuilder.AppendLine("Stacktrace: "); stringBuilder.AppendLine(testResult.StackTrace); } var result = stringBuilder.ToString(); if (result.Length > 0) return result; return testResult.Output ?? string.Empty; } } } #endif
37.494737
267
0.639809
[ "MIT" ]
11xdev-coder/Snek
Library/PackageCache/com.unity.ide.rider@2.0.7/Rider/Editor/UnitTesting/TestsCallback.cs
3,562
C#
using System; using System.Reactive.Linq; using Serilog; namespace ObservableTimerTest { class Program { static void Main(string[] args) { Log.Logger = new LoggerConfiguration().WriteTo.Console().CreateLogger(); // Start after 5 seconds and publish every five seconds var obs = Observable.Timer(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5)); Log.Information("Current time: {time:hh:mm ss}", DateTime.Now); using (obs.Subscribe(x => Log.Information("Produced item at {item:hh:mm ss}", DateTime.Now))) { Console.ReadLine(); } } } }
28.083333
105
0.593472
[ "MIT" ]
PacktPublishing/Mastering-C-7.2-and-.NET-Core-2.1-Application-Development
Chapter12/14 - Observable Timer Overload/Program.cs
676
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _01.Single_Inheritance { public class Dog : Animal { public void Bark() { Console.WriteLine("barking..."); } } }
17
44
0.629758
[ "MIT" ]
ginkogrudev/Databases-Basics-MS-SQ-LServer-September-2017
DB Advanced/Inheritance and Generics/01. Single Inheritance/Dog.cs
291
C#
using UnityEngine; public class C_powerupmanager : MonoBehaviour { [SerializeField] GameObject shield; [SerializeField] Transform shield_t; [SerializeField] float shieldspawn=5f; [SerializeField] GameObject firepower; [SerializeField] Transform firepower_t; [SerializeField] float firepowerspawn = 10f; [SerializeField] GameObject triplefire; [SerializeField] Transform triplefire_t; [SerializeField] float triplefirespawn = 15f; // Start is called before the first frame update void Start() { InvokeRepeating("activatehield", 5f, shieldspawn); InvokeRepeating("activatefirepower", 20f, shieldspawn); InvokeRepeating("activatetriplefire", 25f, shieldspawn); } // Update is called once per frame void activatehield() { if (!shield.activeInHierarchy & C_game_control.control.shield == false) { shield_t.position = transform.position; shield.SetActive(true); } } void activatefirepower() { if (!firepower.activeInHierarchy & C_game_control.control.firepower == false) { firepower_t.position = transform.position; firepower.SetActive(true); } } void activatetriplefire() { if (!triplefire.activeInHierarchy & C_game_control.control.triplefire == false) { triplefire_t.position = transform.position; triplefire.SetActive(true); } } }
25.180328
87
0.638021
[ "MIT" ]
thatsun/prueba
prueba/Assets/scripts/C_powerupmanager.cs
1,538
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEditor; using UnityEngine; namespace UnityEditorUI { /// <summary> /// Widget for displaying read-only text. /// </summary> public interface ILabel : IWidget { /// <summary> /// Label text. /// </summary> IPropertyBinding<string, ILabel> Text { get; } /// <summary> /// Text displayed on mouse hover. /// </summary> IPropertyBinding<string, ILabel> Tooltip { get; } /// <summary> /// Whether or not the label should be displayed in bold (default is false). /// </summary> //IPropertyBinding<bool, ILabel> Bold { get; } /// <summary> /// Width of the widget in pixels. Default uses auto-layout. /// </summary> //IPropertyBinding<int, ILabel> Width { get; } /// <summary> /// Height of the widget in pixels. Default uses auto-layout. /// </summary> //IPropertyBinding<int, ILabel> Height { get; } } /// <summary> /// Widget for displaying read-only text. /// </summary> internal class Label : AbstractWidget, ILabel { private string text = String.Empty; private string tooltip = String.Empty; private PropertyBinding<string, ILabel> textProperty; private PropertyBinding<string, ILabel> tooltipProperty; public IPropertyBinding<string, ILabel> Text { get { return textProperty; } } public IPropertyBinding<string, ILabel> Tooltip { get { return tooltipProperty; } } private GUILayoutOption[] mGuiLayoutOptions = {}; internal Label(ILayout parent,int width) : base(parent) { textProperty = new PropertyBinding<string, ILabel>( this, value => text = value ); tooltipProperty = new PropertyBinding<string, ILabel>( this, value => tooltip = value ); if (width != -1) { mGuiLayoutOptions = new List<GUILayoutOption>() { GUILayout.Width(width) }.ToArray(); } } public override void OnGUI() { var guiContent = new GUIContent(text, tooltip); /*用这些有问题 var style = bold ? EditorStyles.boldLabel : EditorStyles.label; var layoutOptions = new List<GUILayoutOption>(); if (height >= 0) { layoutOptions.Add(GUILayout.Height(height)); } GUILayout.Label(guiContent, style, layoutOptions.ToArray()); */ // 默认用这个其他的有一堆问题 GUILayout.Label(guiContent,mGuiLayoutOptions); } public override void BindViewModel(object viewModel) { textProperty.BindViewModel(viewModel); tooltipProperty.BindViewModel(viewModel); //boldProperty.BindViewModel(viewModel); //widthProperty.BindViewModel(viewModel); //heightProperty.BindViewModel(viewModel); } } }
30.697248
92
0.534967
[ "MIT" ]
317392507/QFramework
Assets/QFramework/Framework/0.Core/Editor/0.EditorKit/IMGUIMVVM/Editor/Label.cs
3,384
C#
namespace api.Core.Repository { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.")] public interface IRepository<T> where T : class { T Get(string celular, string contraseña); IQueryable GetAll(); void Save(T tObject); void SaveRange(IEnumerable<T> tlistEnumerable); IQueryable<T> Find(Expression<Func<T, bool>> predicate); void Remove(T entidad); void RemoveRange(IEnumerable<T> tEnumerable); } }
26.925926
147
0.687758
[ "MIT" ]
Kimeru29/HOAN
api/Core/Repository/IRepository.cs
730
C#
using TRL.Common.Collections; using TRL.Common.Data; using TRL.Common.Models; using TRL.Common.TimeHelpers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using TRL.Logging; using TRL.Common; namespace TRL.Handlers.StopLoss { public class StrategiesStopLossByPointsOnTickHandlers:HashSet<StrategyStopLossByPointsOnTick> { private IDataContext tradingData; private ObservableQueue<Signal> signalQueue; private ILogger logger; private bool measureStopFromSignal; public StrategiesStopLossByPointsOnTickHandlers() : this(TradingData.Instance, SignalQueue.Instance, DefaultLogger.Instance) { } public StrategiesStopLossByPointsOnTickHandlers(IDataContext tradingData, ObservableQueue<Signal> signalQueue, ILogger logger, bool measureStopFromSignal = false) { this.tradingData = tradingData; this.signalQueue = signalQueue; this.logger = logger; this.measureStopFromSignal = measureStopFromSignal; ActivateHandlers(); } private void ActivateHandlers() { foreach (StrategyHeader strategyHeader in this.tradingData.Get<IEnumerable<StrategyHeader>>()) { if (!this.tradingData.Get<IEnumerable<StopPointsSettings>>().Any(s => s.Strategy.Id == strategyHeader.Id)) continue; if (!this.tradingData.Get<IEnumerable<StopLossOrderSettings>>().Any(s => s.Strategy.Id == strategyHeader.Id)) continue; base.Add(new StrategyStopLossByPointsOnTick(strategyHeader, this.tradingData, this.signalQueue, this.logger, this.measureStopFromSignal)); this.logger.Log(String.Format("{0:dd/MM/yyyy H:mm:ss.fff}, {1}, StrategyStopLossOnTick handler has been activated for {2} ", BrokerDateTime.Make(DateTime.Now), this.GetType().Name, strategyHeader.ToString())); } } } }
37.482143
154
0.652692
[ "Apache-2.0" ]
wouldyougo/TRx
TRL.Handlers/StopLoss/StrategiesStopLossByPointsOnTickHandlers.cs
2,101
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; #if !CODE_STYLE using System.Linq; using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.Internal.Log { /// <summary> /// provide a way to log activities to various back end such as etl, code marker and etc /// </summary> internal static partial class Logger { private static ILogger? s_currentLogger; /// <summary> /// next unique block id that will be given to each LogBlock /// </summary> private static int s_lastUniqueBlockId; /// <summary> /// give a way to explicitly set/replace the logger /// </summary> public static ILogger? SetLogger(ILogger logger) { // we don't care what was there already, just replace it explicitly return Interlocked.Exchange(ref Logger.s_currentLogger, logger); } /// <summary> /// ensure we have a logger by putting one from workspace service if one is not there already. /// </summary> public static ILogger? GetLogger() => Logger.s_currentLogger; /// <summary> /// log a specific event with a simple context message which should be very cheap to create /// </summary> public static void Log(FunctionId functionId, string? message = null) { var logger = GetLogger(); if (logger == null) { return; } if (!logger.IsEnabled(functionId)) { return; } logger.Log(functionId, LogMessage.Create(message ?? "")); } /// <summary> /// log a specific event with a context message that will only be created when it is needed. /// the messageGetter should be cheap to create. in another word, it shouldn't capture any locals /// </summary> public static void Log(FunctionId functionId, Func<string> messageGetter) { var logger = GetLogger(); if (logger == null) { return; } if (!logger.IsEnabled(functionId)) { return; } var logMessage = LogMessage.Create(messageGetter); logger.Log(functionId, logMessage); logMessage.Free(); } /// <summary> /// log a specific event with a context message that requires some arguments to be created when requested. /// given arguments will be passed to the messageGetter so that it can create the context message without requiring lifted locals /// </summary> public static void Log<TArg>( FunctionId functionId, Func<TArg, string> messageGetter, TArg arg ) { var logger = GetLogger(); if (logger == null) { return; } if (!logger.IsEnabled(functionId)) { return; } var logMessage = LogMessage.Create(messageGetter, arg); logger.Log(functionId, logMessage); logMessage.Free(); } /// <summary> /// log a specific event with a context message that requires some arguments to be created when requested. /// given arguments will be passed to the messageGetter so that it can create the context message without requiring lifted locals /// </summary> public static void Log<TArg0, TArg1>( FunctionId functionId, Func<TArg0, TArg1, string> messageGetter, TArg0 arg0, TArg1 arg1 ) { var logger = GetLogger(); if (logger == null) { return; } if (!logger.IsEnabled(functionId)) { return; } var logMessage = LogMessage.Create(messageGetter, arg0, arg1); logger.Log(functionId, logMessage); logMessage.Free(); } /// <summary> /// log a specific event with a context message that requires some arguments to be created when requested. /// given arguments will be passed to the messageGetter so that it can create the context message without requiring lifted locals /// </summary> public static void Log<TArg0, TArg1, TArg2>( FunctionId functionId, Func<TArg0, TArg1, TArg2, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2 ) { var logger = GetLogger(); if (logger == null) { return; } if (!logger.IsEnabled(functionId)) { return; } var logMessage = LogMessage.Create(messageGetter, arg0, arg1, arg2); logger.Log(functionId, logMessage); logMessage.Free(); } /// <summary> /// log a specific event with a context message that requires some arguments to be created when requested. /// given arguments will be passed to the messageGetter so that it can create the context message without requiring lifted locals /// </summary> public static void Log<TArg0, TArg1, TArg2, TArg3>( FunctionId functionId, Func<TArg0, TArg1, TArg2, TArg3, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3 ) { var logger = GetLogger(); if (logger == null) { return; } if (!logger.IsEnabled(functionId)) { return; } var logMessage = LogMessage.Create(messageGetter, arg0, arg1, arg2, arg3); logger.Log(functionId, logMessage); logMessage.Free(); } /// <summary> /// log a specific event with a context message. /// </summary> public static void Log(FunctionId functionId, LogMessage logMessage) { var logger = GetLogger(); if (logger == null) { return; } if (!logger.IsEnabled(functionId)) { return; } logger.Log(functionId, logMessage); logMessage.Free(); } /// <summary> /// return next unique pair id /// </summary> private static int GetNextUniqueBlockId() => Interlocked.Increment(ref s_lastUniqueBlockId); /// <summary> /// simplest way to log a start and end pair /// </summary> public static IDisposable LogBlock(FunctionId functionId, CancellationToken token) => LogBlock(functionId, string.Empty, token); /// <summary> /// simplest way to log a start and end pair with a simple context message which should be very cheap to create /// </summary> public static IDisposable LogBlock( FunctionId functionId, string? message, CancellationToken token ) { var logger = GetLogger(); if (logger == null) { return EmptyLogBlock.Instance; } if (!logger.IsEnabled(functionId)) { return EmptyLogBlock.Instance; } return CreateLogBlock( functionId, LogMessage.Create(message ?? ""), GetNextUniqueBlockId(), token ); } /// <summary> /// log a start and end pair with a context message that will only be created when it is needed. /// the messageGetter should be cheap to create. in another word, it shouldn't capture any locals /// </summary> public static IDisposable LogBlock( FunctionId functionId, Func<string> messageGetter, CancellationToken token ) { var logger = GetLogger(); if (logger == null) { return EmptyLogBlock.Instance; } if (!logger.IsEnabled(functionId)) { return EmptyLogBlock.Instance; } return CreateLogBlock( functionId, LogMessage.Create(messageGetter), GetNextUniqueBlockId(), token ); } /// <summary> /// log a start and end pair with a context message that requires some arguments to be created when requested. /// given arguments will be passed to the messageGetter so that it can create the context message without requiring lifted locals /// </summary> public static IDisposable LogBlock<TArg>( FunctionId functionId, Func<TArg, string> messageGetter, TArg arg, CancellationToken token ) { var logger = GetLogger(); if (logger == null) { return EmptyLogBlock.Instance; } if (!logger.IsEnabled(functionId)) { return EmptyLogBlock.Instance; } return CreateLogBlock( functionId, LogMessage.Create(messageGetter, arg), GetNextUniqueBlockId(), token ); } /// <summary> /// log a start and end pair with a context message that requires some arguments to be created when requested. /// given arguments will be passed to the messageGetter so that it can create the context message without requiring lifted locals /// </summary> public static IDisposable LogBlock<TArg0, TArg1>( FunctionId functionId, Func<TArg0, TArg1, string> messageGetter, TArg0 arg0, TArg1 arg1, CancellationToken token ) { var logger = GetLogger(); if (logger == null) { return EmptyLogBlock.Instance; } if (!logger.IsEnabled(functionId)) { return EmptyLogBlock.Instance; } return CreateLogBlock( functionId, LogMessage.Create(messageGetter, arg0, arg1), GetNextUniqueBlockId(), token ); } /// <summary> /// log a start and end pair with a context message that requires some arguments to be created when requested. /// given arguments will be passed to the messageGetter so that it can create the context message without requiring lifted locals /// </summary> public static IDisposable LogBlock<TArg0, TArg1, TArg2>( FunctionId functionId, Func<TArg0, TArg1, TArg2, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, CancellationToken token ) { var logger = GetLogger(); if (logger == null) { return EmptyLogBlock.Instance; } if (!logger.IsEnabled(functionId)) { return EmptyLogBlock.Instance; } return CreateLogBlock( functionId, LogMessage.Create(messageGetter, arg0, arg1, arg2), GetNextUniqueBlockId(), token ); } /// <summary> /// log a start and end pair with a context message that requires some arguments to be created when requested. /// given arguments will be passed to the messageGetter so that it can create the context message without requiring lifted locals /// </summary> public static IDisposable LogBlock<TArg0, TArg1, TArg2, TArg3>( FunctionId functionId, Func<TArg0, TArg1, TArg2, TArg3, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, CancellationToken token ) { var logger = GetLogger(); if (logger == null) { return EmptyLogBlock.Instance; } if (!logger.IsEnabled(functionId)) { return EmptyLogBlock.Instance; } return CreateLogBlock( functionId, LogMessage.Create(messageGetter, arg0, arg1, arg2, arg3), GetNextUniqueBlockId(), token ); } /// <summary> /// log a start and end pair with a context message. /// </summary> public static IDisposable LogBlock( FunctionId functionId, LogMessage logMessage, CancellationToken token ) { var logger = GetLogger(); if (logger == null) { return EmptyLogBlock.Instance; } if (!logger.IsEnabled(functionId)) { return EmptyLogBlock.Instance; } return CreateLogBlock(functionId, logMessage, GetNextUniqueBlockId(), token); } #if !CODE_STYLE public static Func<FunctionId, bool> GetLoggingChecker(IGlobalOptionService optionService) { var functionIds = Enum.GetValues(typeof(FunctionId)).Cast<FunctionId>(); var functionIdOptions = functionIds.ToDictionary( id => id, id => optionService.GetOption(FunctionIdOptions.GetOption(id)) ); return functionId => functionIdOptions[functionId]; } #endif } }
31.986486
137
0.532601
[ "MIT" ]
belav/roslyn
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/Logger.cs
14,204
C#
using System; namespace LibCommon.Structs.GB28181 { /// <summary> /// 不需要鉴权的设备 /// </summary> [Serializable] public class NoAuthenticationRequired { private string? _ipV4Address; private string? _ipV6Address; private string _deviceId; /// <summary> /// 设备ipv4地址(可空) /// </summary> public string? IpV4Address { get => _ipV4Address; set => _ipV4Address = value; } /// <summary> /// 设备ipv6地址(可空) /// </summary> public string? IpV6Address { get => _ipV6Address; set => _ipV6Address = value; } /// <summary> /// 设备id /// </summary> public string DeviceId { get => _deviceId; set => _deviceId = value ?? throw new ArgumentNullException(nameof(value)); } } }
21.488372
87
0.492424
[ "MIT" ]
chenyi2006520/AKStream
LibCommon/Structs/GB28181/NoAuthenticationRequired.cs
968
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.462) // Version 5.462.0.0 www.ComponentFactory.com // ***************************************************************************** using System.Drawing; using System.ComponentModel; namespace ComponentFactory.Krypton.Toolkit { /// <summary> /// Implement storage for palette background details. /// </summary> public class PaletteBackColor1 : PaletteBack { #region Identity /// <summary> /// Initialize a new instance of the PaletteBackColor1 class. /// </summary> /// <param name="inherit">Source for inheriting defaulted values.</param> /// <param name="needPaint">Delegate for notifying paint requests.</param> public PaletteBackColor1(IPaletteBack inherit, NeedPaintHandler needPaint) : base(inherit, needPaint) { } #endregion #region PopulateFromBase /// <summary> /// Populate values from the base palette. /// </summary> /// <param name="state">Palette state to use when populating.</param> public new void PopulateFromBase(PaletteState state) { // Get the values and set into storage Color1 = GetBackColor1(state); } #endregion #region Draw /// <summary> /// Gets a value indicating if background should be drawn. /// </summary> [Browsable(false)] public new InheritBool Draw { get => base.Draw; set => base.Draw = value; } #endregion #region GraphicsHint /// <summary> /// Gets the graphics hint for drawing the background. /// </summary> [Browsable(false)] public new PaletteGraphicsHint GraphicsHint { get => base.GraphicsHint; set => base.GraphicsHint = value; } #endregion #region Color2 /// <summary> /// Gets and sets the second background color. /// </summary> [Browsable(false)] public new Color Color2 { get => base.Color2; set => base.Color2 = value; } #endregion #region ColorStyle /// <summary> /// Gets and sets the color drawing style. /// </summary> [Browsable(false)] public new PaletteColorStyle ColorStyle { get => base.ColorStyle; set => base.ColorStyle = value; } #endregion #region ColorAlign /// <summary> /// Gets and set the color alignment. /// </summary> [Browsable(false)] public new PaletteRectangleAlign ColorAlign { get => base.ColorAlign; set => base.ColorAlign = value; } #endregion #region ColorAngle /// <summary> /// Gets and sets the color angle. /// </summary> [Browsable(false)] public new float ColorAngle { get => base.ColorAngle; set => base.ColorAngle = value; } #endregion #region Image /// <summary> /// Gets and sets the background image. /// </summary> [Browsable(false)] public new Image Image { get => base.Image; set => base.Image = value; } #endregion #region ImageStyle /// <summary> /// Gets and sets the background image style. /// </summary> [Browsable(false)] public new PaletteImageStyle ImageStyle { get => base.ImageStyle; set => base.ImageStyle = value; } #endregion #region ImageAlign /// <summary> /// Gets and set the image alignment. /// </summary> [Browsable(false)] public new PaletteRectangleAlign ImageAlign { get => base.ImageAlign; set => base.ImageAlign = value; } #endregion } }
30.185897
157
0.531535
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-NET-5.462
Source/Krypton Components/ComponentFactory.Krypton.Toolkit/Palette Base/PaletteBack/PaletteBackColor1.cs
4,712
C#
using System; using System.Collections.Generic; using System.Linq; namespace DefiningClasses { public class StartUp { public static void Main() { var engines = new List<Engine>(); var cars = new List<Car>(); int enginesCount = int.Parse(Console.ReadLine()); for (int i = 0; i < enginesCount; i++) { var engineInfo = Console.ReadLine() .Split(" ", StringSplitOptions.RemoveEmptyEntries) .ToArray(); string model = engineInfo[0]; int power = int.Parse(engineInfo[1]); if (engineInfo.Length == 2) { engines.Add(new Engine(model, power)); } else if (engineInfo.Length == 3) { if (int.TryParse(engineInfo[2], out int displacement)) { engines.Add(new Engine(model, power, displacement)); } else { engines.Add(new Engine(model, power, engineInfo[2])); } } else if (engineInfo.Length == 4) { int displacement = int.Parse(engineInfo[2]); string efficiency = engineInfo[3]; engines.Add(new Engine( model, power, displacement, efficiency)); } } int carsCount = int.Parse(Console.ReadLine()); for (int i = 0; i < carsCount; i++) { var carInfo = Console.ReadLine() .Split(" ", StringSplitOptions.RemoveEmptyEntries) .ToArray(); string model = carInfo[0]; string engineModel = carInfo[1]; var engine = GetEngine(engines, engineModel); if (carInfo.Length == 2) { cars.Add(new Car(model, engine)); } else if (carInfo.Length == 3) { if (int.TryParse(carInfo[2], out int weight)) { cars.Add(new Car(model, engine, weight)); } else { cars.Add(new Car(model, engine, carInfo[2])); } } else if (carInfo.Length == 4) { int weight = int.Parse(carInfo[2]); string color = carInfo[3]; cars.Add(new Car( model, engine, weight, color)); } } foreach (var car in cars) { Console.WriteLine(car); } } public static Engine GetEngine(List<Engine> engines, string engineModel) => engines .Where(x => x.Model == engineModel) .FirstOrDefault(); } }
31.105769
91
0.3966
[ "MIT" ]
markodjunev/Softuni
C#/C# Advanced/Defining Classes-Exercise/Car Salesman/StartUp.cs
3,237
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class SspiCli { [DllImport(Interop.Libraries.SspiCli, SetLastError = true)] internal static extern int LsaGetLogonSessionData( ref LUID LogonId, out SafeLsaReturnBufferHandle ppLogonSessionData ); } }
29
71
0.722323
[ "MIT" ]
belav/runtime
src/libraries/Common/src/Interop/Windows/SspiCli/Interop.LsaGetLogonSessionData.cs
551
C#
//------------------------------------------------------------------------------ // <copyright file="update.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /**************************************************************************\ * * Copyright (c) 1998-2002, Microsoft Corp. All Rights Reserved. * * Module Name: * * update.cs * * Abstract: * * Revision History: * \**************************************************************************/ namespace System.Web.MyWebAdminUI { using System; using System.Data; using System.IO; using System.Collections; using System.Web; using System.Web.Util; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; /// <include file='doc\update.uex' path='docs/doc[@for="updatePage"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class updatePage : Page { /// <include file='doc\update.uex' path='docs/doc[@for="updatePage.UrlHidden"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected HtmlInputHidden UrlHidden; /// <include file='doc\update.uex' path='docs/doc[@for="updatePage.AppName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected Label AppName; /// <include file='doc\update.uex' path='docs/doc[@for="updatePage.OldVersion"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected Label OldVersion; /// <include file='doc\update.uex' path='docs/doc[@for="updatePage.NewVersion"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected Label NewVersion; /// <include file='doc\update.uex' path='docs/doc[@for="updatePage.update"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool update = false; /// <include file='doc\update.uex' path='docs/doc[@for="updatePage.Page_Load"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Page_Load(Object sender, EventArgs e) { if (!IsPostBack) { String appurl = Request.QueryString["url"]; MyWebApplication app = MyWeb.GetApplication(appurl); //checking if local if(app.LocalApplication) { Response.Redirect("myweb://Home/myweb2.aspx?success=local" ); } else if (app != null && appurl != null && appurl.Length>0) { UrlHidden.Value = appurl; AppName.Text =(app.Manifest.Name.Length >0) ? (app.Manifest.Name):"the Local Application selected";; String oldVersion = app.Manifest.Version; oldVersion = oldVersion.ToLower(CultureInfo.InvariantCulture); MyWebManifest newManifest = MyWeb.GetManifest(appurl); if(newManifest == null) { Response.Redirect("myweb://Home/myweb2.aspx?success=notfound"); } else { String newVersion = newManifest.Version; newVersion = newVersion.ToLower(CultureInfo.InvariantCulture); if (!oldVersion.Equals(newVersion) ) { update=true; NewVersion.Text = newVersion; OldVersion.Text = oldVersion; } } } } } /// <include file='doc\update.uex' path='docs/doc[@for="updatePage.Submit_Click"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Submit_Click(Object sender, EventArgs e) { MyWebApplication app = MyWeb.GetApplication(UrlHidden.Value); String installedLocation = app.Manifest.InstalledLocation; String name = app.Manifest.Name; if (app != null) { int update = app.Update(); Response.Redirect("myweb://Home/myweb2.aspx?name=" + name + "&success=" + update.ToString() + "&URL=" + UrlHidden.Value + "&installedLocation=" + installedLocation); } else if (app ==null) { Response.Redirect("myweb://Home/myweb2.aspx?name=" + name + "&success=NoApp"); } } } }
30.303448
179
0.528903
[ "Unlicense" ]
bestbat/Windows-Server
com/netfx/src/framework/xsp/deadcode/myweb/update.cs
4,394
C#
using Quartz.Plugins.SendMailJob.DataLayer.Model; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Text; using System.Threading.Tasks; namespace Quartz.Plugins.SendMailJob.DataLayer.Manager { public class SendDataMailAccountManager { public static async Task<List<SendDataMailAccount>> GetMailAccounts() { var sqlConStr = ConstantHelper.GetConnectionString(); List<SendDataMailAccount> sendDataMailAccountList = new List<SendDataMailAccount>(); try { using (SqlConnection connectionQueryData = new SqlConnection(sqlConStr)) { if (connectionQueryData.State == System.Data.ConnectionState.Closed) { connectionQueryData.Open(); } #region Execute Command var selectQuery = @" SELECT [MAILACCOUNTID] ,[MAILACCOUNTTITLE] ,[MAILSERVERNAME] ,[MAILACCOUNTNAME] ,[MAILACCOUNTPASSWORD] ,[MAILPOP3PORT] ,[MAILSMTPPORT] ,[FROMMAILADDRESS] ,[ENABLESSL] FROM [dbo].[PLG_SENDDATA_MAILACCOUNT] WHERE ACTIVE = 1 AND ISDEFAULT = 1 "; using (SqlCommand command = new SqlCommand(selectQuery, connectionQueryData)) { DataTable dataTable = new DataTable(); // create data adapter SqlDataAdapter da = new SqlDataAdapter(command); // this will query your database and return the result to your datatable da.Fill(dataTable); for (int i = 0; i < dataTable.Rows.Count ; i++) { var id = Int32.Parse(dataTable.Rows[i]["MAILACCOUNTID"].ToString()); var title = dataTable.Rows[i]["MAILACCOUNTTITLE"]?.ToString(); var serverName = dataTable.Rows[i]["MAILSERVERNAME"]?.ToString(); var accountName = dataTable.Rows[i]["MAILACCOUNTNAME"]?.ToString(); var accountPass = dataTable.Rows[i]["MAILACCOUNTPASSWORD"]?.ToString(); var pop3Port = Int32.Parse(dataTable.Rows[i]["MAILPOP3PORT"].ToString()); var smptpPort = Int32.Parse(dataTable.Rows[i]["MAILSMTPPORT"].ToString()); var fromAddress = dataTable.Rows[i]["FROMMAILADDRESS"]?.ToString(); var enableSSLValue = dataTable.Rows[i]["ENABLESSL"]?.ToString(); Boolean.TryParse(enableSSLValue, out bool enableSSL); var sendDataMailAccount = new SendDataMailAccount() { AccountId = id, AccountName = accountName, AccountPass = accountPass, Active = 1, FromMailAddress = fromAddress, MailPop3Port = pop3Port, MailSmtpPort = smptpPort, ServerName = serverName, Title = title, EnableSSL =enableSSL }; sendDataMailAccountList.Add(sendDataMailAccount); } } #endregion try { connectionQueryData.Close(); } catch (Exception) { } } } catch (Exception ex) { //TODO:Log } return sendDataMailAccountList; } } }
38.269231
102
0.481658
[ "MIT" ]
Logi3PL/Quartzmin
Source/Quartz.Plugins.SendMailJob/DataLayer/Manager/SendDataMailAccountManager.cs
3,982
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; namespace EZOper.NetSiteUtilities.AopApi { /// <summary> /// AlipayOpenPublicDefaultExtensionCreateModel Data Structure. /// </summary> [Serializable] public class AlipayOpenPublicDefaultExtensionCreateModel : AopObject { /// <summary> /// 默认扩展区列表,最多包含3个扩展区 /// </summary> [XmlArray("areas")] [XmlArrayItem("extension_area")] public List<ExtensionArea> Areas { get; set; } } }
25.428571
72
0.659176
[ "MIT" ]
erikzhouxin/CSharpSolution
NetSiteUtilities/AopApi/Domain/AlipayOpenPublicDefaultExtensionCreateModel.cs
566
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; using System.Xml.Serialization; namespace MusicHub.DataProcessor.ImportDtos { [XmlType("Song")] public class SongDto { [XmlElement("Name")] [Required] [MinLength(3), MaxLength(20)] public string Name { get; set; } [XmlElement("Duration")] [Required] public string Duration { get; set; } [XmlElement("CreatedOn")] [Required] public string CreatedOn { get; set; } [XmlElement("Genre")] [Required] public string Genre { get; set; } [XmlElement("AlbumId")] public int? AlbumId { get; set; } [XmlElement("WriterId")] [Required] public int WriterId { get; set; } [XmlElement("Price")] [Required] //[Range(typeof(decimal), "0.00M", "79228162514264337593543950335M")] [Range(0.00, 1111111111111111)] public decimal Price { get; set; } } }
24.44186
77
0.588963
[ "MIT" ]
antoniovelev/Softuni
C#/Entity Framework/01. Model Defition_Skeleton + Datasets/MusicHub/DataProcessor/ImportDtos/SongDto.cs
1,053
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.IO; using System.IO.Pipelines; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Http.Connections.Internal.Transports { internal class LongPollingServerTransport : IHttpTransport { private readonly PipeReader _application; private readonly ILogger _logger; private readonly CancellationToken _timeoutToken; private readonly HttpConnectionContext? _connection; public LongPollingServerTransport(CancellationToken timeoutToken, PipeReader application, ILoggerFactory loggerFactory) : this(timeoutToken, application, loggerFactory, connection: null) { } public LongPollingServerTransport(CancellationToken timeoutToken, PipeReader application, ILoggerFactory loggerFactory, HttpConnectionContext? connection) { _timeoutToken = timeoutToken; _application = application; _connection = connection; // We create the logger with a string to preserve the logging namespace after the server side transport renames. _logger = loggerFactory.CreateLogger("Microsoft.AspNetCore.Http.Connections.Internal.Transports.LongPollingTransport"); } public async Task ProcessRequestAsync(HttpContext context, CancellationToken token) { try { var result = await _application.ReadAsync(token); var buffer = result.Buffer; try { if (buffer.IsEmpty && (result.IsCompleted || result.IsCanceled)) { Log.LongPolling204(_logger); context.Response.ContentType = "text/plain"; context.Response.StatusCode = StatusCodes.Status204NoContent; return; } // We're intentionally not checking cancellation here because we need to drain messages we've got so far, // but it's too late to emit the 204 required by being canceled. Log.LongPollingWritingMessage(_logger, buffer.Length); context.Response.ContentLength = buffer.Length; context.Response.ContentType = "application/octet-stream"; _connection?.StartSendCancellation(); await context.Response.Body.WriteAsync(buffer, _connection?.SendingToken ?? default); } finally { _connection?.StopSendCancellation(); _application.AdvanceTo(buffer.End); } } catch (OperationCanceledException) { // 4 cases: // 1 - Request aborted, the client disconnected (no response) // 2 - The poll timeout is hit (200) // 3 - SendingToken was canceled, abort the connection // 4 - A new request comes in and cancels this request (204) // Case 1 if (context.RequestAborted.IsCancellationRequested) { // Don't count this as cancellation, this is normal as the poll can end due to the browser closing. // The background thread will eventually dispose this connection if it's inactive Log.LongPollingDisconnected(_logger); } // Case 2 else if (_timeoutToken.IsCancellationRequested) { Log.PollTimedOut(_logger); context.Response.ContentLength = 0; context.Response.ContentType = "text/plain"; context.Response.StatusCode = StatusCodes.Status200OK; } else if (_connection?.SendingToken.IsCancellationRequested == true) { // Case 3 context.Response.ContentType = "text/plain"; context.Response.StatusCode = StatusCodes.Status204NoContent; throw; } else { // Case 4 Log.LongPolling204(_logger); context.Response.ContentType = "text/plain"; context.Response.StatusCode = StatusCodes.Status204NoContent; } } catch (Exception ex) { Log.LongPollingTerminated(_logger, ex); context.Response.ContentType = "text/plain"; context.Response.StatusCode = StatusCodes.Status500InternalServerError; throw; } } private static class Log { private static readonly Action<ILogger, Exception?> _longPolling204 = LoggerMessage.Define(LogLevel.Debug, new EventId(1, "LongPolling204"), "Terminating Long Polling connection by sending 204 response."); private static readonly Action<ILogger, Exception?> _pollTimedOut = LoggerMessage.Define(LogLevel.Debug, new EventId(2, "PollTimedOut"), "Poll request timed out. Sending 200 response to connection."); private static readonly Action<ILogger, long, Exception?> _longPollingWritingMessage = LoggerMessage.Define<long>(LogLevel.Trace, new EventId(3, "LongPollingWritingMessage"), "Writing a {Count} byte message to connection."); private static readonly Action<ILogger, Exception?> _longPollingDisconnected = LoggerMessage.Define(LogLevel.Debug, new EventId(4, "LongPollingDisconnected"), "Client disconnected from Long Polling endpoint for connection."); private static readonly Action<ILogger, Exception?> _longPollingTerminated = LoggerMessage.Define(LogLevel.Error, new EventId(5, "LongPollingTerminated"), "Long Polling transport was terminated due to an error on connection."); public static void LongPolling204(ILogger logger) { _longPolling204(logger, null); } public static void PollTimedOut(ILogger logger) { _pollTimedOut(logger, null); } public static void LongPollingWritingMessage(ILogger logger, long count) { _longPollingWritingMessage(logger, count, null); } public static void LongPollingDisconnected(ILogger logger) { _longPollingDisconnected(logger, null); } public static void LongPollingTerminated(ILogger logger, Exception ex) { _longPollingTerminated(logger, ex); } } } }
43.469136
166
0.593865
[ "MIT" ]
48355746/AspNetCore
src/SignalR/common/Http.Connections/src/Internal/Transports/LongPollingServerTransport.cs
7,042
C#
namespace osfDesigner { public enum DrawMode { ВручнуюПеременный = 2, ВручнуюФиксированный = 1, Стандартный = 0 } }
15.3
33
0.581699
[ "MPL-2.0" ]
Nivanchenko/OneScriptFormsDesigner
OneScriptFormsDesigner/OneScriptFormsDesigner/DrawMode.cs
203
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Security.Permissions; using Microsoft.Azure.Commands.DataFactoryV2.Models; namespace Microsoft.Azure.Commands.DataFactoryV2 { [Cmdlet("Get", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "DataFactoryV2LinkedService", DefaultParameterSetName = ParameterSetNames.ByFactoryName), OutputType(typeof(PSLinkedService))] public class GetAzureDataFactoryLinkedServiceCommand : DataFactoryContextBaseGetCmdlet { [Parameter(ParameterSetName = ParameterSetNames.ByFactoryName, Position = 2, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = Constants.HelpLinkedServiceName)] [Parameter(ParameterSetName = ParameterSetNames.ByFactoryObject, Position = 1, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = Constants.HelpLinkedServiceName)] [Alias(Constants.LinkedServiceName)] [ValidateNotNullOrEmpty] public override string Name { get; set; } public override void ExecuteCmdlet() { ByResourceId(); ByFactoryObject(); AdfEntityFilterOptions filterOptions = new AdfEntityFilterOptions() { Name = Name, ResourceGroupName = ResourceGroupName, DataFactoryName = DataFactoryName }; if (Name != null) { List<PSLinkedService> linkedServices = DataFactoryClient.FilterPSLinkedServices(filterOptions); if (linkedServices != null && linkedServices.Any()) { WriteObject(linkedServices[0]); } return; } // List all linked services until all pages are fetched. do { WriteObject(DataFactoryClient.FilterPSLinkedServices(filterOptions), true); } while (filterOptions.NextLink.IsNextPageLink()); } } }
43.712121
202
0.624263
[ "MIT" ]
3quanfeng/azure-powershell
src/DataFactory/DataFactoryV2/LinkedServices/GetAzureDataFactoryLinkedServiceCommand.cs
2,822
C#
using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading; namespace Disruptor.PerfTests.Support { public class ThreadAffinityUtil { [DllImport("kernel32.dll")] private static extern uint GetCurrentThreadId(); [DllImport("libc.so.6")] private static extern int sched_setaffinity(int pid, IntPtr cpusetsize, ref ulong cpuset); public static Scope SetThreadAffinity(int processorIndex) { Thread.BeginThreadAffinity(); var affinity = (1u << processorIndex); SetProcessorAffinity(affinity); return new Scope(); } private static void RemoveThreadAffinity() { var affinity = (1u << Environment.ProcessorCount) - 1; SetProcessorAffinity(affinity); Thread.EndThreadAffinity(); } private static void SetProcessorAffinity(uint mask) { #if NETFRAMEWORK SetProcessorAffinityWindows(mask); #else if (OperatingSystem.IsWindows()) SetProcessorAffinityWindows(mask); else if (OperatingSystem.IsLinux()) SetProcessorAffinityLinux(mask); else throw new PlatformNotSupportedException(); #endif } #if NETCOREAPP [SupportedOSPlatform("windows")] #endif private static void SetProcessorAffinityWindows(uint mask) { var processThread = GetCurrentProcessThread(); processThread.ProcessorAffinity = new IntPtr(mask); } #if NETCOREAPP [SupportedOSPlatform("linux")] private static void SetProcessorAffinityLinux(uint mask) { var cpuset = (ulong)mask; sched_setaffinity(0, new IntPtr(sizeof(ulong)), ref cpuset); } #endif private static ProcessThread GetCurrentProcessThread() { var threadId = GetCurrentThreadId(); foreach (ProcessThread processThread in Process.GetCurrentProcess().Threads) { if (processThread.Id == threadId) { return processThread; } } throw new InvalidOperationException($"Could not retrieve native thread with ID: {threadId}, current managed thread ID was {threadId}"); } public readonly ref struct Scope { public void Dispose() { RemoveThreadAffinity(); } } } }
28.406593
147
0.599226
[ "Apache-2.0" ]
arnoud67/Disruptor-net
src/Disruptor.PerfTests/Support/ThreadAffinityUtil.cs
2,585
C#
using System; using System.Xml.Linq; namespace PatientEducationAssembler { public class PatientEducationProvider { public XElement ProviderSpecification { get; protected set; } public string contentProviderName { get; set; } public string contentBundleName { get; set; } protected Uri contentProviderUrl { get; set; } protected Uri bundleUrl { get; set; } protected Uri sourceXML { get; } protected LoadDepth currentLoadDepth { get; set; } protected int loadCount { get; set; } public DateTime LastSpecificationUpdate { get; private set; } public string TitlePostfix { get; internal set; } public PatientEducationProvider(Uri sourceXMLFile) { sourceXML = sourceXMLFile; System.IO.FileInfo providerSpecifications = null; try { providerSpecifications = new System.IO.FileInfo(sourceXML.LocalPath); if (providerSpecifications.Exists) LastSpecificationUpdate = providerSpecifications.LastWriteTime; } catch (System.IO.FileNotFoundException) { } } public enum LoadDepth { Full, OneDocument, IndexOnly, TopLevel }; public string GetSpecification() { return ProviderSpecification.ToString(); } } }
31.954545
85
0.618777
[ "MIT" ]
hamishrodda/patient-education-assembler
Patient Education Assembler/PatientEducationProvider.cs
1,408
C#
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("SeudoBuild.Modules.UnityBuild.Shared")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
37.111111
82
0.745509
[ "MIT" ]
mstevenson/SeudoBuild
SeudoBuild.Modules/SeudoBuild.Modules.UnityBuild.Shared/Properties/AssemblyInfo.cs
1,004
C#
using Appy.Configuration.Serializers; using Appy.Infrastructure.OnePassword.Model; using Moq; namespace Appy.Infrastructure.OnePassword.Tests.Fixtures { public class JsonSerializerMock : Mock<IAppyJsonSerializer> { public JsonSerializerMock SetupAndReturns(OnePasswordNote note) { Setup(x => x.Deserialize<OnePasswordNote>( It.IsAny<string>())) .Returns(note); return this; } } }
28
71
0.647059
[ "MIT" ]
YellowLineParking/Appy.Configuration
src/Appy.Infrastructure.1Password.Tests/Fixtures/JsonSerializerMock.cs
476
C#
using Adnc.Infr.EventBus; namespace Adnc.Ord.Domain.Events { /// <summary> /// 订单支付事件 /// </summary> public sealed class OrderPaidEvent : BaseEvent<OrderPaidEvent.EventData> { public OrderPaidEvent(long id, EventData eventData, string eventSource) : base(id, eventData, eventSource) { } public class EventData { public long OrderId { get; set; } public long CustomerId { get; set; } public decimal Amount { get; set; } } } }
22
79
0.569091
[ "MIT" ]
wenfeifei/Adnc
src/ServerApi/Portal/Adnc.Ord/Adnc.Ord.Domain/Events/OrderPaidEvent.cs
564
C#
#if PROPERTIES using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace MvvmDialogs.ComShellDialogs { [ComImport] [Guid(ShellIIDGuid.IPropertyDescription)] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IPropertyDescription { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetPropertyKey(out PropertyKey pkey); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetCanonicalName([MarshalAs(UnmanagedType.LPWStr)] out string ppszName); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetPropertyType(out VarEnum pvartype); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), PreserveSig] HResult GetDisplayName(out IntPtr ppszName); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetEditInvitation(out IntPtr ppszInvite); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetTypeFlags([In] PropertyTypeOptions mask, out PropertyTypeOptions ppdtFlags); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetViewFlags(out PropertyViewOptions ppdvFlags); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetDefaultColumnWidth(out uint pcxChars); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetDisplayType(out PropertyDisplayType pdisplaytype); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetColumnState(out PropertyColumnStateOptions pcsFlags); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetGroupingRange(out PropertyGroupingRange pgr); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetRelativeDescriptionType(out RelativeDescriptionType prdt); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetRelativeDescription([In] PropVariant propvar1, [In] PropVariant propvar2, [MarshalAs(UnmanagedType.LPWStr)] out string ppszDesc1, [MarshalAs(UnmanagedType.LPWStr)] out string ppszDesc2); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetSortDescription(out PropertySortDescription psd); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetSortDescriptionLabel([In] bool fDescending, out IntPtr ppszDescription); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetAggregationType(out PropertyAggregationType paggtype); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetConditionType(out PropertyConditionType pcontype, out PropertyConditionOperation popDefault); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult GetEnumTypeList([In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IPropertyEnumTypeList ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void CoerceToCanonicalValue([In, Out] PropVariant propvar); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] // Note: this method signature may be wrong, but it is not used. HResult FormatForDisplay([In] PropVariant propvar, [In] ref PropertyDescriptionFormatOptions pdfFlags, [MarshalAs(UnmanagedType.LPWStr)] out string ppszDisplay); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] HResult IsValueCanonical([In] PropVariant propvar); } } #endif
61.554054
203
0.746652
[ "Apache-2.0" ]
FantasticFiasco/mvvm-dialogs-contrib
src/net/ComShellDialogs/Native/Properties/IPropertyDescription.cs
4,557
C#
namespace Facebook.Client.Controls { #if NETFX_CORE using System; using System.Globalization; using Windows.UI.Xaml.Data; #endif #if WP8 using System; using System.Globalization; using System.Windows.Data; #endif /// <summary> /// Checks if a value is null or empty. /// </summary> public class IsNullOrEmptyConverter : IValueConverter { #if NETFX_CORE /// <summary> /// Checks if a value is null or empty. /// </summary> /// <param name="value">The value that is produced by the binding target.</param> /// <param name="targetType">The type to convert to.</param> /// <param name="parameter">Set to True to indicate that the return value should be negated.</param> /// <param name="language">The culture to use in the converter (unused).</param> /// <returns>True if the value is null or empty.</returns> public object Convert(object value, Type targetType, object parameter, string language) #endif #if WP8 /// <summary> /// Scales the value by multiplying by a given factor. /// </summary> /// <param name="value">The value that is produced by the binding target.</param> /// <param name="targetType">The type to convert to.</param> /// <param name="parameter">The factor used to scale the value.</param> /// <param name="culture">The culture to use in the converter (unused).</param> /// <returns>A converted value.</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) #endif { bool isNegated; if (!bool.TryParse((string)parameter, out isNegated)) { throw new ArgumentException("Parameter for method Convert must be a boolean value."); } bool result; if (value is string) { result = string.IsNullOrEmpty((string)value); } else { result = value != null; } return isNegated ? !result : result; } #if NETFX_CORE /// <summary> /// Not implemented. /// </summary> public object ConvertBack(object value, Type targetType, object parameter, string language) #endif #if WP8 /// <summary> /// Not implemented. /// </summary> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) #endif { throw new System.NotImplementedException(); } } }
34.589744
109
0.575612
[ "Apache-2.0" ]
MavenRain/facebook-winclient-sdk
Source/Facebook.Client/Controls/Converters/IsNullOrEmptyConverter.cs
2,700
C#
private readonly static IDataSource dataSource = Container.Instance.Resolve<IDataSourceFactory>().Factory(Enum.DataSourceTypeEnum.SpawnlistDoor); IList<IDataSourceRow> dataSourceRows = dataSource.Select().Query(); for (int i = 0; i < dataSourceRows.Count; i++) { IDataSourceRow dataSourceRow = dataSourceRows[i]; } IDataSourceRow dataSourceRow = dataSource.NewRow(); dataSourceRow.Select() .Where(SpawnlistDoor.Column_id, obj.Id) .Execute(); IDataSourceRow dataSourceRow = dataSource.NewRow(); dataSourceRow.Insert() .Set(SpawnlistDoor.Column_id, obj.Id) .Set(SpawnlistDoor.Column_location, obj.Location) .Set(SpawnlistDoor.Column_gfxid, obj.Gfxid) .Set(SpawnlistDoor.Column_locx, obj.Locx) .Set(SpawnlistDoor.Column_locy, obj.Locy) .Set(SpawnlistDoor.Column_mapid, obj.Mapid) .Set(SpawnlistDoor.Column_hp, obj.Hp) .Set(SpawnlistDoor.Column_keeper, obj.Keeper) .Set(SpawnlistDoor.Column_isOpening, obj.IsOpening) .Execute(); IDataSourceRow dataSourceRow = dataSource.NewRow(); dataSourceRow.Update() .Where(SpawnlistDoor.Column_id, obj.Id) .Set(SpawnlistDoor.Column_location, obj.Location) .Set(SpawnlistDoor.Column_gfxid, obj.Gfxid) .Set(SpawnlistDoor.Column_locx, obj.Locx) .Set(SpawnlistDoor.Column_locy, obj.Locy) .Set(SpawnlistDoor.Column_mapid, obj.Mapid) .Set(SpawnlistDoor.Column_hp, obj.Hp) .Set(SpawnlistDoor.Column_keeper, obj.Keeper) .Set(SpawnlistDoor.Column_isOpening, obj.IsOpening) .Execute(); IDataSourceRow dataSourceRow = dataSource.NewRow(); dataSourceRow.Delete() .Where(SpawnlistDoor.Column_id, obj.Id) .Execute(); obj.Id = dataSourceRow.getString(SpawnlistDoor.Column_id); obj.Location = dataSourceRow.getString(SpawnlistDoor.Column_location); obj.Gfxid = dataSourceRow.getString(SpawnlistDoor.Column_gfxid); obj.Locx = dataSourceRow.getString(SpawnlistDoor.Column_locx); obj.Locy = dataSourceRow.getString(SpawnlistDoor.Column_locy); obj.Mapid = dataSourceRow.getString(SpawnlistDoor.Column_mapid); obj.Hp = dataSourceRow.getString(SpawnlistDoor.Column_hp); obj.Keeper = dataSourceRow.getString(SpawnlistDoor.Column_keeper); obj.IsOpening = dataSourceRow.getString(SpawnlistDoor.Column_isOpening);
36.827586
145
0.812734
[ "Unlicense" ]
TaiwanSpring/L1CSharpTW
TableTemp/SpawnlistDoor/CRUD.cs
2,136
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CocosSharp; namespace tests { public class LabelTTFFontsTestNew : AtlasDemoNew { private static readonly string[] fontList = { "fonts/A Damn Mess.ttf", "fonts/Abberancy.ttf", "fonts/Abduction.ttf", "fonts/American Typewriter.ttf", "fonts/Paint Boy.ttf", "fonts/Schwarzwald.ttf", "fonts/Scissor Cuts.ttf", }; public LabelTTFFontsTestNew() { } public override void OnEnter() { base.OnEnter(); var size = Layer.VisibleBoundsWorldspace.Size; var labelFormatCenter = CCLabelFormat.SystemFont; labelFormatCenter.Alignment = CCTextAlignment.Center; for (var i=0;i < fontList.Length; ++i) { var label = new CCLabel(fontList[i], fontList[i], 20, labelFormatCenter); if( label != null) { label.Position = size.Center; label.PositionY = ((size.Height * 0.6f) / fontList.Length * i) + (size.Height/5f); AddChild(label); } else { CCLog.Log ("ERROR: Cannot load: %s", fontList[i]); } } } public override string Title { get { return "New Label + TTF"; } } public override string Subtitle { get { return string.Empty; } } } }
24.408451
102
0.466821
[ "MIT" ]
YersonSolano/CocosSharp
tests/tests/classes/tests/LabelTestNew/LabelTTFFontsTestNew.cs
1,733
C#
namespace HoodedCrow.Quiz { using HoodedCrow.Core; using UnityEngine; [CreateAssetMenu(menuName = "Example/Quiz/Messages/Player Answered")] public class PlayerAnsweredMessage: AMessage<PlayerAnsweredMessageContent> { } }
22.363636
78
0.739837
[ "BSD-3-Clause" ]
Huginn18/Unity-Example-Project
Assets/Scripts/Quiz/Messages/Player Answered/PlayerAnsweredMessage.cs
246
C#
using AutoMapper; using FluentAssertions; using Moq; using Opdex.Platform.Common.Exceptions; using Opdex.Platform.Common.Models; using Opdex.Platform.Infrastructure.Abstractions.Data; using Opdex.Platform.Infrastructure.Abstractions.Data.Models; using Opdex.Platform.Infrastructure.Abstractions.Data.Queries.Deployers; using Opdex.Platform.Infrastructure.Data.Handlers.Deployers; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Opdex.Platform.Infrastructure.Tests.Data.Handlers.Deployers; public class SelectActiveDeployerQueryHandlerTests { private readonly Mock<IDbContext> _dbContext; private readonly SelectActiveDeployerQueryHandler _handler; public SelectActiveDeployerQueryHandlerTests() { var mapper = new MapperConfiguration(config => config.AddProfile(new PlatformInfrastructureMapperProfile())).CreateMapper(); _dbContext = new Mock<IDbContext>(); _handler = new SelectActiveDeployerQueryHandler(_dbContext.Object, mapper); } [Fact] public async Task Handle_Query_Limit1() { // Arrange var query = new SelectActiveDeployerQuery(); // Act await _handler.Handle(query, CancellationToken.None); // Assert _dbContext.Verify(callTo => callTo.ExecuteFindAsync<It.IsAnyType>( It.Is<DatabaseQuery>(q => q.Sql.EndsWith("LIMIT 1;"))), Times.Once); } [Fact] public async Task SelectActiveDeployer_Success() { // Arrange var deployer = new DeployerEntity { Id = 5, Address = new Address("PUv5zxmYE3wKkCgnnF31wo4VC7UNAVzXzH"), PendingOwner = Address.Empty, Owner = new Address("PX4x5WcA7MAPpHnYJoBEXD47TNMBxH9SvD"), IsActive = true, CreatedBlock = 5000, ModifiedBlock = 5000 }; _dbContext.Setup(db => db.ExecuteFindAsync<DeployerEntity>(It.IsAny<DatabaseQuery>())) .ReturnsAsync(deployer); // Act var result = await _handler.Handle(new SelectActiveDeployerQuery(), CancellationToken.None); // Assert _dbContext.Verify(callTo => callTo.ExecuteFindAsync<DeployerEntity>(It.IsAny<DatabaseQuery>()), Times.Once); result.Id.Should().Be(deployer.Id); result.Address.Should().Be(deployer.Address); result.PendingOwner.Should().Be(deployer.PendingOwner); result.Owner.Should().Be(deployer.Owner); result.IsActive.Should().Be(deployer.IsActive); result.CreatedBlock.Should().Be(deployer.CreatedBlock); result.ModifiedBlock.Should().Be(deployer.ModifiedBlock); } [Fact] public async Task SelectActiveDeployer_NotFound_DoesNotThrowNotFoundException() { // Arrange var command = new SelectActiveDeployerQuery(); _dbContext.Setup(db => db.ExecuteFindAsync<DeployerEntity>(It.IsAny<DatabaseQuery>())) .ReturnsAsync((DeployerEntity)null); // Act // Assert await _handler.Invoking(h => h.Handle(command, CancellationToken.None)) .Should() .NotThrowAsync<NotFoundException>(); } [Fact] public async Task SelectActiveDeployer_ReturnsNull() { // Arrange var command = new SelectActiveDeployerQuery(); _dbContext.Setup(db => db.ExecuteFindAsync<DeployerEntity>(It.IsAny<DatabaseQuery>())) .ReturnsAsync((DeployerEntity)null); // Act var result = await _handler.Handle(command, CancellationToken.None); // Assert _dbContext.Verify(callTo => callTo.ExecuteFindAsync<DeployerEntity>(It.IsAny<DatabaseQuery>()), Times.Once); result.Should().BeNull(); } }
34.518519
132
0.680258
[ "MIT" ]
Opdex/opdex-v1-api
test/Opdex.Platform.Infrastructure.Tests/Data/Handlers/Deployers/SelectActiveDeployerQueryHandlerTests.cs
3,728
C#
using Content.Server.GameObjects.Components.Chemistry; using Content.Server.GameObjects.Components.Fluids; using Content.Server.GameObjects.EntitySystems.Click; using Content.Server.Interfaces.GameObjects.Components.Interaction; using Content.Shared.Audio; using Content.Shared.Chemistry; using Content.Shared.GameObjects.Components.Nutrition; using Content.Shared.GameObjects.EntitySystems; using Content.Shared.Interfaces; using Content.Shared.Interfaces.GameObjects.Components; using Robust.Server.GameObjects; using Robust.Server.GameObjects.EntitySystems; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.GameObjects.Systems; using Robust.Shared.Interfaces.GameObjects; using Robust.Shared.Interfaces.Random; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Prototypes; using Robust.Shared.Random; using Robust.Shared.Serialization; using Robust.Shared.Utility; using Robust.Shared.ViewVariables; namespace Content.Server.GameObjects.Components.Nutrition { [RegisterComponent] [ComponentReference(typeof(IAfterInteract))] public class DrinkComponent : Component, IUse, IAfterInteract, ISolutionChange, IExamine, ILand { #pragma warning disable 649 [Dependency] private readonly IPrototypeManager _prototypeManager; [Dependency] private readonly IRobustRandom _random; #pragma warning restore 649 public override string Name => "Drink"; [ViewVariables] private SolutionComponent _contents; [ViewVariables] private string _useSound; [ViewVariables] private bool _defaultToOpened; [ViewVariables] public ReagentUnit TransferAmount { get; private set; } = ReagentUnit.New(2); [ViewVariables] protected bool Opened { get; set; } [ViewVariables] public bool Empty => _contents.CurrentVolume.Float() <= 0; private AppearanceComponent _appearanceComponent; private string _soundCollection; private bool _pressurized; private string _burstSound; public override void ExposeData(ObjectSerializer serializer) { base.ExposeData(serializer); serializer.DataField(ref _useSound, "useSound", "/Audio/Items/drink.ogg"); serializer.DataField(ref _defaultToOpened, "isOpen", false); //For things like cups of coffee. serializer.DataField(ref _soundCollection, "openSounds","canOpenSounds"); serializer.DataField(ref _pressurized, "pressurized",false); serializer.DataField(ref _burstSound, "burstSound", "/Audio/Effects/flash_bang.ogg"); } public override void Initialize() { base.Initialize(); Owner.TryGetComponent(out _appearanceComponent); if(!Owner.TryGetComponent(out _contents)) { _contents = Owner.AddComponent<SolutionComponent>(); } _contents.Capabilities = SolutionCaps.PourIn | SolutionCaps.PourOut | SolutionCaps.Injectable; Opened = _defaultToOpened; UpdateAppearance(); } void ISolutionChange.SolutionChanged(SolutionChangeEventArgs eventArgs) { UpdateAppearance(); } private void UpdateAppearance() { _appearanceComponent?.SetData(SharedFoodComponent.FoodVisuals.Visual, _contents.CurrentVolume.Float()); } bool IUse.UseEntity(UseEntityEventArgs args) { if (!Opened) { //Do the opening stuff like playing the sounds. var soundCollection = _prototypeManager.Index<SoundCollectionPrototype>(_soundCollection); var file = _random.Pick(soundCollection.PickFiles); EntitySystem.Get<AudioSystem>().PlayFromEntity(file, args.User, AudioParams.Default); Opened = true; return false; } return TryUseDrink(args.User); } //Force feeding a drink to someone. void IAfterInteract.AfterInteract(AfterInteractEventArgs eventArgs) { TryUseDrink(eventArgs.Target); } public void Examine(FormattedMessage message, bool inDetailsRange) { if (!Opened || !inDetailsRange) { return; } var color = Empty ? "gray" : "yellow"; var openedText = Loc.GetString(Empty ? "Empty" : "Opened"); message.AddMarkup(Loc.GetString("[color={0}]{1}[/color]", color, openedText)); } private bool TryUseDrink(IEntity target) { if (target == null) { return false; } if (!Opened) { target.PopupMessage(target, Loc.GetString("Open it first!")); return false; } if (_contents.CurrentVolume.Float() <= 0) { target.PopupMessage(target, Loc.GetString("It's empty!")); return false; } if (!target.TryGetComponent(out StomachComponent stomachComponent)) { return false; } var transferAmount = ReagentUnit.Min(TransferAmount, _contents.CurrentVolume); var split = _contents.SplitSolution(transferAmount); if (stomachComponent.TryTransferSolution(split)) { if (_useSound == null) return false; EntitySystem.Get<AudioSystem>().PlayFromEntity(_useSound, target, AudioParams.Default.WithVolume(-2f)); target.PopupMessage(target, Loc.GetString("Slurp")); UpdateAppearance(); return true; } //Stomach was full or can't handle whatever solution we have. _contents.TryAddSolution(split); target.PopupMessage(target, Loc.GetString("You've had enough {0}!", Owner.Name)); return false; } void ILand.Land(LandEventArgs eventArgs) { if (_pressurized && !Opened && _random.Prob(0.25f) && Owner.TryGetComponent(out SolutionComponent component)) { Opened = true; var solution = component.SplitSolution(component.CurrentVolume); SpillHelper.SpillAt(Owner, solution, "PuddleSmear"); EntitySystem.Get<AudioSystem>().PlayFromEntity(_burstSound, Owner, AudioParams.Default.WithVolume(-4)); } } } }
36.581522
119
0.620413
[ "MIT" ]
Hughgent/space-station-14
Content.Server/GameObjects/Components/Nutrition/DrinkComponent.cs
6,733
C#
using XamarinFormsSample.WinPhone.Resources; namespace XamarinFormsSample.WinPhone { /// <summary> /// Provides access to string resources. /// </summary> public class LocalizedStrings { private static AppResources _localizedResources = new AppResources(); public AppResources LocalizedResources { get { return _localizedResources; } } } }
25.533333
86
0.704961
[ "Apache-2.0" ]
Alshaikh-Abdalrahman/jedoo
GettingStarted/XamarinFormsSample/XamarinFormsSample/XamarinFormsSample.WinPhone/LocalizedStrings.cs
385
C#
using BL.Tienda; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Win.Tienda { public partial class FormModelo : Form { ModeloBL _modelos; CategoriasBL _categorias; TiposBL _tiposBL; public FormModelo() { InitializeComponent(); _modelos = new ModeloBL(); listaModelosBindingSource.DataSource = _modelos.ObtenerModelos(); _categorias = new CategoriasBL(); listaCategoriasBindingSource.DataSource = _categorias.ObtenerCategorias(); _tiposBL = new TiposBL(); listaTiposBindingSource.DataSource = _tiposBL.ObtenerTipos(); } private void listaModelosBindingNavigatorSaveItem_Click(object sender, EventArgs e) { listaModelosBindingSource.EndEdit(); var modelo = (Modelo)listaModelosBindingSource.Current; if (fotoPictureBox.Image != null) { modelo.Foto = Program.imageToByteArray(fotoPictureBox.Image); } else { modelo.Foto = null; } var resultado = _modelos.GuardarModelo(modelo); if (resultado.Exitoso == true) { listaModelosBindingSource.ResetBindings(false); DeshabilitarHabilitarBotones(true); MessageBox.Show("Producto Guardado"); } else { MessageBox.Show(resultado.Mensaje); } } private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e) { _modelos.AgregarModelo(); listaModelosBindingSource.MoveLast(); DeshabilitarHabilitarBotones(false); } private void DeshabilitarHabilitarBotones(bool valor) { bindingNavigatorMoveFirstItem.Enabled = valor; bindingNavigatorMoveLastItem.Enabled = valor; bindingNavigatorMovePreviousItem.Enabled = valor; bindingNavigatorMoveNextItem.Enabled = valor; bindingNavigatorPositionItem.Enabled = valor; bindingNavigatorAddNewItem.Enabled = valor; bindingNavigatorDeleteItem.Enabled = valor; toolStripButtonCancelar.Visible = !valor; } private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e) { if (idTextBox.Text != "") { var resultado = MessageBox.Show("Desea eliminar este registro?", "Eliminar", MessageBoxButtons.YesNo); if (resultado == DialogResult.Yes) { var id = Convert.ToInt32(idTextBox.Text); Eliminar(id); } } } private void Eliminar(int id) { var resultado = _modelos.EliminarModelo(id); if (resultado == true) { listaModelosBindingSource.ResetBindings(false); } else { MessageBox.Show("Ocurrio un error al eliminar el modelo"); } } private void toolStripButtonCancelar_Click(object sender, EventArgs e) { _modelos.CancelarCambios(); DeshabilitarHabilitarBotones(true); } private void idTextBox_TextChanged(object sender, EventArgs e) { } private void idTextBox_TextChanged_1(object sender, EventArgs e) { } private void idLabel_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { var modelo = (Modelo)listaModelosBindingSource.Current; if (modelo != null) { openFileDialog1.ShowDialog(); var archivo = openFileDialog1.FileName; if (archivo != "") { var fileInfo = new FileInfo(archivo); var fileStream = fileInfo.OpenRead(); fotoPictureBox.Image = Image.FromStream(fileStream); } } else { MessageBox.Show("Cree un producto antes de asignarle una imagen"); } } private void button2_Click(object sender, EventArgs e) { fotoPictureBox.Image = null; } private void button3_Click(object sender, EventArgs e) { string buscar = textBox1.Text; if (buscar == "") { listaModelosBindingSource.DataSource = _modelos.ObtenerModelos(); } else { listaModelosBindingSource.DataSource = _modelos.ObtenerModelos(buscar); } listaModelosBindingSource.ResetBindings(false); } } }
28.79558
118
0.548734
[ "MIT" ]
elvinpalma/Ventas
Tienda/Win.Tienda/FormModelo.cs
5,214
C#
using System; using System.Net; using System.Threading.Tasks; using BDFramework.UFlux.Contains; using BDFramework.UFlux.Reducer; using LitJson; namespace BDFramework.UFlux.Test { /// <summary> /// 这里是逻辑状态, /// 比如服务器返回,客户端计算状态数据 /// </summary> public class S_HeroDataDemo6Test : StateBase { public string Name; public int Hp; public int MaxHp; } /// <summary> /// Reducer 函数处理的集合 /// </summary> public class Reducer_Demo06Test : AReducers<S_HeroDataDemo6Test> { public enum Reducer06 { //同步请求 RequestHeroDataSynchronization, //异步请求 RequestHeroDataAsync, //回调请求 RequestHeroCallback, } /// <summary> /// 注册所有的Recucer /// </summary> public override void RegisterReducers() { base.RegisterReducers(); //这里用显式注册,避免函数签名错误 //同步方法 this.AddRecucer(Reducer06.RequestHeroDataSynchronization, RequestServer); //异步方法 this.AddAsyncRecucer(Reducer06.RequestHeroDataAsync, RequestServerByAsync); //回调需要考虑乱序问题 this.AddCallbackReducer(Reducer06.RequestHeroCallback, RequestServerByCallback); } /// <summary> /// url /// </summary> readonly public string url = "https://1843236967254885.cn-shanghai.fc.aliyuncs.com/2016-08-15/proxy/BDFramework/DemoForUFlux/"; /// <summary> /// 同步网络请求 /// </summary> /// <param name="old"></param> /// <param name="param"></param> /// <returns></returns> private S_HeroDataDemo6Test RequestServer(S_HeroDataDemo6Test old, object @param) { var api = url + "api/bdframework/getherodata"; WebClient wc=new WebClient(); string ret = wc.DownloadString(api); var hero = JsonMapper.ToObject<S_HeroDataDemo6Test>(ret); hero.Hp -= 5; hero.Name += 2; hero.MaxHp += 10; return hero; } /// <summary> /// 异步网络请求 /// </summary> /// <param name="old"></param> /// <param name="param"></param> /// <returns></returns> async private Task<S_HeroDataDemo6Test>RequestServerByAsync(S_HeroDataDemo6Test old, object @param) { var api = url + "api/bdframework/getherodata"; WebClient wc=new WebClient(); string ret = await wc.DownloadStringTaskAsync(api); var hero = JsonMapper.ToObject<S_HeroDataDemo6Test>(ret); hero.Hp -= 5; hero.Name += 2; hero.MaxHp += 10; return hero; } /// <summary> /// 网络请求回调 /// </summary> /// <param name="old"></param> /// <param name="param"></param> /// <returns></returns> private void RequestServerByCallback (Store<S_HeroDataDemo6Test>.GetState getStateFunc, object @params = null, Action<S_HeroDataDemo6Test> callback = null) { var api = url + "api/bdframework/getherodata"; WebClient wc=new WebClient(); //提前注册回调 wc.DownloadStringCompleted += (sender,download) => { var hero = JsonMapper.ToObject<S_HeroDataDemo6Test>(download.Result); hero.Hp -= 5; hero.Name += 2; hero.MaxHp += 10; callback?.Invoke(hero); }; //开始异步下载 wc.DownloadStringAsync(new Uri(api)); } } }
31.487179
163
0.538545
[ "Apache-2.0" ]
AzureZheng/BDFramework.Core
Assets/Code/Game@hotfix/demo6_UFlux/06.Window_Reducer/Reducer_Demo06Test.cs
3,912
C#
using System; using System.ComponentModel.DataAnnotations.Schema; namespace IZCommerce.Core.Models { public class Order { public int OrderId { get; set; } public string OrderNumber { get; set; } public DateTime OrderDate { get; set; } public DateTime dateTime { get; set; } public DateTime RequiredDate { get; set; } public string Freight { get; set; } public double SalesTax { get; set; } public DateTime Timestamp { get; set; } public int TransacStatus { get; set; } public string Errlog { get; set; } public string ErrMsg { get; set; } public string FullFilled { get; set; } public bool Deleted { get; set; } public double Paid { get; set; } public DateTime PaymentDate { get; set; } [ForeignKey(nameof(Customer))] public int CustomerId { get; set; } public Customer Customer { get; set; } [ForeignKey(nameof(Payment))] public int PaymentId { get; set; } public Payment Payment { get; set; } [ForeignKey(nameof(Shipper))] public int ShipperId { get; set; } public Shipper Shipper { get; set; } } }
23.557692
51
0.591837
[ "MIT" ]
timnguyen90/IZCommerce
Src/IZCommerce/IZCommerce.Core/Models/Order.cs
1,227
C#
// Colorado (c) 2015 Baltasar MIT License <baltasarq@gmail.com> namespace ColoradoTests { using NUnit.Framework; using System; using Colorado.Core; [TestFixture] public class TestDecimalMark { [Test] public void TestDecimalSeparator() { for (int i = 0; i < DecimalMark.DecimalSeparatorChar.Count; ++i) { Assert.AreEqual( DecimalMark.DecimalSeparatorChar[ i ], DecimalMark.AsChar( (DecimalMark.DecimalSeparator) i ) ); } } [Test] public void TestIsDecimalMark() { Assert.AreEqual( false, DecimalMark.IsDecimalMark( 'a' ) ); Assert.AreEqual( true, DecimalMark.IsDecimalMark( '.' ) ); Assert.AreEqual( true, DecimalMark.IsDecimalMark( ',' ) ); } [Test] public void TestWhichDecimalMark() { Assert.AreEqual( DecimalMark.DecimalSeparator.Point, DecimalMark.WhichDecimalMark( "4" ) ); Assert.AreEqual( DecimalMark.DecimalSeparator.Point, DecimalMark.WhichDecimalMark( "4.5" ) ); Assert.AreEqual( DecimalMark.DecimalSeparator.Comma, DecimalMark.WhichDecimalMark( "4,5" ) ); Assert.AreEqual( 0, DecimalMark.WhichDecimalMark( '.' ) ); Assert.AreEqual( 1, DecimalMark.WhichDecimalMark( ',' ) ); Assert.AreEqual( -1, DecimalMark.WhichDecimalMark( 'a' ) ); } [Test] public void TestIsNumber() { string[] testNumbers = { "", " ", ".0", "-.1", "-.", "0.4e-5", "5.4", "0", "+", "+.0", "0,6e-6", "5,6", "hello4", "4d", "3", "0.4e5", "0,1E45", "0,0001", ",1", "1,", "1.", }; bool[] testResults = { false, false, true, true, false, true, true, true, false, true, true, true, false, false, true, true, true, true, true, true, true, }; for(int i = 0; i < testResults.Length; ++i) { bool result = DecimalMark.IsNumber( testNumbers[ i ] ); Assert.AreEqual( testResults[ i ], result ); } } [Test] public void TestIsRealNumber() { string[] testNumbers = { "", " ", ".0", "4e+5", "-.", "4", "5.4", "0", "+", "+.0", "0,6e-6", "5,6", "hello4", "4d", "0,", "0.4e5", "0,1E45", "0,0001", }; bool[] testResults = { false, false, true, false, false, false, true, false, false, true, true, true, false, false, true, true, true, true, }; for(int i = 0; i < testResults.Length; ++i) { bool result = DecimalMark.IsRealNumber( testNumbers[ i ] ); Console.WriteLine( "[\"{0}\"] -> {1} == {2}?", testNumbers[ i ], testResults[ i ], result ); Assert.AreEqual( testResults[ i ], result ); } } } }
25.158416
96
0.587564
[ "MIT" ]
Baltasarq/Colorado
ColoradoTests/TestDecimalMark.cs
2,543
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; namespace PdfiumViewer.Demo { public partial class MainForm : Form { private SearchForm _searchForm; public MainForm() { InitializeComponent(); renderToBitmapsToolStripMenuItem.Enabled = false; pdfViewer1.Renderer.DisplayRectangleChanged += Renderer_DisplayRectangleChanged; pdfViewer1.Renderer.ZoomChanged += Renderer_ZoomChanged; pdfViewer1.Renderer.MouseMove += Renderer_MouseMove; pdfViewer1.Renderer.MouseLeave += Renderer_MouseLeave; ShowPdfLocation(PdfPoint.Empty); cutMarginsWhenPrintingToolStripMenuItem.PerformClick(); _zoom.Text = pdfViewer1.Renderer.Zoom.ToString(); Disposed += (s, e) => pdfViewer1.Document?.Dispose(); } private void Renderer_MouseLeave(object sender, EventArgs e) { ShowPdfLocation(PdfPoint.Empty); } private void Renderer_MouseMove(object sender, MouseEventArgs e) { ShowPdfLocation(pdfViewer1.Renderer.PointToPdf(e.Location)); } private void ShowPdfLocation(PdfPoint point) { if (!point.IsValid) { _pageToolStripLabel.Text = null; _coordinatesToolStripLabel.Text = null; } else { _pageToolStripLabel.Text = (point.Page + 1).ToString(); _coordinatesToolStripLabel.Text = point.Location.X + "," + point.Location.Y; } } void Renderer_ZoomChanged(object sender, EventArgs e) { _zoom.Text = pdfViewer1.Renderer.Zoom.ToString(); } void Renderer_DisplayRectangleChanged(object sender, EventArgs e) { _page.Text = (pdfViewer1.Renderer.Page + 1).ToString(); } private void MainForm_Shown(object sender, EventArgs e) { var args = Environment.GetCommandLineArgs(); if (args.Length > 1) { pdfViewer1.Document?.Dispose(); pdfViewer1.Document = OpenDocument(args[1]); renderToBitmapsToolStripMenuItem.Enabled = true; } else { OpenFile(); } _showBookmarks.Checked = pdfViewer1.ShowBookmarks; _showToolbar.Checked = pdfViewer1.ShowToolbar; } private PdfDocument OpenDocument(string fileName) { try { return PdfDocument.Load(this, fileName); } catch (Exception ex) { MessageBox.Show(this, ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return null; } } private void OpenFile() { using (var form = new OpenFileDialog()) { form.Filter = "PDF Files (*.pdf)|*.pdf|All Files (*.*)|*.*"; form.RestoreDirectory = true; form.Title = "Open PDF File"; if (form.ShowDialog(this) != DialogResult.OK) { Dispose(); return; } pdfViewer1.Document?.Dispose(); pdfViewer1.Document = OpenDocument(form.FileName); renderToBitmapsToolStripMenuItem.Enabled = true; } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Close(); } private void openToolStripMenuItem_Click(object sender, EventArgs e) { OpenFile(); } private void renderToBitmapsToolStripMenuItem_Click(object sender, EventArgs e) { int dpiX; int dpiY; using (var form = new ExportBitmapsForm()) { if (form.ShowDialog() != DialogResult.OK) return; dpiX = form.DpiX; dpiY = form.DpiY; } string path; using (var form = new FolderBrowserDialog()) { if (form.ShowDialog(this) != DialogResult.OK) return; path = form.SelectedPath; } var document = pdfViewer1.Document; for (int i = 0; i < document.PageCount; i++) { using (var image = document.Render(i, (int)document.PageSizes[i].Width, (int)document.PageSizes[i].Height, dpiX, dpiY, false)) { image.Save(Path.Combine(path, "Page " + i + ".png")); } } } private void toolStripButton1_Click_1(object sender, EventArgs e) { pdfViewer1.Renderer.Page--; } private void toolStripButton2_Click(object sender, EventArgs e) { pdfViewer1.Renderer.Page++; } private void cutMarginsWhenPrintingToolStripMenuItem_Click(object sender, EventArgs e) { cutMarginsWhenPrintingToolStripMenuItem.Checked = true; shrinkToMarginsWhenPrintingToolStripMenuItem.Checked = false; pdfViewer1.DefaultPrintMode = PdfPrintMode.CutMargin; } private void shrinkToMarginsWhenPrintingToolStripMenuItem_Click(object sender, EventArgs e) { shrinkToMarginsWhenPrintingToolStripMenuItem.Checked = true; cutMarginsWhenPrintingToolStripMenuItem.Checked = false; pdfViewer1.DefaultPrintMode = PdfPrintMode.ShrinkToMargin; } private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e) { using (var form = new PrintPreviewDialog()) { form.Document = pdfViewer1.Document.CreatePrintDocument(pdfViewer1.DefaultPrintMode); form.ShowDialog(this); } } private void _fitWidth_Click(object sender, EventArgs e) { FitPage(PdfViewerZoomMode.FitWidth); } private void FitPage(PdfViewerZoomMode zoomMode) { int page = pdfViewer1.Renderer.Page; pdfViewer1.ZoomMode = zoomMode; pdfViewer1.Renderer.Zoom = 1; pdfViewer1.Renderer.Page = page; } private void _fitHeight_Click(object sender, EventArgs e) { FitPage(PdfViewerZoomMode.FitHeight); } private void _fitBest_Click(object sender, EventArgs e) { FitPage(PdfViewerZoomMode.FitBest); } private void _page_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { e.Handled = true; int page; if (int.TryParse(_page.Text, out page)) pdfViewer1.Renderer.Page = page - 1; } } private void _zoom_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { e.Handled = true; float zoom; if (float.TryParse(_zoom.Text, out zoom)) pdfViewer1.Renderer.Zoom = zoom; } } private void toolStripButton4_Click(object sender, EventArgs e) { pdfViewer1.Renderer.ZoomIn(); } private void toolStripButton3_Click(object sender, EventArgs e) { pdfViewer1.Renderer.ZoomOut(); } private void _rotateLeft_Click(object sender, EventArgs e) { pdfViewer1.Renderer.RotateLeft(); } private void _rotateRight_Click(object sender, EventArgs e) { pdfViewer1.Renderer.RotateRight(); } private void _hideToolbar_Click(object sender, EventArgs e) { pdfViewer1.ShowToolbar = _showToolbar.Checked; } private void _hideBookmarks_Click(object sender, EventArgs e) { pdfViewer1.ShowBookmarks = _showBookmarks.Checked; } private void deleteCurrentPageToolStripMenuItem_Click(object sender, EventArgs e) { // PdfRenderer does not support changes to the loaded document, // so we fake it by reloading the document into the renderer. int page = pdfViewer1.Renderer.Page; var document = pdfViewer1.Document; pdfViewer1.Document = null; document.DeletePage(page); pdfViewer1.Document = document; pdfViewer1.Renderer.Page = page; } private void rotate0ToolStripMenuItem_Click(object sender, EventArgs e) { Rotate(PdfRotation.Rotate0); } private void rotate90ToolStripMenuItem_Click(object sender, EventArgs e) { Rotate(PdfRotation.Rotate90); } private void rotate180ToolStripMenuItem_Click(object sender, EventArgs e) { Rotate(PdfRotation.Rotate180); } private void rotate270ToolStripMenuItem_Click(object sender, EventArgs e) { Rotate(PdfRotation.Rotate270); } private void Rotate(PdfRotation rotate) { // PdfRenderer does not support changes to the loaded document, // so we fake it by reloading the document into the renderer. int page = pdfViewer1.Renderer.Page; var document = pdfViewer1.Document; pdfViewer1.Document = null; document.RotatePage(page, rotate); pdfViewer1.Document = document; pdfViewer1.Renderer.Page = page; } private void showRangeOfPagesToolStripMenuItem_Click(object sender, EventArgs e) { using (var form = new PageRangeForm(pdfViewer1.Document)) { if (form.ShowDialog(this) == DialogResult.OK) { pdfViewer1.Document = form.Document; } } } private void informationToolStripMenuItem_Click(object sender, EventArgs e) { PdfInformation info = pdfViewer1.Document.GetInformation(); StringBuilder sz = new StringBuilder(); sz.AppendLine($"Author: {info.Author}"); sz.AppendLine($"Creator: {info.Creator}"); sz.AppendLine($"Keywords: {info.Keywords}"); sz.AppendLine($"Producer: {info.Producer}"); sz.AppendLine($"Subject: {info.Subject}"); sz.AppendLine($"Title: {info.Title}"); sz.AppendLine($"Create Date: {info.CreationDate}"); sz.AppendLine($"Modified Date: {info.ModificationDate}"); MessageBox.Show(sz.ToString(), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void _getTextFromPage_Click(object sender, EventArgs e) { int page = pdfViewer1.Renderer.Page; string text = pdfViewer1.Document.GetPdfText(page); string caption = string.Format("Page {0} contains {1} character(s):", page + 1, text.Length); if (text.Length > 128) text = text.Substring(0, 125) + "...\n\n\n\n..." + text.Substring(text.Length - 125); MessageBox.Show(this, text, caption, MessageBoxButtons.OK, MessageBoxIcon.Information); } private void findToolStripMenuItem_Click(object sender, EventArgs e) { if (_searchForm == null) { _searchForm = new SearchForm(pdfViewer1.Renderer); _searchForm.Disposed += (s, ea) => _searchForm = null; _searchForm.Show(this); } _searchForm.Focus(); } private void printMultiplePagesToolStripMenuItem_Click(object sender, EventArgs e) { using (var form = new PrintMultiplePagesForm(pdfViewer1)) { form.ShowDialog(this); } } } }
31.963446
142
0.565022
[ "Apache-2.0" ]
Erapchu/MyPdfiumViewer
PdfiumViewer.Demo/MainForm.cs
12,244
C#
namespace Macabre2D.Wpf.Common.Controls { using MahApps.Metro.IconPacks; using System.Windows; using System.Windows.Controls; public partial class IconToggleButton : UserControl { public static readonly DependencyProperty IsNotToggledKindProperty = DependencyProperty.Register( nameof(IsNotToggledKind), typeof(PackIconMaterialKind), typeof(IconToggleButton), new PropertyMetadata()); public static readonly DependencyProperty IsToggledKindProperty = DependencyProperty.Register( nameof(IsToggledKind), typeof(PackIconMaterialKind), typeof(IconToggleButton), new PropertyMetadata()); public static readonly DependencyProperty IsToggledProperty = DependencyProperty.Register( nameof(IsToggled), typeof(bool), typeof(IconToggleButton), new PropertyMetadata(false)); public IconToggleButton() { this.InitializeComponent(); } public PackIconMaterialKind IsNotToggledKind { get { return (PackIconMaterialKind)this.GetValue(IsNotToggledKindProperty); } set { this.SetValue(IsNotToggledKindProperty, value); } } public bool IsToggled { get { return (bool)this.GetValue(IsToggledProperty); } set { this.SetValue(IsToggledProperty, value); } } public PackIconMaterialKind IsToggledKind { get { return (PackIconMaterialKind)this.GetValue(IsToggledKindProperty); } set { this.SetValue(IsToggledKindProperty, value); } } } }
36.043478
105
0.655006
[ "MIT" ]
BrettStory/CosmicJam
Wpf/Common/Controls/IconToggleButton.xaml.cs
1,660
C#
using RestWithASPNETUdemy.Data.Converter.Contract; using RestWithASPNETUdemy.Data.VO; using RestWithASPNETUdemy.Model; using System; using System.Collections.Generic; using System.Linq; namespace RestWithASPNETUdemy.Data.Converter.Implementations { public class BookConverter : IParser<BookVO, Book>, IParser<Book, BookVO> { public Book Parse(BookVO origin) { if (origin == null) return null; return new Book { Id = origin.Id, Author = origin.Author, LaunchDate = origin.LaunchDate, Price = origin.Price, Title = origin.Title }; } public BookVO Parse(Book origin) { if (origin == null) return null; return new BookVO { Id = origin.Id, Author = origin.Author, LaunchDate = origin.LaunchDate, Price = origin.Price, Title = origin.Title }; } public List<Book> Parse(List<BookVO> origin) { if (origin == null) return null; return origin.Select(item => Parse(item)).ToList(); } public List<BookVO> Parse(List<Book> origin) { if (origin == null) return null; return origin.Select(item => Parse(item)).ToList(); } } }
27.480769
77
0.531141
[ "Apache-2.0" ]
Henry-Roberto/RestWithASP.NET5Udemy
03_RestWithASPNETUdemy_Connection_With_DB/RestWithASPNETUdemy/RestWithASPNETUdemy/Data/Converter/Implementations/BookConverter.cs
1,431
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WarehouseMgr.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("WarehouseMgr.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.625
178
0.60338
[ "MIT" ]
mogliang/Generic-WPF-Form-Controls
src/WarehouseMgr/Properties/Resources.Designer.cs
2,783
C#