content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Diagnostics; using System.IO; using System.Text; using Mdmeta.Core; using static Mdmeta.Tasks.Walterlv.MdmetaUtils; namespace Mdmeta.Tasks.Walterlv { [CommandMetadata("wupdate", Description = "根据文件的修改时间更新 YAML 元数据中的更新时间。")] public sealed class UpdateTask : CommandTask { [CommandArgument("[folder]", Description = "要初始化 md 文件属性的文件夹。(如果不指定,则会自动查找。)")] public string FolderName { get; set; } [CommandOption("-t|--ignore-in-hour", Description = "当修改时间与发布时间间隔在指定的小时数以内时,只更新发布时间。")] public string IgnoreInHour { get; set; } public override int Run() { try { var folderName = FindPostFolder(FolderName); var folder = new DirectoryInfo(Path.GetFullPath(folderName)); var count = 0; Console.WriteLine("更新文件的时间元数据:"); var watch = new Stopwatch(); watch.Start(); foreach (var file in folder.EnumerateFiles("*.md", SearchOption.AllDirectories)) { var updated = UpdateFile(file); count += updated ? 1 : 0; } watch.Stop(); if (count > 0) { Console.Write($"耗时:{watch.Elapsed},"); OutputOn($"总计更新 {count} 个。", ConsoleColor.Green); } else { Console.WriteLine("没有文件需要更新。"); } return 0; } catch (Exception ex) { OutputError(ex.Message); return 1; } } private bool UpdateFile(FileInfo file) { var frontMatter = PostMeta.FromFile(file); if (frontMatter == null) return false; var dateString = frontMatter.Date; if (!string.IsNullOrWhiteSpace(dateString)) { var date = DateTimeOffset.Parse(dateString); var writeTime = file.LastWriteTimeUtc.ToUniversalTime(); var roundWriteTime = new DateTimeOffset( writeTime.Year, writeTime.Month, writeTime.Day, writeTime.Hour, writeTime.Minute, writeTime.Second, TimeSpan.Zero); if (roundWriteTime != date.ToUniversalTime()) { var splitted = UpdateMetaTime(file, frontMatter, writeTime); // 更新文件的最近写入时间,在此前的时间上额外添加 10ms,以便编辑器或其他软件能够识别到文件变更。 var fileLastWriteTime = writeTime + TimeSpan.FromMilliseconds(10); if (splitted) { var fileCreationTime = DateTimeOffset.Parse( frontMatter.PublishDate ?? frontMatter.Date).UtcDateTime; file.CreationTimeUtc = fileCreationTime; file.LastWriteTimeUtc = fileLastWriteTime; } else { file.CreationTimeUtc = fileLastWriteTime; file.LastWriteTimeUtc = fileLastWriteTime; } return true; } } return false; } /// <summary> /// 更新 Markdown Metadata 元数据。 /// </summary> /// <param name="file"></param> /// <param name="frontMatter"></param> /// <param name="date"></param> /// <returns> /// 如果更新后日期已分为发布和更新日期,则返回 true;否则返回 false。 /// </returns> private bool UpdateMetaTime(FileInfo file, YamlFrontMeta frontMatter, DateTimeOffset date) { var originalDateString = frontMatter.Date; var newDateString = date.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss zz00"); if (string.IsNullOrWhiteSpace(frontMatter.PublishDate)) { if (double.TryParse(IgnoreInHour, out var ignoreInHour)) { var timeSpan = TimeSpan.FromHours(ignoreInHour); var originalDate = DateTimeOffset.Parse(frontMatter.Date); if (date - originalDate < timeSpan) { // 发布时间并没有过去太久,不算作更新。 UpdateFrontMatter(file, originalDateString, newDateString, false); return false; } } // 发布时间过去很久了,现在需要修改。 UpdateFrontMatter(file, originalDateString, newDateString, true); return true; } // 早已修改过,现在只是再修改而已。 UpdateFrontMatter(file, originalDateString, newDateString, false); return true; } private void UpdateFrontMatter(FileInfo file, string originalDate, string newDate, bool split) { Console.WriteLine($"- {file.FullName}"); var text = File.ReadAllText(file.FullName); var builder = new StringBuilder(text); if (split) { // date 和 publishDate 应该分开更新。 // 适用于不存在 publishDate 时。 Console.WriteLine($" publishDate: {originalDate}"); Console.WriteLine($" date: {newDate}"); builder.Replace($"date: {originalDate}", $@"publishDate: {originalDate} date: {newDate}"); } else { // 只更新 date。 // 适用于存在 publishDate,或者不存在 publishDate 但无需更新 date 时。 Console.WriteLine($" date: {newDate}"); builder.Replace($"date: {originalDate}", $@"date: {newDate}"); } File.WriteAllText(file.FullName, builder.ToString()); } } }
36.198758
102
0.507378
[ "MIT" ]
dotnet-campus/markdown-metadata
src/Mdmeta.Core/Tasks/Walterlv/UpdateTask.cs
6,382
C#
using Jobsity.Chat.DataContext.Models; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Threading.Tasks; namespace Jobsity.Chat.UI.Areas.Identity.Pages.Account.Manage { public class GenerateRecoveryCodesModel : PageModel { private readonly UserManager<ApplicationUser> _userManager; private readonly ILogger<GenerateRecoveryCodesModel> _logger; public GenerateRecoveryCodesModel( UserManager<ApplicationUser> userManager, ILogger<GenerateRecoveryCodesModel> logger) { _userManager = userManager; _logger = logger; } [TempData] public string[] RecoveryCodes { get; set; } [TempData] public string StatusMessage { get; set; } public async Task<IActionResult> OnGetAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var isTwoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user); if (!isTwoFactorEnabled) { var userId = await _userManager.GetUserIdAsync(user); throw new InvalidOperationException($"Cannot generate recovery codes for user with ID '{userId}' because they do not have 2FA enabled."); } return Page(); } public async Task<IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var isTwoFactorEnabled = await _userManager.GetTwoFactorEnabledAsync(user); var userId = await _userManager.GetUserIdAsync(user); if (!isTwoFactorEnabled) { throw new InvalidOperationException($"Cannot generate recovery codes for user with ID '{userId}' as they do not have 2FA enabled."); } var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10); RecoveryCodes = recoveryCodes.ToArray(); _logger.LogInformation("User with ID '{UserId}' has generated new 2FA recovery codes.", userId); StatusMessage = "You have generated new recovery codes."; return RedirectToPage("./ShowRecoveryCodes"); } } }
37.027778
153
0.633158
[ "MIT" ]
magupisoft/chat-challenge
Jobsity.Chat.UI/Areas/Identity/Pages/Account/Manage/GenerateRecoveryCodes.cshtml.cs
2,668
C#
using System; using System.Collections.Generic; using System.Text; namespace RegexBuilder { public class OptionsGroupPattern : GroupPattern { bool? m_IgnoreCase = null; bool? m_Multiline = null; bool? m_ExplicitCapture = null; bool? m_SingleLine = null; bool? m_IgnorePatternWhitespace = null; public OptionsGroupPattern() { } public OptionsGroupPattern(params Pattern[] patterns) : base(patterns) { } public OptionsGroupPattern IgnoreCase(bool? enabled = true) { var options = (OptionsGroupPattern)this.Copy(); options.m_IgnoreCase = enabled; options.ModifyPrefix(); return options; } public OptionsGroupPattern Multiline(bool? enabled = true) { var options = (OptionsGroupPattern)this.Copy(); options.m_Multiline = enabled; options.ModifyPrefix(); return options; } public OptionsGroupPattern ExplicitCapture(bool? enabled = true) { var options = (OptionsGroupPattern)this.Copy(); options.m_ExplicitCapture = enabled; options.ModifyPrefix(); return options; } public OptionsGroupPattern SingleLine(bool? enabled = true) { var options = (OptionsGroupPattern)this.Copy(); options.m_SingleLine = enabled; options.ModifyPrefix(); return options; } public OptionsGroupPattern IgnorePatternWhitespace(bool? enabled = true) { var options = (OptionsGroupPattern)this.Copy(); options.m_IgnorePatternWhitespace = enabled; options.ModifyPrefix(); return options; } public OptionsGroupPattern SetAll(bool? value) { var options = (OptionsGroupPattern)this.Copy(); options.m_IgnoreCase = value; options.m_Multiline = value; options.m_ExplicitCapture = value; options.m_SingleLine = value; options.m_IgnorePatternWhitespace = value; options.ModifyPrefix(); return options; } void ModifyPrefix() { string enable = ""; string disable = ""; if (m_IgnoreCase.HasValue) if (m_IgnoreCase.Value) enable += "i"; else disable += "i"; if (m_Multiline.HasValue) if (m_Multiline.Value) enable += "m"; else disable += "m"; if (m_ExplicitCapture.HasValue) if (m_ExplicitCapture.Value) enable += "n"; else disable += "n"; if (m_SingleLine.HasValue) if (m_SingleLine.Value) enable += "s"; else disable += "s"; if (m_IgnorePatternWhitespace.HasValue) if (m_IgnorePatternWhitespace.Value) enable += "x"; else disable += "x"; if (disable == "") { if (enable == "") Prefix = ""; else Prefix = $"?{enable}" + (PatternExpr == "" ? "" : ":"); } else Prefix = $"?{enable}-{disable}" + (PatternExpr == "" ? "" : ":"); } public override string Expression { get { if (Prefix == "" && PatternExpr =="") return ""; return $"({Prefix + PatternExpr})" ; } } } }
28.522059
81
0.480278
[ "MIT" ]
VBAndCs/Verex
Verex/Groups/OptionsGroup.cs
3,881
C#
using System.Collections.Generic; using System.Text.RegularExpressions; using BattleTech; using fastJSON; using Newtonsoft.Json.Linq; namespace TisButAScratch.Framework { public class GlobalVars { public static bool rollDie(int diecount, int sides, int success, out int sum) { sum = 0; for (int i = 0; i < diecount; i++) { var currentRoll = UnityEngine.Random.Range(1, sides + 1); sum += currentRoll; } return sum > success; } internal static Regex TBAS_SimBleedStatMod = new Regex("^TBAS_SimBleed__(?<type>.*?)__(?<value>.*?)$",// __(?<operation>.*?)$", RegexOptions.Compiled); //shamelessly stolen from BlueWinds internal static SimGameState sim; internal const string aiPilotFlag = "AI_TEMP_"; internal const string iGUID = "iGUID_"; internal const string injuryStateTag = "injuryState_"; internal const string DEBILITATEDTAG = "DEBILITATED"; internal const string MissionKilledStat = "MissionKilled"; internal static Injury DEBIL = new Injury { injuryID = "DEBILITATED", injuryName = "DEBILITATED", injuryLoc = InjuryLoc.NOT_SET, couldBeThermal = false, description = "Whether due to amputation or extensive tissue damage, this pilot is debilitated and is unable to deploy without rehabilitation.", severity = 100, effects = new List<EffectData>(), effectDataJO = new List<JObject>() }; [JsonIgnore] public List<EffectData> effects = new List<EffectData>(); public List<JObject> effectDataJO = new List<JObject>(); public enum InjuryLoc { NOT_SET, Psych, Head, ArmL, Torso, ArmR, LegL, LegR, } } }
31.09375
156
0.573367
[ "MIT" ]
ajkroeg/TisButAScratch
Framework/GlobalVars.cs
1,992
C#
using System; using System.Collections.Generic; using System.Diagnostics; using Manatee.Json.Internal; using Manatee.Json.Pointer; using Manatee.Json.Serialization; namespace Manatee.Json.Schema { /// <summary> /// Defines the `maxProperties` JSON Schema keyword. /// </summary> [DebuggerDisplay("Name={Name} Value={Value}")] public class MaxPropertiesKeyword : IJsonSchemaKeyword, IEquatable<MaxPropertiesKeyword> { /// <summary> /// Gets or sets the error message template. /// </summary> /// <remarks> /// Supports the following tokens: /// - actual /// - upperBound /// </remarks> public static string ErrorTemplate { get; set; } = "The array should contain at most {{upperBound}} properties, but {{actual}} were found."; /// <summary> /// Gets the name of the keyword. /// </summary> public string Name => "maxProperties"; /// <summary> /// Gets the versions (drafts) of JSON Schema which support this keyword. /// </summary> public JsonSchemaVersion SupportedVersions { get; } = JsonSchemaVersion.All; /// <summary> /// Gets the a value indicating the sequence in which this keyword will be evaluated. /// </summary> public int ValidationSequence => 1; /// <summary> /// Gets the vocabulary that defines this keyword. /// </summary> public SchemaVocabulary Vocabulary => SchemaVocabularies.Validation; /// <summary> /// The numeric value for this keyword. /// </summary> public uint Value { get; private set; } /// <summary> /// Used for deserialization. /// </summary> [DeserializationUseOnly] public MaxPropertiesKeyword() { } /// <summary> /// Creates an instance of the <see cref="MaxPropertiesKeyword"/>. /// </summary> public MaxPropertiesKeyword(uint value) { Value = value; } /// <summary> /// Provides the validation logic for this keyword. /// </summary> /// <param name="context">The context object.</param> /// <returns>Results object containing a final result and any errors that may have been found.</returns> public SchemaValidationResults Validate(SchemaValidationContext context) { var results = new SchemaValidationResults(Name, context); if (context.Instance.Type != JsonValueType.Object) return results; if (context.Instance.Object.Count > Value) { results.IsValid = false; results.AdditionalInfo["upperBound"] = Value; results.AdditionalInfo["actual"] = context.Instance.Object.Count; results.ErrorMessage = ErrorTemplate.ResolveTokens(results.AdditionalInfo); } return results; } /// <summary> /// Used register any subschemas during validation. Enables look-forward compatibility with `$ref` keywords. /// </summary> /// <param name="baseUri">The current base URI</param> /// <param name="localRegistry"></param> public void RegisterSubschemas(Uri baseUri, JsonSchemaRegistry localRegistry) { } /// <summary> /// Resolves any subschemas during resolution of a `$ref` during validation. /// </summary> /// <param name="pointer">A <see cref="JsonPointer"/> to the target schema.</param> /// <param name="baseUri">The current base URI.</param> /// <returns>The referenced schema, if it exists; otherwise null.</returns> public JsonSchema ResolveSubschema(JsonPointer pointer, Uri baseUri) { return null; } /// <summary> /// Builds an object from a <see cref="JsonValue"/>. /// </summary> /// <param name="json">The <see cref="JsonValue"/> representation of the object.</param> /// <param name="serializer">The <see cref="JsonSerializer"/> instance to use for additional /// serialization of values.</param> public void FromJson(JsonValue json, JsonSerializer serializer) { Value = (uint) json.Number; } /// <summary> /// Converts an object to a <see cref="JsonValue"/>. /// </summary> /// <param name="serializer">The <see cref="JsonSerializer"/> instance to use for additional /// serialization of values.</param> /// <returns>The <see cref="JsonValue"/> representation of the object.</returns> public JsonValue ToJson(JsonSerializer serializer) { return Value; } /// <summary>Indicates whether the current object is equal to another object of the same type.</summary> /// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns> /// <param name="other">An object to compare with this object.</param> public bool Equals(MaxPropertiesKeyword other) { if (other is null) return false; if (ReferenceEquals(this, other)) return true; return Equals(Value, other.Value); } /// <summary>Indicates whether the current object is equal to another object of the same type.</summary> /// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns> /// <param name="other">An object to compare with this object.</param> public bool Equals(IJsonSchemaKeyword other) { return Equals(other as MaxPropertiesKeyword); } /// <summary>Determines whether the specified object is equal to the current object.</summary> /// <returns>true if the specified object is equal to the current object; otherwise, false.</returns> /// <param name="obj">The object to compare with the current object. </param> public override bool Equals(object obj) { return Equals(obj as MaxPropertiesKeyword); } /// <summary>Serves as the default hash function. </summary> /// <returns>A hash code for the current object.</returns> public override int GetHashCode() { return (Value.GetHashCode()); } } }
37.77027
142
0.697853
[ "MIT" ]
JechoJekov/Manatee.Json
Manatee.Json/Schema/Keywords/MaxPropertiesKeyword.cs
5,592
C#
using System; using System.Collections.Generic; namespace Chartreuse.Today.Core.Shared.Model.Smart { public class SmartViewTagRule : SmartViewRule<string> { private static readonly List<SmartViewFilter> supportedFilters = new List<SmartViewFilter> { SmartViewFilter.Is, SmartViewFilter.IsNot, SmartViewFilter.Contains, SmartViewFilter.DoesNotContains, SmartViewFilter.Exists, SmartViewFilter.DoesNotExist }; private static readonly List<SmartViewField> supportedFields = new List<SmartViewField> { SmartViewField.Tags }; public override List<SmartViewField> SupportedFields { get { return supportedFields; } } public override List<SmartViewFilter> SupportedFilters { get { return supportedFilters; } } public SmartViewTagRule() { } public SmartViewTagRule(SmartViewFilter filter, SmartViewField field, string value) : base(filter, field, value) { } public override bool IsMatch(ITask task) { if (this.Field != SmartViewField.Tags) throw new NotImplementedException("Incorrect field"); switch (this.Filter) { case SmartViewFilter.Is: return task.Tags != null && task.Tags.Equals(this.Value, StringComparison.OrdinalIgnoreCase); case SmartViewFilter.IsNot: return task.Tags == null || (task.Tags != null && !task.Tags.Equals(this.Value, StringComparison.OrdinalIgnoreCase)); case SmartViewFilter.Contains: return task.Tags != null && task.Tags.Contains(this.Value); case SmartViewFilter.DoesNotContains: return string.IsNullOrWhiteSpace(task.Tags) || (task.Tags != null && !task.Tags.Contains(this.Value)); case SmartViewFilter.Exists: return task.ReadTags().Count > 0; case SmartViewFilter.DoesNotExist: return task.ReadTags().Count == 0; default: throw new ArgumentOutOfRangeException(); } } public override SmartViewRule Read(SmartViewFilter filter, SmartViewField field, string value) { return new SmartViewTagRule(filter, field, value); } } }
40.508475
258
0.617573
[ "MIT" ]
2DayApp/2day
src/2Day.Core.Shared/Model/Smart/SmartViewTagRule.cs
2,392
C#
namespace Lexs4SearchRetrieveWebService { /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("WscfGen", "1.0.0.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="ReferenceType", Namespace="http://niem.gov/niem/structures/2.0")] public partial class ReferenceType2 { private string idField; private string refField; private string linkMetadataField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified, DataType="ID")] public string id { get { return this.idField; } set { this.idField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified, DataType="IDREF")] public string @ref { get { return this.refField; } set { this.refField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified, DataType="IDREFS")] public string linkMetadata { get { return this.linkMetadataField; } set { this.linkMetadataField = value; } } } }
28.492063
124
0.512535
[ "Apache-2.0" ]
gtri-iead/LEXS-NET-Sample-Implementation-4.0
LEXS Search Retrieve Service Implementation/LexsSearchRetrieveCommon/ReferenceType2.cs
1,795
C#
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Windows.Threading; using MathNet.Numerics.Statistics; using Microsoft.Win32; using ScottPlot; using Math_Waveform_Graph; using Histogram_Graph; using MahApps.Metro.Controls; namespace DateTime_Waveform_Graph { /// <summary> /// Interaction logic for DateTime_Math_Waveform.xaml /// </summary> public partial class DateTime_Math_Waveform : MetroWindow { //Set Window Title, helps determine which instrument owns this Graph Window string Graph_Owner; //Needed to add the Plot to the graph ScottPlot.Plottable.SignalPlotXY Measurement_Plot; double[] Measurement_DateTime; //Date time data for the measurement data double[] Measurement_Data; //Waveform Array //Auto clear the output log after a specific amount of items inside the log has been reached. int Auto_Clear_Output_Log_Count = 40; //This integer variable is thread safe, interlocked.exchange is used. // A counter that is incremented when a measurement is processed. Show how many measuremnet is displayed on the GUI window. int Measurement_Count; //For testing set int Start_Sample; int End_Sample; string Measurement_Unit; public DateTime_Math_Waveform(string Graph_Owner, string Window_Title, double Value, int Start_Sample, int End_Sample, string Graph_Title, string Y_Axis_Label, int Red, int Green, int Blue, double[] Measurement_Data, int Measurement_Count, double[] Measurement_DateTime) { InitializeComponent(); Graph_RightClick_Menu(); this.Title = Graph_Owner + " " + Window_Title; this.Graph_Owner = Graph_Owner; if (Y_Axis_Label.Length > 3) { Measurement_Unit = Y_Axis_Label.Substring(0, 3); } else { Measurement_Unit = Y_Axis_Label; } this.Measurement_Data = Measurement_Data; this.Measurement_DateTime = Measurement_DateTime; this.Measurement_Count = Measurement_Count; this.Start_Sample = Start_Sample; this.End_Sample = End_Sample; try { Add_Measurement_Waveform(Y_Axis_Label, Red, Green, Blue); Start_SampleNumber_Label.Content = this.Start_Sample; End_SampleNumber_Label.Content = this.End_Sample; Sample_Average_Label.Content = (decimal)Math.Round(this.Measurement_Data.Mean(), 6); Max_Recorded_Sample_Label.Content = (decimal)this.Measurement_Data.Maximum(); Min_Recorded_Sample_Label.Content = (decimal)this.Measurement_Data.Minimum(); Total_Samples_Label.Content = this.Measurement_Count; Positive_Samples_Label.Content = this.Measurement_Data.Where(x => x >= 0).Count(); Negative_Samples_Label.Content = this.Measurement_Data.Where(x => x < 0).Count(); Sample_Average_Label_Unit.Content = Measurement_Unit; Max_Recorded_Sample_Label_Unit.Content = Measurement_Unit; Min_Recorded_Sample_Label_Unit.Content = Measurement_Unit; TimeSpan duration = (DateTime.FromOADate(Measurement_DateTime[Measurement_Count - 1])).Subtract(DateTime.FromOADate(Measurement_DateTime[0])); Time_Duration_Text.Content = duration.ToString("hh':'mm':'ss'.'fff"); Hours_Duration_Text.Content = Math.Round(duration.TotalHours, 10) + " h"; Minutes_Duration_Text.Content = Math.Round(duration.TotalMinutes, 10) + " m"; Seconds_Duration_Text.Content = Math.Round(duration.TotalSeconds, 10) + " s"; Graph.Plot.YLabel(Y_Axis_Label); Graph.Plot.XLabel("N Samples"); Graph.Plot.Title(Graph_Title); } catch (Exception Ex) { Graph_Color_Menu.IsEnabled = false; Insert_Log(Ex.Message, 1); Insert_Log("Probably no data inside the Measurement Data Array", 1); Graph.Plot.AddAnnotation(Ex.Message, -10, -10); Graph.Plot.AddText("Failed to create an DateTime Math Waveform, try again.", 5, 0, size: 20, color: System.Drawing.Color.Red); Graph.Plot.AxisAuto(); Graph.Render(); } } private void Add_Measurement_Waveform(string Y_Axis_Label, int Red, int Green, int Blue) { Measurement_Plot = Graph.Plot.AddSignalXY(Measurement_DateTime, Measurement_Data, color: System.Drawing.Color.FromArgb(Red, Green, Blue), label: Y_Axis_Label); Graph.Plot.XAxis.DateTimeFormat(true); Graph.Render(); } private void Window_Closed(object sender, EventArgs e) { try { Measurement_Data = null; Measurement_DateTime = null; Measurement_Plot = null; } catch (Exception) { } } } }
42.430769
278
0.645758
[ "MIT" ]
Niravk1997/HP-Data-Log-Graphing-Utility
src/.Net_Core_6/Graph_Windows/DateTime_Graph/DateTime_Math_Waveform.xaml.cs
5,518
C#
using Azure.Storage.Blobs; using Microsoft.Extensions.DependencyInjection; using Sparc.Core; namespace Sparc.Storage.Azure { public static class ServiceCollectionExtensions { public static IServiceCollection AddAzureStorage(this IServiceCollection services, string connectionString) { services.AddScoped(_ => new BlobServiceClient(connectionString)); services.AddScoped<IRepository<File>, AzureBlobRepository>(); return services; } } }
30
115
0.715686
[ "MIT" ]
sparc-coop/Sparc.Kernel
Sparc.Storage.Azure/ServiceCollectionExtensions.cs
512
C#
using System.Web.Mvc; using System.Web.Routing; namespace Entities { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Products", action = "Index", id = UrlParameter.Optional } ); } } }
25.7
104
0.529183
[ "MIT" ]
hi-q/entities
Entities/App_Start/RouteConfig.cs
516
C#
// Generated on 03/23/2022 09:50:29 using System; using System.Collections.Generic; using System.Linq; using AmaknaProxy.API.Protocol.Types; using AmaknaProxy.API.IO; using AmaknaProxy.API.Network; namespace AmaknaProxy.API.Protocol.Messages { public class TreasureHuntMessage : NetworkMessage { public const uint Id = 7652; public override uint MessageId { get { return Id; } } public sbyte questType; public double startMapId; public Types.TreasureHuntStep[] knownStepsList; public sbyte totalStepCount; public uint checkPointCurrent; public uint checkPointTotal; public int availableRetryCount; public Types.TreasureHuntFlag[] flags; public TreasureHuntMessage() { } public TreasureHuntMessage(sbyte questType, double startMapId, Types.TreasureHuntStep[] knownStepsList, sbyte totalStepCount, uint checkPointCurrent, uint checkPointTotal, int availableRetryCount, Types.TreasureHuntFlag[] flags) { this.questType = questType; this.startMapId = startMapId; this.knownStepsList = knownStepsList; this.totalStepCount = totalStepCount; this.checkPointCurrent = checkPointCurrent; this.checkPointTotal = checkPointTotal; this.availableRetryCount = availableRetryCount; this.flags = flags; } public override void Serialize(IDataWriter writer) { writer.WriteSbyte(questType); writer.WriteDouble(startMapId); writer.WriteShort((short)knownStepsList.Length); foreach (var entry in knownStepsList) { writer.WriteShort(entry.TypeId); entry.Serialize(writer); } writer.WriteSbyte(totalStepCount); writer.WriteVarInt((int)checkPointCurrent); writer.WriteVarInt((int)checkPointTotal); writer.WriteInt(availableRetryCount); writer.WriteShort((short)flags.Length); foreach (var entry in flags) { entry.Serialize(writer); } } public override void Deserialize(IDataReader reader) { questType = reader.ReadSbyte(); startMapId = reader.ReadDouble(); var limit = (ushort)reader.ReadUShort(); knownStepsList = new Types.TreasureHuntStep[limit]; for (int i = 0; i < limit; i++) { knownStepsList[i] = ProtocolTypeManager.GetInstance<Types.TreasureHuntStep>(reader.ReadUShort()); knownStepsList[i].Deserialize(reader); } totalStepCount = reader.ReadSbyte(); checkPointCurrent = reader.ReadVarUInt(); checkPointTotal = reader.ReadVarUInt(); availableRetryCount = reader.ReadInt(); limit = (ushort)reader.ReadUShort(); flags = new Types.TreasureHuntFlag[limit]; for (int i = 0; i < limit; i++) { flags[i] = new Types.TreasureHuntFlag(); flags[i].Deserialize(reader); } } } }
35.516129
236
0.593097
[ "MIT" ]
ImNotARobot742/DofusProtocol
DofusProtocol/D2Parser/Protocol/Messages/game/context/roleplay/treasureHunt/TreasureHuntMessage.cs
3,303
C#
using EnhancedBattleTest.BannerEditor; using EnhancedBattleTest.Config; using EnhancedBattleTest.UI.Basic; using TaleWorlds.Core; using TaleWorlds.Library; using TaleWorlds.Localization; namespace EnhancedBattleTest.UI { public class SideVM : ViewModel { private TeamConfig _config; private ImageIdentifierVM _banner; public TextVM Name { get; } [DataSourceProperty] public ImageIdentifierVM Banner { get => _banner; set { if (_banner == value) return; _banner = value; OnPropertyChanged(nameof(Banner)); } } public bool ShouldShowBanner => !EnhancedBattleTestSubModule.IsMultiplayer; public TextVM TacticText { get; } public NumberVM<float> TacticLevel { get; } public CharacterButtonVM General { get; } public TextVM EnableGeneralText { get; } public BoolVM EnableGeneral { get; } public TroopGroup TroopGroup { get; } public bool IsPlayerSide { set { Name.TextObject = value ? new TextObject("{=BC7n6qxk}PLAYER") : new TextObject("{=35IHscBa}ENEMY"); General.IsPlayerSide = value; TroopGroup.IsPlayerSide = value; } } public SideVM(TeamConfig config, bool isPlayerSide, BattleTypeConfig battleTypeConfig) { Name = new TextVM(isPlayerSide ? new TextObject("{=BC7n6qxk}PLAYER") : new TextObject("{=35IHscBa}ENEMY")); _config = config; Banner = new ImageIdentifierVM(BannerCode.CreateFrom(_config.BannerKey), true); TacticText = new TextVM(GameTexts.FindText("str_ebt_tactic_level")); TacticLevel = new NumberVM<float>(config.TacticLevel, 0, 100, true); TacticLevel.OnValueChanged += f => _config.TacticLevel = (int)f; General = new CharacterButtonVM(_config, _config.General, GameTexts.FindText("str_ebt_troop_role", "general"), isPlayerSide, battleTypeConfig); EnableGeneralText = new TextVM(GameTexts.FindText("str_ebt_enable")); EnableGeneral = new BoolVM(_config.HasGeneral); EnableGeneral.OnValueChanged += OnEnableGeneralChanged; TroopGroup = new TroopGroup(config, config.Troops, isPlayerSide, battleTypeConfig); } private void OnEnableGeneralChanged(bool value) { _config.HasGeneral = value; } public bool IsValid() { return TroopGroup.IsValid(); } public void EditBanner() { BannerEditorState.Config = _config; BannerEditorState.OnDone = () => Banner = new ImageIdentifierVM(BannerCode.CreateFrom(_config.BannerKey), true); TaleWorlds.Core.Game.Current.GameStateManager.PushState(TaleWorlds.Core.Game.Current.GameStateManager.CreateState<BannerEditorState>()); } public override void RefreshValues() { base.RefreshValues(); Name.RefreshValues(); General.RefreshValues(); TroopGroup.RefreshValues(); } } }
33.57732
148
0.613141
[ "MIT" ]
Fellow93/EnhancedBattleTest
source/src/UI/SideVM.cs
3,259
C#
// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. using System; using System.Linq; namespace Geb.Image.Formats.MetaData.Profiles.Icc { /// <summary> /// This type represents an array of unsigned 32bit integers. /// </summary> internal sealed class IccUInt32ArrayTagDataEntry : IccTagDataEntry, IEquatable<IccUInt32ArrayTagDataEntry> { /// <summary> /// Initializes a new instance of the <see cref="IccUInt32ArrayTagDataEntry"/> class. /// </summary> /// <param name="data">The array data</param> public IccUInt32ArrayTagDataEntry(uint[] data) : this(data, IccProfileTag.Unknown) { } /// <summary> /// Initializes a new instance of the <see cref="IccUInt32ArrayTagDataEntry"/> class. /// </summary> /// <param name="data">The array data</param> /// <param name="tagSignature">Tag Signature</param> public IccUInt32ArrayTagDataEntry(uint[] data, IccProfileTag tagSignature) : base(IccTypeSignature.UInt32Array, tagSignature) { Guard.NotNull(data, nameof(data)); this.Data = data; } /// <summary> /// Gets the array data /// </summary> public uint[] Data { get; } /// <inheritdoc/> public override bool Equals(IccTagDataEntry other) { return other is IccUInt32ArrayTagDataEntry entry && this.Equals(entry); } /// <inheritdoc/> public bool Equals(IccUInt32ArrayTagDataEntry other) { if (other == null) { return false; } if (ReferenceEquals(this, other)) { return true; } return base.Equals(other) && this.Data.SequenceEqual(other.Data); } /// <inheritdoc/> public override bool Equals(object obj) { if (obj == null) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj is IccUInt32ArrayTagDataEntry && this.Equals((IccUInt32ArrayTagDataEntry)obj); } /// <inheritdoc/> public override int GetHashCode() { unchecked { return (base.GetHashCode() * 397) ^ (this.Data?.GetHashCode() ?? 0); } } } }
28.977011
110
0.539865
[ "MIT" ]
xiaotie/GebImage
src/Geb.Image/Formats/MetaData/Profiles/ICC/TagDataEntries/IccUInt32ArrayTagDataEntry.cs
2,523
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.Collections.Generic; using System.Security.Policy; using System.IO; using System.Configuration.Assemblies; using StackCrawlMark = System.Threading.StackCrawlMark; using System.Runtime.Serialization; using System.Diagnostics.Contracts; using System.Runtime.Loader; namespace System.Reflection { public abstract partial class Assembly : ICustomAttributeProvider, ISerializable { private static volatile bool s_LoadFromResolveHandlerSetup = false; private static object s_syncRootLoadFrom = new object(); private static List<string> s_LoadFromAssemblyList = new List<string>(); private static object s_syncLoadFromAssemblyList = new object(); private static Assembly LoadFromResolveHandler(object sender, ResolveEventArgs args) { Assembly requestingAssembly = args.RequestingAssembly; // Requesting assembly for LoadFrom is always loaded in defaultContext - proceed only if that // is the case. if (AssemblyLoadContext.Default != AssemblyLoadContext.GetLoadContext(requestingAssembly)) return null; // Get the path where requesting assembly lives and check if it is in the list // of assemblies for which LoadFrom was invoked. bool fRequestorLoadedViaLoadFrom = false; string requestorPath = Path.GetFullPath(requestingAssembly.Location); if (string.IsNullOrEmpty(requestorPath)) return null; lock(s_syncLoadFromAssemblyList) { fRequestorLoadedViaLoadFrom = s_LoadFromAssemblyList.Contains(requestorPath); } // If the requestor assembly was not loaded using LoadFrom, exit. if (!fRequestorLoadedViaLoadFrom) return null; // Requestor assembly was loaded using loadFrom, so look for its dependencies // in the same folder as it. // Form the name of the assembly using the path of the assembly that requested its load. AssemblyName requestedAssemblyName = new AssemblyName(args.Name); string requestedAssemblyPath = Path.Combine(Path.GetDirectoryName(requestorPath), requestedAssemblyName.Name+".dll"); // Load the dependency via LoadFrom so that it goes through the same path of being in the LoadFrom list. Assembly resolvedAssembly = null; try { resolvedAssembly = Assembly.LoadFrom(requestedAssemblyPath); } catch(FileNotFoundException) { // Catch FileNotFoundException when attempting to resolve assemblies via this handler to account for missing assemblies. resolvedAssembly = null; } return resolvedAssembly; } public static Assembly LoadFrom(String assemblyFile) { if (assemblyFile == null) throw new ArgumentNullException(nameof(assemblyFile)); string fullPath = Path.GetFullPath(assemblyFile); if (!s_LoadFromResolveHandlerSetup) { lock (s_syncRootLoadFrom) { if (!s_LoadFromResolveHandlerSetup) { AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(LoadFromResolveHandler); s_LoadFromResolveHandlerSetup = true; } } } // Add the path to the LoadFrom path list which we will consult // before handling the resolves in our handler. lock(s_syncLoadFromAssemblyList) { if (!s_LoadFromAssemblyList.Contains(fullPath)) { s_LoadFromAssemblyList.Add(fullPath); } } return AssemblyLoadContext.Default.LoadFromAssemblyPath(fullPath); } public static Assembly LoadFrom(String assemblyFile, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm) { throw new NotSupportedException(SR.NotSupported_AssemblyLoadFromHash); } // Locate an assembly by the long form of the assembly name. // eg. "Toolbox.dll, version=1.1.10.1220, locale=en, publickey=1234567890123456789012345678901234567890" [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static Assembly Load(String assemblyString) { Contract.Ensures(Contract.Result<Assembly>() != null); Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeAssembly.InternalLoad(assemblyString, null, ref stackMark, false /*forIntrospection*/); } // Returns type from the assembly while keeping compatibility with Assembly.Load(assemblyString).GetType(typeName) for managed types. // Calls Type.GetType for WinRT types. // Note: Type.GetType fails for assembly names that start with weird characters like '['. By calling it for managed types we would // break AppCompat. [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod internal static Type GetType_Compat(String assemblyString, String typeName) { // Normally we would get the stackMark only in public APIs. This is internal API, but it is AppCompat replacement of public API // call Assembly.Load(assemblyString).GetType(typeName), therefore we take the stackMark here as well, to be fully compatible with // the call sequence. StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; RuntimeAssembly assembly; AssemblyName assemblyName = RuntimeAssembly.CreateAssemblyName( assemblyString, false /*forIntrospection*/, out assembly); if (assembly == null) { if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime) { return Type.GetType(typeName + ", " + assemblyString, true /*throwOnError*/, false /*ignoreCase*/); } assembly = RuntimeAssembly.InternalLoadAssemblyName( assemblyName, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/); } return assembly.GetType(typeName, true /*throwOnError*/, false /*ignoreCase*/); } // Locate an assembly by its name. The name can be strong or // weak. The assembly is loaded into the domain of the caller. [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static Assembly Load(AssemblyName assemblyRef) { Contract.Ensures(Contract.Result<Assembly>() != null); Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly); AssemblyName modifiedAssemblyRef = null; if (assemblyRef != null && assemblyRef.CodeBase != null) { modifiedAssemblyRef = (AssemblyName)assemblyRef.Clone(); modifiedAssemblyRef.CodeBase = null; } else { modifiedAssemblyRef = assemblyRef; } StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeAssembly.InternalLoadAssemblyName(modifiedAssemblyRef, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/); } // Locate an assembly by its name. The name can be strong or // weak. The assembly is loaded into the domain of the caller. [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod internal static Assembly Load(AssemblyName assemblyRef, IntPtr ptrLoadContextBinder) { Contract.Ensures(Contract.Result<Assembly>() != null); Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly); AssemblyName modifiedAssemblyRef = null; if (assemblyRef != null && assemblyRef.CodeBase != null) { modifiedAssemblyRef = (AssemblyName)assemblyRef.Clone(); modifiedAssemblyRef.CodeBase = null; } else { modifiedAssemblyRef = assemblyRef; } StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeAssembly.InternalLoadAssemblyName(modifiedAssemblyRef, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/, ptrLoadContextBinder); } // Loads the assembly with a COFF based IMAGE containing // an emitted assembly. The assembly is loaded into the domain // of the caller. The second parameter is the raw bytes // representing the symbol store that matches the assembly. [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore) { Contract.Ensures(Contract.Result<Assembly>() != null); Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly); AppDomain.CheckLoadByteArraySupported(); if (rawAssembly == null) throw new ArgumentNullException(nameof(rawAssembly)); AssemblyLoadContext alc = new IndividualAssemblyLoadContext(); MemoryStream assemblyStream = new MemoryStream(rawAssembly); MemoryStream symbolStream = (rawSymbolStore != null) ? new MemoryStream(rawSymbolStore) : null; return alc.LoadFromStream(assemblyStream, symbolStream); } private static Dictionary<string, Assembly> s_loadfile = new Dictionary<string, Assembly>(); public static Assembly LoadFile(String path) { Contract.Ensures(Contract.Result<Assembly>() != null); Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly); AppDomain.CheckLoadFileSupported(); Assembly result = null; if (path == null) throw new ArgumentNullException(nameof(path)); if (PathInternal.IsPartiallyQualified(path)) { throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(path)); } string normalizedPath = Path.GetFullPath(path); lock (s_loadfile) { if (s_loadfile.TryGetValue(normalizedPath, out result)) return result; AssemblyLoadContext alc = new IndividualAssemblyLoadContext(); result = alc.LoadFromAssemblyPath(normalizedPath); s_loadfile.Add(normalizedPath, result); } return result; } /* * Get the assembly that the current code is running from. */ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static Assembly GetExecutingAssembly() { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeAssembly.GetExecutingAssembly(ref stackMark); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static Assembly GetCallingAssembly() { // LookForMyCallersCaller is not guarantee to return the correct stack frame // because of inlining, tail calls, etc. As a result GetCallingAssembly is not // ganranteed to return the correct result. We should document it as such. StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller; return RuntimeAssembly.GetExecutingAssembly(ref stackMark); } public static Assembly GetEntryAssembly() { AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager; if (domainManager == null) domainManager = new AppDomainManager(); return domainManager.EntryAssembly; } } }
46.553571
189
0.637131
[ "MIT" ]
dotnetGame/coreclr
src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs
13,035
C#
using System; using UnityEngine; public class Destructible { public float Health { get; private set; } public float MaxHealth { get; private set; } public Action onDeath = delegate { }; public Action onHurt = delegate { }; public Destructible(float health, float maxHealth) { if (maxHealth > health) { health = maxHealth; } MaxHealth = maxHealth; Health = health; } /// <summary> /// Hurt the destructible. /// </summary> /// <returns>true if died.</returns> public bool Hurt(float value) { Health -= value; Health = Mathf.Clamp(Health, 0f, MaxHealth); onHurt.Invoke(); if (Health <= 0f) { Die(); return true; } return false; } public void Die() { onDeath.Invoke(); } }
18.5
54
0.527027
[ "MIT" ]
marcuskaraker/JRPG_Fighting
Assets/Scripts/Combat/Destructible.cs
890
C#
using System.Diagnostics.CodeAnalysis; namespace LanceC.SpreadsheetIO.Reading.Failures; /// <summary> /// Represents a header mismatch between the defined map and the spreadsheet. /// </summary> [ExcludeFromCodeCoverage] public record HeaderReadingFailure( bool MissingHeaderRow, IReadOnlyCollection<MissingHeaderReadingFailure> MissingHeaders, IReadOnlyCollection<InvalidHeaderReadingFailure> InvalidHeaders) { /// <summary> /// Gets the value that determines whether the specified header row is not found. /// </summary> public bool MissingHeaderRow { get; init; } = MissingHeaderRow; /// <summary> /// Gets the collection of headers that are not found. /// </summary> public IReadOnlyCollection<MissingHeaderReadingFailure> MissingHeaders { get; init; } = MissingHeaders; /// <summary> /// Gets the collection of headers that do not match the map. /// </summary> public IReadOnlyCollection<InvalidHeaderReadingFailure> InvalidHeaders { get; init; } = InvalidHeaders; }
35.724138
107
0.737452
[ "MIT" ]
lanceccraig/SpreadsheetIO
src/SpreadsheetIO/Reading/Failures/HeaderReadingFailure.cs
1,036
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.AspNetCore; using Microsoft.Extensions.DependencyInjection; using Oqtane.Infrastructure; using System.Diagnostics; using Microsoft.Extensions.Logging; using Oqtane.Shared; using Oqtane.Documentation; namespace Oqtane.Server { [PrivateApi("Mark Entry-Program as private, since it's not very useful in the public docs")] public class Program { public static void Main(string[] args) { var host = BuildWebHost(args); var databaseManager = host.Services.GetService<IDatabaseManager>(); var install = databaseManager.Install(); if (!string.IsNullOrEmpty(install.Message)) { var filelogger = host.Services.GetRequiredService<ILogger<Program>>(); if (filelogger != null) { filelogger.LogError($"[Oqtane.Server.Program.Main] {install.Message}"); } } host.Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseConfiguration(new ConfigurationBuilder() .AddCommandLine(args) .Build()) .UseStartup<Startup>() .ConfigureLocalizationSettings() .Build(); } }
33.860465
96
0.612637
[ "MIT" ]
2sic-forks/oqtane.framework
Oqtane.Server/Program.cs
1,456
C#
using System; using Spax.Physics2D; namespace Spax.Physics2D { [Flags] public enum PhysicsLogicType { Explosion = (1 << 0) } public struct PhysicsLogicFilter { public PhysicsLogicType ControllerIgnores; /// <summary> /// Ignores the controller. The controller has no effect on this body. /// </summary> /// <param name="type">The logic type.</param> public void IgnorePhysicsLogic(PhysicsLogicType type) { ControllerIgnores |= type; } /// <summary> /// Restore the controller. The controller affects this body. /// </summary> /// <param name="type">The logic type.</param> public void RestorePhysicsLogic(PhysicsLogicType type) { ControllerIgnores &= ~type; } /// <summary> /// Determines whether this body ignores the the specified controller. /// </summary> /// <param name="type">The logic type.</param> /// <returns> /// <c>true</c> if the body has the specified flag; otherwise, <c>false</c>. /// </returns> public bool IsPhysicsLogicIgnored(PhysicsLogicType type) { return (ControllerIgnores & type) == type; } } public abstract class PhysicsLogic : FilterData { private PhysicsLogicType _type; public World World; public override bool IsActiveOn(Body body) { if (body.PhysicsLogicFilter.IsPhysicsLogicIgnored(_type)) return false; return base.IsActiveOn(body); } public PhysicsLogic(World world, PhysicsLogicType type) { _type = type; World = world; } } }
27.030303
85
0.566704
[ "MIT" ]
JoshHux/SpaxFightingGameEnginePrototype
Assets/_hysics/FixedPoint/Physics/Farseer/Common/PhysicsLogic/PhysicsLogic.cs
1,784
C#
namespace DIO.Series { public enum Genero { Acao = 1, Aventura = 2, Comedia = 3, Documentario = 4, Drama = 5, Ficcao_Cientifica = 6, Musical = 7, Romance = 8, Suspense = 9, Terror = 10 } }
14.25
30
0.442105
[ "MIT" ]
devguilhermeribeiro/App-de-Serie-da-DIO
DIO.Series/Enum/Genero.cs
285
C#
using Handyman.DataContractValidator.Model; using System.Diagnostics; namespace Handyman.DataContractValidator.Validation { internal class AnyValidator : ITypeInfoValidator { public void Validate(ITypeInfo actual, ITypeInfo expected, ValidationContext context) { Debug.Assert(expected is AnyTypeInfo); } } }
27.461538
93
0.722689
[ "MIT" ]
JonasSamuelsson/Handyman
src/Handyman.DataContractValidator/src/Validation/AnyValidator.cs
359
C#
namespace AVLTree { public class AVLSortedDictionary<TKey, TValue> { } }
12
51
0.583333
[ "MIT" ]
tvvister/AVLTree
AVLTree/AVLSortedDictionary.cs
98
C#
#region "copyright" /* Copyright © 2016 - 2021 Stefan Berg <isbeorn86+NINA@googlemail.com> and the N.I.N.A. contributors This file is part of N.I.N.A. - Nighttime Imaging 'N' Astronomy. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #endregion "copyright" using ASCOM; using ASCOM.DriverAccess; using NINA.Core.Locale; using NINA.Core.Utility; using NINA.Core.Utility.Notification; using NINA.Equipment.Interfaces; using NINA.Equipment.Utility; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace NINA.Equipment.Equipment { /// <summary> /// The unified class that handles the shared properties of all ASCOM devices like Connection, Generic Info and Setup /// </summary> public abstract class AscomDevice<T> : BaseINPC, IDevice where T : AscomDriver { public AscomDevice(string id, string name) { Id = id; Name = name; } protected T device; public string Category { get; } = "ASCOM"; protected abstract string ConnectionLostMessage { get; } protected object lockObj = new object(); public bool HasSetupDialog { get { return true; } } public string Id { get; } public string Name { get; } public string Description { get { try { return device?.Description ?? string.Empty; } catch (Exception) { } return string.Empty; } } public string DriverInfo { get { try { return device?.DriverInfo ?? string.Empty; } catch (Exception) { } return string.Empty; } } public string DriverVersion { get { try { return device?.DriverVersion ?? string.Empty; } catch (Exception) { } return string.Empty; } } private bool connected; private void DisconnectOnConnectionError() { try { Notification.ShowWarning(ConnectionLostMessage); Disconnect(); } catch (Exception ex) { Logger.Error(ex); } } public bool Connected { get { lock (lockObj) { if (connected && device != null) { bool val = false; try { bool expected; val = device?.Connected ?? false; expected = connected; if (expected != val) { Logger.Error($"{Name} should be connected but reports to be disconnected. Trying to reconnect..."); try { Connected = true; if (!device.Connected) { throw new NotConnectedException(); } val = true; Logger.Info($"{Name} reconnection successful"); } catch (Exception ex) { Logger.Error("Reconnection failed. The device might be disconnected! - ", ex); DisconnectOnConnectionError(); } } } catch (Exception ex) { Logger.Error(ex); DisconnectOnConnectionError(); } return val; } else { return false; } } } private set { lock (lockObj) { if (device != null) { Logger.Debug($"SET {Name} Connected to {value}"); device.Connected = value; connected = value; } } } } /// <summary> /// Customizing hook called before connection /// </summary> protected virtual Task PreConnect() { return Task.CompletedTask; } /// <summary> /// Customizing hook called after successful connection /// </summary> protected virtual Task PostConnect() { return Task.CompletedTask; } /// <summary> /// Customizing hook called before disconnection /// </summary> protected virtual void PreDisconnect() { } /// <summary> /// Customizing hook called after disconnection /// </summary> protected virtual void PostDisconnect() { } public Task<bool> Connect(CancellationToken token) { return Task.Run(async () => { try { propertyGETMemory = new Dictionary<string, PropertyMemory>(); propertySETMemory = new Dictionary<string, PropertyMemory>(); Logger.Trace($"{Name} - Calling PreConnect"); await PreConnect(); Logger.Trace($"{Name} - Creating instance for {Id}"); device = GetInstance(Id); Connected = true; if (Connected) { Logger.Trace($"{Name} - Calling PostConnect"); await PostConnect(); RaiseAllPropertiesChanged(); } } catch (Exception ex) { Logger.Error(ex); Notification.ShowError(string.Format(Loc.Instance["LblUnableToConnect"], Name, ex.Message)); } return Connected; }); } protected abstract T GetInstance(string id); public void SetupDialog() { if (HasSetupDialog) { try { bool dispose = false; if (device == null) { Logger.Trace($"{Name} - Creating instance for {Id}"); device = GetInstance(Id); dispose = true; } Logger.Trace($"{Name} - Creating Setup Dialog for {Id}"); device.SetupDialog(); if (dispose) { device.Dispose(); device = null; } } catch (Exception ex) { Logger.Error(ex); Notification.ShowError(ex.Message); } } } public void Disconnect() { lock (lockObj) { Logger.Info($"Disconnecting from {Id} {Name}"); Logger.Trace($"{Name} - Calling PreDisconnect"); PreDisconnect(); try { Connected = false; } catch (Exception ex) { Logger.Error(ex); } connected = false; Logger.Trace($"{Name} - Calling PostDisconnect"); PostDisconnect(); Dispose(); } RaiseAllPropertiesChanged(); } public void Dispose() { Logger.Trace($"{Name} - Disposing device"); device?.Dispose(); device = null; } protected Dictionary<string, PropertyMemory> propertyGETMemory = new Dictionary<string, PropertyMemory>(); protected Dictionary<string, PropertyMemory> propertySETMemory = new Dictionary<string, PropertyMemory>(); /// <summary> /// Tries to get a property by its name. If an exception occurs the last known value will be used instead. /// If a PropertyNotImplementedException occurs, the "isImplemetned" value will be set to false /// </summary> /// <typeparam name="PropT"></typeparam> /// <param name="propertyName">Property Name of the AscomDevice property</param> /// <param name="defaultValue">The default value to be returned when not connected or not implemented</param> /// <returns></returns> protected PropT GetProperty<PropT>(string propertyName, PropT defaultValue) { if (device != null) { var retries = 3; var interval = TimeSpan.FromMilliseconds(100); var type = device.GetType(); if (!propertyGETMemory.TryGetValue(propertyName, out var memory)) { memory = new PropertyMemory(type.GetProperty(propertyName)); propertyGETMemory[propertyName] = memory; } for (int i = 0; i < retries; i++) { try { if (i > 0) { Thread.Sleep(interval); Logger.Info($"Retrying to GET {type.Name}.{propertyName} - Attempt {i + 1} / {retries}"); } if (memory.IsImplemented && Connected) { PropT value = (PropT)memory.GetValue(device); Logger.Trace($"GET {type.Name}.{propertyName}: {value}"); return (PropT)memory.LastValue; } else { return defaultValue; } } catch (Exception ex) { if (ex.InnerException is PropertyNotImplementedException || ex.InnerException is System.NotImplementedException) { Logger.Info($"Property {type.Name}.{propertyName} GET is not implemented in this driver ({Name})"); memory.IsImplemented = false; return defaultValue; } if (ex.InnerException is NotConnectedException) { Logger.Error($"{Name} is not connected ", ex.InnerException); } var logEx = ex.InnerException ?? ex; Logger.Error($"An unexpected exception occurred during GET of {type.Name}.{propertyName}: ", logEx); } } var val = (PropT)memory.LastValue; Logger.Info($"GET {type.Name}.{propertyName} failed - Returning last known value {val}"); return val; } return defaultValue; } /// <summary> /// Tries to set a property by its name. If an exception occurs it will be logged. /// If a PropertyNotImplementedException occurs, the "isImplemetned" value will be set to false /// </summary> /// <typeparam name="PropT"></typeparam> /// <param name="propertyName">Property Name of the AscomDevice property</param> /// <param name="value">The value to be set for the given property</param> /// <returns></returns> protected bool SetProperty<PropT>(string propertyName, PropT value, [CallerMemberName] string originalPropertyName = null) { if (device != null) { var type = device.GetType(); if (!propertySETMemory.TryGetValue(propertyName, out var memory)) { memory = new PropertyMemory(type.GetProperty(propertyName)); propertySETMemory[propertyName] = memory; } try { if (memory.IsImplemented && Connected) { memory.SetValue(device, value); Logger.Trace($"SET {type.Name}.{propertyName}: {value}"); RaisePropertyChanged(originalPropertyName); return true; } else { return false; } } catch (Exception ex) { if (ex.InnerException is PropertyNotImplementedException || ex.InnerException is System.NotImplementedException) { Logger.Info($"Property {type.Name}.{propertyName} SET is not implemented in this driver ({Name})"); memory.IsImplemented = false; return false; } if (ex is InvalidValueException) { Logger.Warning(ex.Message); return false; } if (ex is ASCOM.InvalidOperationException) { Logger.Warning(ex.Message); return false; } if (ex.InnerException is NotConnectedException) { Logger.Error($"{Name} is not connected ", ex.InnerException); return false; } var message = ex.InnerException?.Message ?? ex.Message; Logger.Error($"An unexpected exception occurred during SET of {type.Name}.{propertyName}: {message}"); } } return false; } protected class PropertyMemory { public PropertyMemory(PropertyInfo p) { info = p; IsImplemented = true; LastValue = null; if (p.PropertyType.IsValueType) { LastValue = Activator.CreateInstance(p.PropertyType); } } private PropertyInfo info; public bool IsImplemented { get; set; } public object LastValue { get; set; } public object GetValue(AscomDriver device) { var value = info.GetValue(device); LastValue = value; return value; } public void SetValue(AscomDriver device, object value) { info.SetValue(device, value); } } } }
37.321337
138
0.480438
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
daleghent/NINA
NINA.Equipment/Equipment/AscomDevice.cs
14,521
C#
using Microsoft.SyndicationFeed; using TDNI.External.Blogs.Parsers.PostParsers.Attributes.Abstract; namespace TDNI.External.Blogs.Parsers.PostParsers.Attributes { public class AuthorParser : IAttributeParser<AuthorParser> { public string Parse(ISyndicationItem item, params string[] args) { string author = args[0]; ISyndicationPerson? person = item.Contributors.FirstOrDefault(x => x.RelationshipType == "author"); if (person != null) { author = person.Name ?? person.Email; } return author; } } }
29.809524
111
0.624601
[ "MIT" ]
hasan-hasanov/TheDotNetInfo
src/TheDotNetInfo/TDNI.External.Blogs/Parsers/PostParsers/Attributes/AuthorParser.cs
628
C#
/*************************************************************************/ /* Copyright (c) 2016 Iván Vodopiviz */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ using UnityEngine; using System.Collections; public class OrbitCamera : MonoBehaviour { public Transform target; public float speed = 1; void Start () { } void Update () { if (target != null) { transform.LookAt (target); transform.Translate (Vector3.right * Time.deltaTime * speed); } } }
45.813953
76
0.540102
[ "MIT" ]
ivodopiviz/UnityVoxelExample
Assets/scripts/OrbitCamera.cs
1,973
C#
using Microsoft.SharePoint.Client; using PnP.PowerShell.Commands.Base.PipeBinds; using System; using System.Management.Automation; namespace PnP.PowerShell.Commands.Principals { [Cmdlet(VerbsCommon.Remove, "PnPAlert")] public class RemoveAlert : PnPWebCmdlet { [Parameter(Mandatory = false)] public UserPipeBind User; [Parameter(Mandatory = true)] public AlertPipeBind Identity; [Parameter(Mandatory = false)] public SwitchParameter Force; protected override void ExecuteCmdlet() { User user; if (null != User) { user = User.GetUser(ClientContext); if (user == null) { throw new ArgumentException("Unable to find user", "Identity"); } } else { user = CurrentWeb.CurrentUser; } if (!Force) { user.EnsureProperty(u => u.LoginName); } if (Force || ShouldContinue($"Remove alert {Identity.Id} for {user.LoginName}?", "Remove alert")) { user.Alerts.DeleteAlert(Identity.Id); ClientContext.ExecuteQueryRetry(); } } } }
27.87234
109
0.529008
[ "MIT" ]
AndersRask/powershell
src/Commands/Principals/RemoveAlert.cs
1,312
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace ResNet50 { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (e.PrelaunchActivated == false) { if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); } } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } } }
38.811881
99
0.614031
[ "MIT" ]
ChangweiZhang/Awesome-WindowsML-ONNX-Models
src/WindowsML-Demos/ResNet50/App.xaml.cs
3,922
C#
using System.Collections.Generic; namespace AbstractFactoryDesignPattern.Domain.Interface { using Entities; public interface IInstrumentoCorda { IList<Nota> ListarNotas(); short ObterQuantidadeCordas(); } }
18.615385
55
0.710744
[ "MIT" ]
abrandaol-youtube/DesignPatternsGoF
AbstractFactoryDesignPattern/Domain/Interface/IInstrumentoCorda.cs
244
C#
using Kros.Authorization.Api.Domain; using Kros.KORM; using Kros.KORM.Converter; using Kros.KORM.Metadata; namespace Kros.Authorization.Api.Infrastructure { /// <summary> /// Configure database for KORM. /// </summary> public class DatabaseConfiguration : DatabaseConfigurationBase { /// <summary> /// Name of Users table in database. /// </summary> internal const string UsersTableName = "Users"; /// <summary> /// Name of Permissions table in database. /// </summary> internal const string PermissionsTableName = "Permissions"; /// <summary> /// Create database model. /// </summary> /// <param name="modelBuilder"><see cref="ModelConfigurationBuilder"/></param> public override void OnModelCreating(ModelConfigurationBuilder modelBuilder) { modelBuilder.Entity<User>() .HasTableName(UsersTableName) .HasPrimaryKey(f => f.Id).AutoIncrement(AutoIncrementMethodType.Custom) .UseConverterForProperties<string>(NullAndTrimStringConverter.ConvertNull); modelBuilder.Entity<Permission>() .HasTableName(PermissionsTableName) .UseConverterForProperties<string>(NullAndTrimStringConverter.ConvertNull) .Property(f => f.Key).HasColumnName("PermissionKey"); } } }
34.731707
91
0.633427
[ "MIT" ]
Kros-sk/Kros.AspNetCore.BestPractices
src/Services/Kros.Authorization.Api/Infrastructure/DatabaseConfiguration.cs
1,426
C#
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() // 100/100 { List<int> upperZip = Console.ReadLine().Split(' ').Select(int.Parse).ToList(); List<int> lowerZip = Console.ReadLine().Split(' ').Select(int.Parse).ToList(); int firstCounter = 0; int latterCounter = 100; int biggestCounter = 100; FindTheSmallestDigit(lowerZip, ref firstCounter, ref latterCounter, ref biggestCounter); FindTheSmallestDigit(upperZip, ref firstCounter, ref latterCounter, ref biggestCounter); RemoveBiggestNumbers(lowerZip, biggestCounter); RemoveBiggestNumbers(upperZip, biggestCounter); List<int> printAnswer = new List<int>(); for (int cycle = 0; cycle < Math.Max(upperZip.Count, lowerZip.Count); cycle++) { if (cycle < lowerZip.Count) { printAnswer.Add(lowerZip[cycle]); } if (cycle < upperZip.Count) { printAnswer.Add(upperZip[cycle]); } } Console.WriteLine(string.Join(" ", printAnswer)); } static void FindTheSmallestDigit(List<int> upperZip, ref int firstCounter, ref int latterCounter, ref int biggestCounter) { for (int upperCycle = 0; upperCycle < upperZip.Count; upperCycle++) { firstCounter = 0; string enumerate = upperZip[upperCycle].ToString(); foreach (char character in enumerate) { if (character == '-') { continue; } firstCounter++; } if (Math.Min(latterCounter, firstCounter) < biggestCounter) { biggestCounter = Math.Min(latterCounter, firstCounter); } latterCounter = firstCounter; } } static void RemoveBiggestNumbers(List<int> upperZip, int biggestCounter) { for (int upperCycle = 0; upperCycle < upperZip.Count; upperCycle++) { int finalCounter = 0; string enumerate = upperZip[upperCycle].ToString(); foreach (char character in enumerate) { if (character == '-') { continue; } finalCounter++; } if (finalCounter > biggestCounter) { upperZip.RemoveAt(upperCycle); upperCycle--; } } } }
32.518987
125
0.538731
[ "MIT" ]
GabrielRezendi/Programming-Fundamentals-2017
02.Extented Fundamentals/15.LISTS - EXERCISES/06.03 Stuck Zipper/Program.cs
2,571
C#
using System; using System.Collections.Generic; using System.Text; using Qwack.Transport.BasicTypes; namespace Qwack.Transport.TransportObjects.Instruments.Funding { public class TO_FloatRateIndex { public DayCountBasis DayCountBasis { get; set; } public DayCountBasis DayCountBasisFixed { get; set; } public string ResetTenor { get; set; } public string ResetTenorFixed { get; set; } public string HolidayCalendars { get; set; } public RollType RollConvention { get; set; } public string Currency { get; set; } public string FixingOffset { get; set; } } }
28.909091
62
0.683962
[ "MIT" ]
cetusfinance/qwack
src/Qwack.Transport/TransportObjects/Instruments/Funding/TO_FloatRateIndex.cs
636
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Burnable : MonoBehaviour { public GameObject burningEffect; public bool isOnFire; public float fireHealth; public float moistureAmount; // Use this for initialization void Start () { } // Update is called once per frame void Update () { burningEffect.SetActive(isOnFire); } }
18.5
42
0.714988
[ "MIT" ]
WallRushGO/ASMGameJam2018
game/Assets/_Proto_UnitControl/Scripts/Burnable.cs
409
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.Collections.Generic; namespace Microsoft.Toolkit.Parsers.Markdown.Blocks { /// <summary> /// This specifies the Content of the List element. /// </summary> public class ListItemBlock { /// <summary> /// Gets or sets the contents of the list item. /// </summary> public IList<MarkdownBlock> Blocks { get; set; } internal ListItemBlock() { } } }
27.913043
71
0.643302
[ "MIT" ]
14632791/WindowsCommunityToolkit
Microsoft.Toolkit.Parsers/Markdown/Blocks/List/ListItemBlock.cs
642
C#
// This file is part of Silk.NET. // // You may modify and distribute Silk.NET under the terms // of the MIT license. See the LICENSE file for details. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Text; using Silk.NET.Core; using Silk.NET.Core.Native; using Silk.NET.Core.Attributes; using Silk.NET.Core.Contexts; using Silk.NET.Core.Loader; using Silk.NET.OpenGLES; using Extension = Silk.NET.Core.Attributes.ExtensionAttribute; #pragma warning disable 1591 namespace Silk.NET.OpenGLES.Extensions.NV { [Extension("NV_fragment_coverage_to_color")] public unsafe partial class NVFragmentCoverageToColor : NativeExtension<GL> { public const string ExtensionName = "NV_fragment_coverage_to_color"; [NativeApi(EntryPoint = "glFragmentCoverageColorNV")] public partial void FragmentCoverageColor([Flow(FlowDirection.In)] uint color); public NVFragmentCoverageToColor(INativeContext ctx) : base(ctx) { } } }
29.771429
87
0.742802
[ "MIT" ]
ThomasMiz/Silk.NET
src/OpenGL/Extensions/Silk.NET.OpenGLES.Extensions.NV/NVFragmentCoverageToColor.gen.cs
1,042
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Rocky_Models { public class OrderDetail { [Key] public int Id { get; set; } [Required] public int OrderHeaderId { get; set; } [ForeignKey("OrderHeaderId")] public OrderHeader OrderHeader { get; set; } [Required] public int ProductId { get; set; } [ForeignKey("ProductId")] public Product Product { get; set; } public int Sqft { get; set; } public double PricePerSqFt { get; set; } } }
23.290323
52
0.641274
[ "MIT" ]
PacktPublishing/ASP.NET-Core-MVC-Up-and-Running-.NET-5
Part 2 Code bundle/Rocky_Models/OrderDetail.cs
724
C#
namespace MassTransit.RabbitMqTransport.Topology { using System.Collections.Generic; /// <summary> /// The exchange to queue binding details to declare the binding to RabbitMQ /// </summary> public interface ExchangeToQueueBinding { /// <summary> /// The source exchange /// </summary> Exchange Source { get; } /// <summary> /// The destination exchange /// </summary> Queue Destination { get; } /// <summary> /// A routing key for the exchange binding /// </summary> string RoutingKey { get; } /// <summary> /// The arguments for the binding /// </summary> IDictionary<string, object> Arguments { get; } } }
24.0625
80
0.555844
[ "ECL-2.0", "Apache-2.0" ]
AlexanderMeier/MassTransit
src/Transports/MassTransit.RabbitMqTransport/RabbitMqTransport/Topology/Entities/ExchangeToQueueBinding.cs
770
C#
/* * MinIO .NET Library for Amazon S3 Compatible Cloud Storage, (C) 2017 MinIO, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Minio.Helper { internal static class Constants { // Maximum number of parts. public static int MaxParts = 10000; // Minimum part size. public static long MinimumPartSize = 5 * 1024L * 1024L; // Maximum part size. public static long MaximumPartSize = 5 * 1024L * 1024L * 1024L; // Maximum streaming object size. public static long MaximumStreamObjectSize = MaxParts * MinimumPartSize; // maxSinglePutObjectSize - maximum size 5GiB of object per PUT // operation. public static long MaxSinglePutObjectSize = 1024L * 1024L * 1024L * 5; // maxSingleCopyObjectSize - 5GiB public static long MaxSingleCopyObjectSize = 1024L * 1024L * 1024L * 5; // maxMultipartPutObjectSize - maximum size 5TiB of object for // Multipart operation. public static long MaxMultipartPutObjectSize = 1024L * 1024L * 1024L * 1024L * 5; // optimalReadBufferSize - optimal buffer 5MiB used for reading // through Read operation. public static long OptimalReadBufferSize = 1024L * 1024L * 5; public static int DefaultExpiryTime = 7 * 24 * 3600; // SSEGenericHeader is the AWS SSE header used for SSE-S3 and SSE-KMS. public static string SSEGenericHeader = "X-Amz-Server-Side-Encryption"; // SSEKMSKeyId is the AWS SSE KMS Key-Id. public static string SSEKMSKeyId = "X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id"; // SSEKMSContext is the AWS SSE KMS Context. public static string SSEKMSContext = "X-Amz-Server-Side-Encryption-Context"; } }
41.690909
89
0.68382
[ "Apache-2.0" ]
krisis/minio-dotnet
Minio/Helper/Constants.cs
2,295
C#
namespace _05.Sort_Array_Using_Insertion_Sort { using System; using System.Collections.Generic; using System.Linq; public class SortArrayUsingInsertionSort { public static void Main() { var numbers = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToArray(); for (int i = 0; i < numbers.Length; i++) { for (int sort = 0; sort < numbers.Length - 1; sort++) { var first = numbers[sort]; var second = numbers[sort + 1]; if (second < first) { numbers[sort] = second; numbers[sort + 1] = first; } } } Console.WriteLine(string.Join(" ", numbers)); } } }
27.166667
69
0.435583
[ "MIT" ]
1ooIL40/FundamentalsExtendetRepo
Array and List Algorithms - Lab/05. Sort Array Using Insertion Sort/SortArrayUsingInsertionSort.cs
980
C#
using System.Collections.Generic; using System.Drawing; using System.Linq; using TradeHub.Charts.GDI; using TradeHub.Charts.Interfaces; using TradeHub.Core.Model; namespace TradeHub.Charts.Modules { /// <summary> /// Base implementation of a static chart module. All static chart modules can derive from this class to benefit from its generic drawing methods. /// </summary> public class StaticChartModule { /// <summary> /// If set to true, the space between each tick will be represented by an integer. Otherwise, float will be used. /// In practice, when set to true each tick position will be rounded to the nearest pixel and whitespace might appear to the left or right of the chart data. /// When set to false the tick position will use all the available space and might overlap with other data or chart components. /// </summary> public const bool ROUND_SPACE_BETWEEN_DIV_X = false; public const int RIGHT_LEGEND_WIDTH = 62; // TODO: this should be calculated based on the longest price to display public const int RIGHT_LEGEND_DASH_LENGTH = 4; public const int BOTTOM_LEGEND_WIDTH = 20; public const int BOTTOM_LEGEND_DASH_LENGTH = 4; /// <summary> /// The StaticChart object hosting this module. Used to access chart properties such as width and style. /// </summary> public StaticChart parent; /// <summary> /// The overlays to draw on top of this module. /// </summary> public List<IChartOverlay> Overlays = new(); /// <summary> /// Spaces between divisions on the X axis. This is calculated using the number of ticks to display and the available width. /// </summary> public float spaceBetweenDivX; /// <summary> /// The height of the module. /// </summary> public int Height { get; set; } /// <summary> /// Draws the module on the Graphics drawing surface. /// </summary> public virtual void Draw(Graphics g) { spaceBetweenDivX = ROUND_SPACE_BETWEEN_DIV_X ? (int)(g.ClipBounds.Width - RIGHT_LEGEND_WIDTH - RIGHT_LEGEND_DASH_LENGTH) / parent.TickData.Ticks.Count() : (g.ClipBounds.Width - RIGHT_LEGEND_WIDTH - RIGHT_LEGEND_DASH_LENGTH) / parent.TickData.Ticks.Count(); DrawBorder(g); DrawYAxis(g); DrawXAxis(g); DrawData(g); DrawOverlays(g); } public void DrawBorder(Graphics g) { if (parent.ChartStyleOptions.ModulesBorderWidth == 0) { return; } DrawingHelper.DrawRectangle(g, parent.ChartStyleOptions.ModulesBorderColor, g.ClipBounds.X, g.ClipBounds.Y, g.ClipBounds.Width - 1, g.ClipBounds.Y + Height - 1); } public virtual void DrawXAxis(Graphics g) { return; } public virtual void DrawYAxis(Graphics g) { return; } public virtual void DrawData(Graphics g) { return; } public virtual void DrawOverlays(Graphics g) { return; } /// <summary> /// Prints an error message on the on the Graphics object. /// </summary> public virtual void DrawError(Graphics g, string message) { var f = new Font("Arial", 14, FontStyle.Regular, GraphicsUnit.World); var strSize = g.MeasureString(message, f); var msgPos = new PointF(g.ClipBounds.Width / 2 - strSize.Width / 2, g.ClipBounds.Height / 2 - strSize.Height / 2); DrawingHelper.DrawString(g, message, f, Brushes.Red, msgPos); } /// <summary> /// Translate a price into a vertical screen coordinate. /// </summary> /// <param name="price">The price.</param> /// <param name="yMin">The top of the drawing area.</param> /// <param name="yMax">The bottom of the drawing area.</param> /// <returns>Y coordinate to which the given price corresponds.</returns> public int WorldToScreen(TickList tickData, decimal price, int yMin, int yMax) { var range = tickData.Max - tickData.Min; var yProp = 1 - ((price - tickData.Min) / range); var yOffset = yProp * (yMax - yMin); return yMin + (int)yOffset; } } }
35.81746
173
0.603146
[ "MIT" ]
leboeuf/TradeHub-csharp
src/TradeHub.Charts/Modules/StaticChartModule.cs
4,515
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace UnsupervisedLearning.SelfOrganizingMaps.LearningRateFunctions { /// <summary> /// Essa implementação da função de taxa de aprendizado segue as sugestões propostas por Haykin no livro Redes Neurais: Princípios e Prática. /// /// </summary> public class LearningRateFunction : ILearningRateFunction { /// <summary> /// Taxa de aprendizado inicial. /// </summary> private double initial_learning_rate; /// <summary> /// Taxa de decaimento da função de taxa de aprendizado durante a fase de ordenação. /// </summary> private double time_constant; /// <summary> /// Limiar para transição para a fase de convergência. Após início da fase de convergência, este valor será sempre retornado /// como taxa de aprendizado. /// </summary> private double convergence_phase_threshold; /// <summary> /// Iteração em que o algoritmo passará da fase de ordenação para a fase de convergência. /// </summary> private int advance_phase_threshold; private string _print; public string print { get { if(string.IsNullOrWhiteSpace(_print)) _print = "lr_" + initial_learning_rate + time_constant; return _print; } } public double apply(int iteration) { if (iteration > advance_phase_threshold) return convergence_phase_threshold; return initial_learning_rate * Math.Exp(-(iteration / time_constant)); } /// <summary> /// Configura uma função de taxa de aprendizado com a taxa de aprendizado, constante de decaimento e limiar de transição de fase informados. /// </summary> public LearningRateFunction(double initialLearningRate, double timeConstant) { if (initialLearningRate <= 0) throw new InvalidOperationException("Taxa de aprendizado inicial deve ser maior que zero."); if (timeConstant <= 0) throw new InvalidOperationException("Constante de decaimento deve ser maior que zero."); initial_learning_rate = initialLearningRate; time_constant = timeConstant; convergence_phase_threshold = 0.01; advance_phase_threshold = (int)(- timeConstant * Math.Log(convergence_phase_threshold / initialLearningRate)); } /// <summary> /// Configura uma função de taxa de aprendizado com a taxa de aprendizado, constante de tempo e limiar de transição de fase sugeridos por /// Haykin em Redes Neurais: Princípios e Prática(taxa de aprendizado inical = 0.1; constante de tempo = 1000; limiar de transição de fase = 0.01) /// </summary> public LearningRateFunction() :this(0.1, 1000) { } } }
36.038462
150
0.697972
[ "MIT" ]
luisgandrade/TCCSharpRecSys
UnsupervisedLearning/SelfOrganizingMaps/LearningRateFunctions/LearningRateFunction.cs
2,849
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // // Microsoft Cognitive Services: http://www.microsoft.com/cognitive // // Microsoft Cognitive Services Github: // https://github.com/Microsoft/Cognitive // // Copyright (c) Microsoft Corporation // All rights reserved. // // MIT License: // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using Microsoft.ProjectOxford.Face.Contract; using System; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using System.Collections.Generic; using System.IO; using ServiceHelpers; // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236 namespace IntelligentKioskSample.Controls { public class EmotionFeedback { public string Text { get; set; } public SolidColorBrush AccentColor { get; set; } public string ImageFileName { get; set; } } public sealed partial class ImageWithFaceBorderUserControl : UserControl { public ImageWithFaceBorderUserControl() { this.InitializeComponent(); } public static readonly DependencyProperty DetectFacesOnLoadProperty = DependencyProperty.Register( "DetectFacesOnLoad", typeof(bool), typeof(ImageWithFaceBorderUserControl), new PropertyMetadata(false) ); public static readonly DependencyProperty ShowMultipleFacesProperty = DependencyProperty.Register( "ShowMultipleFaces", typeof(bool), typeof(ImageWithFaceBorderUserControl), new PropertyMetadata(false) ); public static readonly DependencyProperty PerformRecognitionProperty = DependencyProperty.Register( "PerformRecognition", typeof(bool), typeof(ImageWithFaceBorderUserControl), new PropertyMetadata(false) ); public static readonly DependencyProperty DetectFaceAttributesProperty = DependencyProperty.Register( "DetectFaceAttributes", typeof(bool), typeof(ImageWithFaceBorderUserControl), new PropertyMetadata(false) ); public static readonly DependencyProperty ShowRecognitionResultsProperty = DependencyProperty.Register( "ShowRecognitionResults", typeof(bool), typeof(ImageWithFaceBorderUserControl), new PropertyMetadata(false) ); public static readonly DependencyProperty ShowDialogOnApiErrorsProperty = DependencyProperty.Register( "ShowDialogOnApiErrors", typeof(bool), typeof(ImageWithFaceBorderUserControl), new PropertyMetadata(false) ); public static readonly DependencyProperty ShowEmotionRecognitionProperty = DependencyProperty.Register( "ShowEmotionRecognition", typeof(bool), typeof(ImageWithFaceBorderUserControl), new PropertyMetadata(false) ); public static readonly DependencyProperty BalloonBackgroundProperty = DependencyProperty.Register( "BalloonBackground", typeof(SolidColorBrush), typeof(ImageWithFaceBorderUserControl), new PropertyMetadata(null) ); public static readonly DependencyProperty BalloonForegroundProperty = DependencyProperty.Register( "BalloonForeground", typeof(SolidColorBrush), typeof(ImageWithFaceBorderUserControl), new PropertyMetadata(null) ); public static readonly DependencyProperty DetectFaceLandmarksProperty = DependencyProperty.Register( "DetectFaceLandmarks", typeof(bool), typeof(ImageWithFaceBorderUserControl), new PropertyMetadata(false) ); public SolidColorBrush BalloonBackground { get { return (SolidColorBrush)GetValue(BalloonBackgroundProperty); } set { SetValue(BalloonBackgroundProperty, (SolidColorBrush)value); } } public SolidColorBrush BalloonForeground { get { return (SolidColorBrush)GetValue(BalloonForegroundProperty); } set { SetValue(BalloonForegroundProperty, (SolidColorBrush)value); } } public bool ShowEmotionRecognition { get { return (bool)GetValue(ShowEmotionRecognitionProperty); } set { SetValue(ShowEmotionRecognitionProperty, (bool)value); } } public bool ShowMultipleFaces { get { return (bool)GetValue(ShowMultipleFacesProperty); } set { SetValue(ShowMultipleFacesProperty, (bool)value); } } public bool DetectFacesOnLoad { get { return (bool)GetValue(DetectFacesOnLoadProperty); } set { SetValue(DetectFacesOnLoadProperty, (bool)value); } } public bool DetectFaceAttributes { get { return (bool)GetValue(DetectFaceAttributesProperty); } set { SetValue(DetectFaceAttributesProperty, (bool)value); } } public bool PerformRecognition { get { return (bool)GetValue(PerformRecognitionProperty); } set { SetValue(PerformRecognitionProperty, (bool)value); } } public bool ShowRecognitionResults { get { return (bool)GetValue(ShowRecognitionResultsProperty); } set { SetValue(ShowRecognitionResultsProperty, (bool)value); } } public bool ShowDialogOnApiErrors { get { return (bool)GetValue(ShowDialogOnApiErrorsProperty); } set { SetValue(ShowDialogOnApiErrorsProperty, (bool)value); } } public bool DetectFaceLandmarks { get { return (bool)GetValue(DetectFaceLandmarksProperty); } set { SetValue(DetectFaceLandmarksProperty, (bool)value); } } private async void OnDataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args) { ImageAnalyzer dataContext = this.DataContext as ImageAnalyzer; foreach (var child in this.hostGrid.Children.Where(c => !(c is Image)).ToArray()) { this.hostGrid.Children.Remove(child); } // remove the current source this.bitmapImage.UriSource = null; if (dataContext != null) { try { if (dataContext.ImageUrl != null) { this.bitmapImage.UriSource = new Uri(dataContext.ImageUrl); } else if (dataContext.GetImageStreamCallback != null) { await this.bitmapImage.SetSourceAsync((await dataContext.GetImageStreamCallback()).AsRandomAccessStream()); } } catch (Exception ex) { // If we fail to load the image we will just not display it this.bitmapImage.UriSource = null; if (this.ShowDialogOnApiErrors) { await Util.GenericApiCallExceptionHandler(ex, "Error loading captured image."); } } } } private async Task DetectAndShowFaceBorders() { this.progressIndicator.IsActive = true; foreach (var child in this.hostGrid.Children.Where(c => !(c is Image)).ToArray()) { this.hostGrid.Children.Remove(child); } ImageAnalyzer imageWithFace = this.DataContext as ImageAnalyzer; if (imageWithFace != null) { if (imageWithFace.DetectedFaces == null) { await imageWithFace.DetectFacesAsync(detectFaceAttributes: this.DetectFaceAttributes, detectFaceLandmarks: this.DetectFaceLandmarks); } double renderedImageXTransform = this.imageControl.RenderSize.Width / this.bitmapImage.PixelWidth; double renderedImageYTransform = this.imageControl.RenderSize.Height / this.bitmapImage.PixelHeight; foreach (Face face in imageWithFace.DetectedFaces) { FaceIdentificationBorder faceUI = new FaceIdentificationBorder() { Tag = face.FaceId, }; faceUI.Margin = new Thickness((face.FaceRectangle.Left * renderedImageXTransform) + ((this.ActualWidth - this.imageControl.RenderSize.Width) / 2), (face.FaceRectangle.Top * renderedImageYTransform) + ((this.ActualHeight - this.imageControl.RenderSize.Height) / 2), 0, 0); faceUI.BalloonBackground = this.BalloonBackground; faceUI.BalloonForeground = this.BalloonForeground; faceUI.ShowFaceRectangle(face.FaceRectangle.Width * renderedImageXTransform, face.FaceRectangle.Height * renderedImageYTransform); if (this.DetectFaceLandmarks) { faceUI.ShowFaceLandmarks(renderedImageXTransform, renderedImageYTransform, face); } this.hostGrid.Children.Add(faceUI); if (!this.ShowMultipleFaces) { break; } } if (this.PerformRecognition) { if (imageWithFace.IdentifiedPersons == null) { await imageWithFace.IdentifyFacesAsync(); } if (this.ShowRecognitionResults) { foreach (Face face in imageWithFace.DetectedFaces) { // Get the border for the associated face id FaceIdentificationBorder faceUI = (FaceIdentificationBorder)this.hostGrid.Children.FirstOrDefault(e => e is FaceIdentificationBorder && (Guid)(e as FaceIdentificationBorder).Tag == face.FaceId); if (faceUI != null) { IdentifiedPerson faceIdIdentification = imageWithFace.IdentifiedPersons.FirstOrDefault(p => p.FaceId == face.FaceId); string name = this.DetectFaceAttributes && faceIdIdentification != null ? faceIdIdentification.Person.Name : null; string gender = this.DetectFaceAttributes ? face.FaceAttributes.Gender : null; double age = this.DetectFaceAttributes ? face.FaceAttributes.Age : 0; double confidence = this.DetectFaceAttributes && faceIdIdentification != null ? faceIdIdentification.Confidence : 0; faceUI.ShowIdentificationData(age, gender, (uint)Math.Round(confidence * 100), name); } } } } } this.progressIndicator.IsActive = false; } private async Task DetectAndShowEmotion() { this.progressIndicator.IsActive = true; foreach (var child in this.hostGrid.Children.Where(c => !(c is Image)).ToArray()) { this.hostGrid.Children.Remove(child); } ImageAnalyzer imageWithFace = this.DataContext as ImageAnalyzer; if (imageWithFace != null) { if (imageWithFace.DetectedFaces == null) { await imageWithFace.DetectFacesAsync(); } double renderedImageXTransform = this.imageControl.RenderSize.Width / this.bitmapImage.PixelWidth; double renderedImageYTransform = this.imageControl.RenderSize.Height / this.bitmapImage.PixelHeight; foreach (Face face in imageWithFace.DetectedFaces) { FaceIdentificationBorder faceUI = new FaceIdentificationBorder(); faceUI.Margin = new Thickness((face.FaceRectangle.Left * renderedImageXTransform) + ((this.ActualWidth - this.imageControl.RenderSize.Width) / 2), (face.FaceRectangle.Top * renderedImageYTransform) + ((this.ActualHeight - this.imageControl.RenderSize.Height) / 2), 0, 0); faceUI.BalloonBackground = this.BalloonBackground; faceUI.BalloonForeground = this.BalloonForeground; faceUI.ShowFaceRectangle(face.FaceRectangle.Width * renderedImageXTransform, face.FaceRectangle.Height * renderedImageYTransform); faceUI.ShowEmotionData(face.FaceAttributes.Emotion); this.hostGrid.Children.Add(faceUI); if (!this.ShowMultipleFaces) { break; } } } this.progressIndicator.IsActive = false; } private async Task PreviewImageFaces() { if (!this.DetectFacesOnLoad || this.progressIndicator.IsActive) { return; } ImageAnalyzer img = this.DataContext as ImageAnalyzer; if (img != null) { img.UpdateDecodedImageSize(this.bitmapImage.PixelHeight, this.bitmapImage.PixelWidth); } if (this.ShowEmotionRecognition) { await this.DetectAndShowEmotion(); } else if (this.DetectFaceAttributes) { await this.DetectAndShowFaceBorders(); } } private async void OnBitmapImageOpened(object sender, RoutedEventArgs e) { await PreviewImageFaces(); } private async void OnImageSizeChanged(object sender, SizeChangedEventArgs e) { await this.PreviewImageFaces(); } } }
38.967581
222
0.592538
[ "MIT" ]
CCalanni/src
RaspberryPiKiosk/Controls/ImageWithFaceBorderUserControl.xaml.cs
15,628
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Data.Common; using Microsoft.SqlTools.ServiceLayer.Connection.Contracts; using Microsoft.SqlTools.Utility; namespace Microsoft.SqlTools.ServiceLayer.Connection { /// <summary> /// Information pertaining to a unique connection instance. /// </summary> public class ConnectionInfo { /// <summary> /// Constructor /// </summary> public ConnectionInfo(ISqlConnectionFactory factory, string ownerUri, ConnectionDetails details) { Factory = factory; OwnerUri = ownerUri; ConnectionDetails = details; ConnectionId = Guid.NewGuid(); IntellisenseMetrics = new InteractionMetrics<double>(new int[] {50, 100, 200, 500, 1000, 2000}); } /// <summary> /// Unique Id, helpful to identify a connection info object /// </summary> public Guid ConnectionId { get; private set; } /// <summary> /// URI identifying the owner/user of the connection. Could be a file, service, resource, etc. /// </summary> public string OwnerUri { get; private set; } /// <summary> /// Factory used for creating the SQL connection associated with the connection info. /// </summary> public ISqlConnectionFactory Factory { get; private set; } /// <summary> /// Properties used for creating/opening the SQL connection. /// </summary> public ConnectionDetails ConnectionDetails { get; private set; } /// <summary> /// A map containing all connections to the database that are associated with /// this ConnectionInfo's OwnerUri. /// This is internal for testing access only /// </summary> internal readonly ConcurrentDictionary<string, DbConnection> ConnectionTypeToConnectionMap = new ConcurrentDictionary<string, DbConnection>(); /// <summary> /// Intellisense Metrics /// </summary> public InteractionMetrics<double> IntellisenseMetrics { get; private set; } /// <summary> /// Returns true if the db connection is to any cloud instance /// </summary> public bool IsCloud { get; set; } /// <summary> /// Returns true if the db connection is to a SQL db instance /// </summary> public bool IsSqlDb { get; set; } /// Returns true if the sql connection is to a DW instance /// </summary> public bool IsSqlDW { get; set; } /// <summary> /// Returns the major version number of the db we are connected to /// </summary> public int MajorVersion { get; set; } /// <summary> /// All DbConnection instances held by this ConnectionInfo /// </summary> public ICollection<DbConnection> AllConnections { get { return ConnectionTypeToConnectionMap.Values; } } /// <summary> /// All connection type strings held by this ConnectionInfo /// </summary> /// <returns></returns> public ICollection<string> AllConnectionTypes { get { return ConnectionTypeToConnectionMap.Keys; } } public bool HasConnectionType(string connectionType) { connectionType = connectionType ?? ConnectionType.Default; return ConnectionTypeToConnectionMap.ContainsKey(connectionType); } /// <summary> /// The count of DbConnectioninstances held by this ConnectionInfo /// </summary> public int CountConnections { get { return ConnectionTypeToConnectionMap.Count; } } /// <summary> /// Try to get the DbConnection associated with the given connection type string. /// </summary> /// <returns>true if a connection with type connectionType was located and out connection was set, /// false otherwise </returns> /// <exception cref="ArgumentException">Thrown when connectionType is null or empty</exception> public bool TryGetConnection(string connectionType, out DbConnection connection) { Validate.IsNotNullOrEmptyString("Connection Type", connectionType); return ConnectionTypeToConnectionMap.TryGetValue(connectionType, out connection); } /// <summary> /// Adds a DbConnection to this object and associates it with the given /// connection type string. If a connection already exists with an identical /// connection type string, it is not overwritten. Ignores calls where connectionType = null /// </summary> /// <exception cref="ArgumentException">Thrown when connectionType is null or empty</exception> public void AddConnection(string connectionType, DbConnection connection) { Validate.IsNotNullOrEmptyString("Connection Type", connectionType); ConnectionTypeToConnectionMap.TryAdd(connectionType, connection); } /// <summary> /// Removes the single DbConnection instance associated with string connectionType /// </summary> /// <exception cref="ArgumentException">Thrown when connectionType is null or empty</exception> public void RemoveConnection(string connectionType) { Validate.IsNotNullOrEmptyString("Connection Type", connectionType); DbConnection connection; ConnectionTypeToConnectionMap.TryRemove(connectionType, out connection); } /// <summary> /// Removes all DbConnection instances held by this object /// </summary> public void RemoveAllConnections() { foreach (var type in AllConnectionTypes) { DbConnection connection; ConnectionTypeToConnectionMap.TryRemove(type, out connection); } } } }
36.889535
108
0.615603
[ "MIT" ]
Bhaskers-Blu-Org2/sqltoolsservice
src/Microsoft.SqlTools.ServiceLayer/Connection/ConnectionInfo.cs
6,345
C#
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using Scriban.Parsing; namespace Scriban.Liquid2Scriban { class Program { static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("liquid2scriban.exe [--relaxed-include] <files...> "); Console.WriteLine(" Converts input Liquid files to Scriban files. Write result to input file + `.sbnXXX` extension where XXX is the original extension"); Console.WriteLine(); Console.WriteLine(" <files> can be a wildcard **.htm (for recursive, or *.htm) for not recursive"); Console.WriteLine(); Console.WriteLine(" --relaxed-include Parse liquid include parameter as a string without quotes"); Environment.Exit(1); return; } var files = new List<string>(); bool relaxedInclude = false; for (var i = 0; i < args.Length; i++) { var arg = args[i]; if (arg == "--relaxed-include") { relaxedInclude = true; } else if (arg.IndexOf("**") >= 0) { var index = arg.IndexOf("**"); var previousdir = arg.Substring(0, index); var pattern = arg.Substring(index + 1); if (pattern.Contains("/") || pattern.Contains("\\")) { Console.WriteLine($"Error the pattern: `{pattern}` cannot contain /, \\"); Environment.Exit(1); return; } var rootDir = Path.Combine(Environment.CurrentDirectory, previousdir); foreach (var file in Directory.GetFiles(rootDir, pattern, SearchOption.AllDirectories)) { files.Add(Path.Combine(rootDir, file)); } } else if (arg.IndexOf("*") >= 0) { var index = arg.IndexOf("*"); var previousdir = arg.Substring(0, index); var pattern = arg.Substring(index); if (pattern.Contains("/") || pattern.Contains("\\")) { Console.WriteLine($"Error the pattern: `{pattern}` cannot contain /, \\"); Environment.Exit(1); return; } var rootDir = Path.Combine(Environment.CurrentDirectory, previousdir); foreach (var file in Directory.GetFiles(rootDir, pattern)) { files.Add(Path.Combine(rootDir, file)); } } else { files.Add(Path.Combine(Environment.CurrentDirectory, arg)); } } foreach (var file in files) { var text = File.ReadAllText(file); var template = Template.ParseLiquid(text, file, lexerOptions: new LexerOptions() {Mode = ScriptMode.Liquid, KeepTrivia = true, EnableIncludeImplicitString = relaxedInclude }); if (template.HasErrors) { DumpMessages(template, "parsing the liquid template", file); } else { var scriban = template.ToText(); var extension = Path.GetExtension(file); if (!string.IsNullOrEmpty(extension)) { extension = ".sbn" + extension.Substring(1); } else { extension = ".sbn"; } var outputFile = Path.ChangeExtension(file, extension); File.WriteAllText(outputFile, scriban); var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"Scriban file generated: {outputFile}"); Console.ForegroundColor = color; // Try to reparse the generated template to verify that we don't have any errors var newTemplate = Template.Parse(scriban, outputFile); if (newTemplate.HasErrors) { DumpMessages(template, "verifying the generated scriban template", outputFile); } } } } private static void DumpMessages(Template template, string parsingContext, string file) { if (template.HasErrors) { Console.WriteLine($"Error while {parsingContext}: {file}"); foreach (var message in template.Messages) { var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(" " + message); Console.ForegroundColor = color; } } } } }
41.734848
191
0.475041
[ "BSD-2-Clause" ]
Guria/scriban
src/liquid2scriban/Program.cs
5,509
C#
using System; namespace ContosoAir.Clients { public static class GlobalSettings { public const string ContosoAirEndpoint = "https://contosoairprod-api-mtczerocfa.azurewebsites.net/"; public const string AuthenticationTokenEndpoint = "https://api.cognitive.microsoft.com/sts/v1.0"; public const string SpeechRecognitionEndpoint = "https://speech.platform.bing.com/recognize"; public const string SkypeBotAccount = "28:XXXXXXXXXX"; public const string CognitiveServicesKey = "8475871faed346eda4abc75ae27dd88d"; //8475871faed346eda4abc75ae27dd88d public const string BingSpeechApiKey = "e4d4520cc2d1442d89debbbb1d9909e0";//e4d4520cc2d1442d89debbbb1d9909e0 public const string AudioContentType = @"audio/wav; codec=""audio/pcm""; samplerate=16000"; public const string AudioFilename = "ContosoAir.wav"; public const int DefaultDelayedTime = 20; // in seconds public const int DefaultFeedbackTime = 120; // in seconds // Default DateTime in views public static readonly DateTime MyTripsDepartDate = new DateTime(2017, 4, 4); // Azure B2C settings public const string ClientId = "8db29c10-50c7-416f-b1c9-795c9592ab4e"; public static string Authority = "https://login.microsoftonline.com/"; public const string Tenant = "onemtcb2c.onmicrosoft.com"; public const string SignUpSignInPolicy = "B2C_1_Contosoair"; // Azure Push Notification public const string NotificationHubConnectionString = "Endpoint=sb://contosoairprod-notification-nsmtczerocfa.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=ggKKtrwjK1rQHxv06FMUh/moZSUjbn1BsZEWMJfC5iA="; public const string NotificationHubName = "contosoairprodnotification-hub"; // HockeyApp public const string HockeyAppiOS = "c5564727a8d94d99b6e8e51505842fd8"; public const string HockeyAppAndroid = "a24b7677201a48a38f9ad1e0eec7fc90"; public const string HockeyAppUWP = "89e906b5e04e43d396971aa9e6d4361f"; // Android public const string AndroidProjectNumber = ""; public const string AndroidPackageId = "com.contoso.air"; } }
54.707317
259
0.738297
[ "MIT" ]
Microsoft/developer-immersion-data
source/sp-gda/gdaexpericence7/ContosoAir/src/ContosoAir.Clients/GlobalSettings.cs
2,245
C#
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // 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. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Egl { /// <summary> /// [EGL] Value of EGL_SOCKET_TYPE_UNIX_NV symbol. /// </summary> [RequiredByFeature("EGL_NV_stream_socket_unix")] public const int SOCKET_TYPE_UNIX_NV = 0x324E; } }
32.888889
81
0.765203
[ "MIT" ]
GiantBlargg/OpenGL.Net
OpenGL.Net/NV/Egl.NV_stream_socket_unix.cs
1,776
C#
// <auto-generated /> using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using NodaTime; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; using Sorigin; namespace Sorigin.Migrations { [DbContext(typeof(SoriginContext))] [Migration("20211029211201_RefreshTokens")] partial class RefreshTokens { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 63) .HasAnnotation("ProductVersion", "5.0.10") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); modelBuilder.Entity("Sorigin.Models.Platforms.DiscordUser", b => { b.Property<string>("Id") .HasColumnType("text") .HasColumnName("id"); b.Property<string>("Avatar") .IsRequired() .HasColumnType("text") .HasColumnName("avatar"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("text") .HasColumnName("discriminator"); b.Property<string>("Username") .IsRequired() .HasColumnType("text") .HasColumnName("username"); b.HasKey("Id") .HasName("pk_discord_user"); b.ToTable("discord_user"); }); modelBuilder.Entity("Sorigin.Models.Platforms.SteamUser", b => { b.Property<string>("Id") .HasColumnType("text") .HasColumnName("id"); b.Property<string>("Avatar") .IsRequired() .HasColumnType("text") .HasColumnName("avatar"); b.Property<string>("Username") .IsRequired() .HasColumnType("text") .HasColumnName("username"); b.HasKey("Id") .HasName("pk_steam_user"); b.ToTable("steam_user"); }); modelBuilder.Entity("Sorigin.Models.RefreshToken", b => { b.Property<string>("Value") .HasColumnType("text") .HasColumnName("value"); b.Property<Instant>("Created") .HasColumnType("timestamp") .HasColumnName("created"); b.Property<Instant>("Expiration") .HasColumnType("timestamp") .HasColumnName("expiration"); b.Property<Guid>("UserID") .HasColumnType("uuid") .HasColumnName("user_id"); b.HasKey("Value") .HasName("pk_refresh_tokens"); b.HasIndex("UserID") .HasDatabaseName("ix_refresh_tokens_user_id"); b.HasIndex("Value") .HasDatabaseName("ix_refresh_tokens_value"); b.ToTable("refresh_tokens"); }); modelBuilder.Entity("Sorigin.Models.Transfer", b => { b.Property<Guid>("ID") .ValueGeneratedOnAdd() .HasColumnType("uuid") .HasColumnName("id"); b.Property<Guid>("TransferID") .HasColumnType("uuid") .HasColumnName("transfer_id"); b.HasKey("ID") .HasName("pk_transfers"); b.HasIndex("ID") .HasDatabaseName("ix_transfers_id"); b.HasIndex("TransferID") .HasDatabaseName("ix_transfers_transfer_id"); b.ToTable("transfers"); }); modelBuilder.Entity("Sorigin.Models.User", b => { b.Property<Guid>("ID") .ValueGeneratedOnAdd() .HasColumnType("uuid") .HasColumnName("id"); b.Property<string>("Bio") .HasColumnType("text") .HasColumnName("bio"); b.Property<string>("DiscordId") .HasColumnType("text") .HasColumnName("discord_id"); b.Property<int>("GamePlatform") .HasColumnType("integer") .HasColumnName("game_platform"); b.Property<int>("Role") .HasColumnType("integer") .HasColumnName("role"); b.Property<string>("SteamId") .HasColumnType("text") .HasColumnName("steam_id"); b.Property<List<Guid>>("Transfers") .HasColumnType("uuid[]") .HasColumnName("transfers"); b.Property<string>("Username") .IsRequired() .HasColumnType("text") .HasColumnName("username"); b.HasKey("ID") .HasName("pk_users"); b.HasIndex("DiscordId") .HasDatabaseName("ix_users_discord_id"); b.HasIndex("ID") .HasDatabaseName("ix_users_id"); b.HasIndex("SteamId") .HasDatabaseName("ix_users_steam_id"); b.HasIndex("Username") .HasDatabaseName("ix_users_username"); b.ToTable("users"); }); modelBuilder.Entity("Sorigin.Models.RefreshToken", b => { b.HasOne("Sorigin.Models.User", null) .WithMany("Tokens") .HasForeignKey("UserID") .HasConstraintName("fk_refresh_tokens_users_user_id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Sorigin.Models.User", b => { b.HasOne("Sorigin.Models.Platforms.DiscordUser", "Discord") .WithMany() .HasForeignKey("DiscordId") .HasConstraintName("fk_users_discord_user_discord_id"); b.HasOne("Sorigin.Models.Platforms.SteamUser", "Steam") .WithMany() .HasForeignKey("SteamId") .HasConstraintName("fk_users_steam_user_steam_id"); b.Navigation("Discord"); b.Navigation("Steam"); }); modelBuilder.Entity("Sorigin.Models.User", b => { b.Navigation("Tokens"); }); #pragma warning restore 612, 618 } } }
35.557604
120
0.4479
[ "MIT" ]
ProjectSIRA/Sorigin
Sorigin/Migrations/20211029211201_RefreshTokens.Designer.cs
7,718
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; using UnityEditor; namespace HighlightPlus { public class TransparentWithDepth { static Material bmDepthOnly; [MenuItem ("GameObject/Effects/Highlight Plus/Add Depth To Transparent Object", false, 100)] static void AddDepthOption () { Renderer renderer = GetRenderer (); if (renderer == null) return; if (!EditorUtility.DisplayDialog ("Add Depth To Transparent Object", "This option will force the transparent object to write to the depth buffer by adding a new special material to the renderer (existing materials are preserved) so it can occlude and allow See-Through effect.\nOnly use on transparent objects.\n\nProceed?", "Yes", "No")) { return; } Material[] materials = renderer.sharedMaterials; for (int k = 0; k < materials.Length; k++) { if (materials [k] == bmDepthOnly) { EditorUtility.DisplayDialog ("Depth Support", "Already set! Nothing to do.", "Ok"); return; } } if (materials == null) { renderer.sharedMaterial = bmDepthOnly; } else { List<Material> newMaterials = new List<Material> (materials); newMaterials.Insert (0, bmDepthOnly); renderer.sharedMaterials = newMaterials.ToArray (); } } [MenuItem ("GameObject/Effects/Highlight Plus/Remove Depth Compatibility", false, 101)] static void RemoveDepthOption () { Renderer renderer = GetRenderer (); if (renderer == null) return; Material[] materials = renderer.sharedMaterials; for (int k = 0; k < materials.Length; k++) { if (materials [k] == bmDepthOnly) { List<Material> newMaterials = new List<Material> (renderer.sharedMaterials); newMaterials.RemoveAt (k); renderer.sharedMaterials = newMaterials.ToArray (); return; } } for (int k = 0; k < materials.Length; k++) { if (materials [k] == bmDepthOnly) { EditorUtility.DisplayDialog ("Depth Support", "This object was not previously modified! Nothing to do.", "Ok"); return; } } } static Renderer GetRenderer () { if (Selection.activeGameObject == null) { EditorUtility.DisplayDialog ("Depth Support", "This option can only be used on GameObjects.", "Ok"); return null; } Renderer renderer = Selection.activeGameObject.GetComponent<Renderer> (); if (renderer == null) { EditorUtility.DisplayDialog ("Depth Support", "This option can only be used on GameObjects with a Renderer component attached.", "Ok"); return null; } if (bmDepthOnly == null) { bmDepthOnly = Resources.Load<Material> ("HighlightPlus/HighlightPlusDepthWrite"); if (bmDepthOnly == null) { EditorUtility.DisplayDialog ("Depth Support", "HighlightPlusDepthWrite material not found!", "Ok"); return null; } } return renderer; } } }
31.217391
343
0.685585
[ "Apache-2.0" ]
ArtemkaKun/4exp-gamejam
Assets/External/HighlightPlus/Editor/TransparentWithDepth.cs
2,872
C#
using System; using System.Collections.Generic; using CleanThatCode.Community.Models.Entities; using System.Globalization; namespace CleanThatCode.Community.Tests.Mocks { public static class FakeData { public static IEnumerable<Post> Posts { get { return new List<Post> { new Post { Id = 1, Title = "Thundercats Unite!", Author = "Lion-O", Message = "My fellow cats, good job on the last mission were we took care of that old guy Mum-Ra. I will be waiting for you guys at the cave.", Created = DateTime.ParseExact("08/14/2016 13:22:15", "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture), NumberOfLikes = 5 }, new Post { Id = 2, Title = "Castle Grayskull is open for business", Author = "He-Man", Message = "Business hasn't been booming, so I've deciced to turn Castle Grayskull to a hotel and is currently open for business!", Created = DateTime.ParseExact("08/14/2016 13:22:15", "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture), NumberOfLikes = 112 }, new Post { Id = 3, Title = "Castle Grayskull has been closed for business.....", Author = "He-Man", Message = "Skeletor has ruined me.......", Created = DateTime.ParseExact("08/14/2016 13:22:15", "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture), NumberOfLikes = 1 }, new Post { Id = 4, Title = "Beetlejuice 2 is out", Author = "Warner Bros.", Message = "Beetlejuice 2 is now out! All original cast!", Created = DateTime.ParseExact("08/14/2016 13:22:15", "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture), NumberOfLikes = 992 } }; } } public static IEnumerable<Comment> Comments { get { return new List<Comment> { new Comment { Id = 1, PostId = 1, Author = "Mum-Ra", Message = "I will eventually get you Lion-O! Just you wait.... Just you wait!", Created = DateTime.ParseExact("08/14/2016 13:22:15", "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture) }, new Comment { Id = 2, PostId = 1, Author = "Lion-O", Message = "Mum-Ra! You have been trying for years without success. I am not scared of you!", Created = DateTime.ParseExact("08/14/2016 13:22:15", "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture) } }; } } } }
42.585366
167
0.428694
[ "MIT" ]
eggertmar1/T-514-VEFT
Class_2/template 2/CleanThatCode.Community.Tests/Mocks/FakeData.cs
3,492
C#
using GitVersion.Common; using GitVersion.Configuration; using GitVersion.Extensions; using GitVersion.Model.Configuration; namespace GitVersion.VersionCalculation; /// <summary> /// Active only when the branch is marked as IsDevelop. /// Two different algorithms (results are merged): /// <para> /// Using <see cref="VersionInBranchNameVersionStrategy"/>: /// Version is that of any child branches marked with IsReleaseBranch (except if they have no commits of their own). /// BaseVersionSource is the commit where the child branch was created. /// Always increments. /// </para> /// <para> /// Using <see cref="TaggedCommitVersionStrategy"/>: /// Version is extracted from all tags on the <c>main</c> branch which are valid. /// BaseVersionSource is the tag's commit (same as base strategy). /// Increments if the tag is not the current commit (same as base strategy). /// </para> /// </summary> public class TrackReleaseBranchesVersionStrategy : VersionStrategyBase { private readonly IRepositoryStore repositoryStore; private readonly VersionInBranchNameVersionStrategy releaseVersionStrategy; private readonly TaggedCommitVersionStrategy taggedCommitVersionStrategy; public TrackReleaseBranchesVersionStrategy(IRepositoryStore repositoryStore, Lazy<GitVersionContext> versionContext) : base(versionContext) { this.repositoryStore = repositoryStore.NotNull(); this.releaseVersionStrategy = new VersionInBranchNameVersionStrategy(repositoryStore, versionContext); this.taggedCommitVersionStrategy = new TaggedCommitVersionStrategy(repositoryStore, versionContext); } public override IEnumerable<BaseVersion> GetVersions() { if (Context.Configuration?.TracksReleaseBranches == true) { return ReleaseBranchBaseVersions().Union(MainTagsVersions()); } return Array.Empty<BaseVersion>(); } private IEnumerable<BaseVersion> MainTagsVersions() { var main = this.repositoryStore.FindBranch(Config.MainBranchKey); return main != null ? this.taggedCommitVersionStrategy.GetTaggedVersions(main, null) : Array.Empty<BaseVersion>(); } private IEnumerable<BaseVersion> ReleaseBranchBaseVersions() { var releaseBranchConfig = Context.FullConfiguration?.GetReleaseBranchConfig(); if (releaseBranchConfig.Any()) { var releaseBranches = this.repositoryStore.GetReleaseBranches(releaseBranchConfig); return releaseBranches .SelectMany(b => GetReleaseVersion(Context, b)) .Select(baseVersion => { // Need to drop branch overrides and give a bit more context about // where this version came from var source1 = "Release branch exists -> " + baseVersion.Source; return new BaseVersion(source1, baseVersion.ShouldIncrement, baseVersion.SemanticVersion, baseVersion.BaseVersionSource, null); }) .ToList(); } return Array.Empty<BaseVersion>(); } private IEnumerable<BaseVersion> GetReleaseVersion(GitVersionContext context, IBranch releaseBranch) { var tagPrefixRegex = context.Configuration?.GitTagPrefix; // Find the commit where the child branch was created. var baseSource = this.repositoryStore.FindMergeBase(releaseBranch, context.CurrentBranch); if (Equals(baseSource, context.CurrentCommit)) { // Ignore the branch if it has no commits. return Array.Empty<BaseVersion>(); } return this.releaseVersionStrategy .GetVersions(tagPrefixRegex, releaseBranch) .Select(b => new BaseVersion(b.Source, true, b.SemanticVersion, baseSource, b.BranchNameOverride)); } }
39.848485
122
0.68289
[ "MIT" ]
velkovb/GitVersion
src/GitVersion.Core/VersionCalculation/BaseVersionCalculators/TrackReleaseBranchesVersionStrategy.cs
3,945
C#
#region usings using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; #endregion namespace ServerManager.BackgroundService { public abstract class BackgroundService : IHostedService { private readonly CancellationTokenSource _stoppingCts = new CancellationTokenSource(); private Task _executingTask; public virtual Task StartAsync(CancellationToken cancellationToken) { // Store the task we're executing _executingTask = ExecuteAsync(_stoppingCts.Token); // If the task is completed then return it, // this will bubble cancellation and failure to the caller if (_executingTask.IsCompleted) { return _executingTask; } // Otherwise it's running return Task.CompletedTask; } public virtual async Task StopAsync(CancellationToken cancellationToken) { // Stop called without start if (_executingTask == null) { return; } try { // Signal cancellation to the executing method _stoppingCts.Cancel(); } finally { // Wait until the task completes or the stop token triggers await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken)); } } protected virtual async Task ExecuteAsync(CancellationToken stoppingToken) { //stoppingToken.Register(() => // _logger.LogDebug($" GracePeriod background task is stopping.")); do { await Process(); await Task.Delay(5000, stoppingToken); //5 seconds delay } while (!stoppingToken.IsCancellationRequested); } protected abstract Task Process(); } }
22.757143
77
0.719397
[ "BSD-3-Clause" ]
L3tum/ServerManager
ServerManager/BackgroundService/BackgroundService.cs
1,595
C#
using System; namespace TDD.PokerHandsChecker.IsFourOfAKind.PokerDemo { public class PokerHandsChecker : IPokerHandsChecker { public bool IsValidHand(IHand hand) { throw new NotImplementedException(); } public bool IsStraightFlush(IHand hand) { throw new NotImplementedException(); } public bool IsFourOfAKind(IHand hand) { var handCards = hand.Cards; if (handCards.Count != 5) { return false; } for (var i = 0; i < handCards.Count; i += 5) { var firstCard = handCards[i]; var secondCard = handCards[i + 1]; var thirdCard = handCards[i + 2]; var fourthCard = handCards[i + 3]; if (firstCard.Suit != secondCard.Suit && secondCard.Suit != thirdCard.Suit && thirdCard.Suit != fourthCard.Suit && secondCard.Face == firstCard.Face && thirdCard.Face == secondCard.Face && fourthCard.Face == thirdCard.Face) { return true; } } return false; } public bool IsFullHouse(IHand hand) { throw new NotImplementedException(); } public bool IsFlush(IHand hand) { throw new NotImplementedException(); } public bool IsStraight(IHand hand) { throw new NotImplementedException(); } public bool IsThreeOfAKind(IHand hand) { throw new NotImplementedException(); } public bool IsTwoPair(IHand hand) { throw new NotImplementedException(); } public bool IsOnePair(IHand hand) { throw new NotImplementedException(); } public bool IsHighCard(IHand hand) { throw new NotImplementedException(); } public int CompareHands(IHand firstHand, IHand secondHand) { throw new NotImplementedException(); } } }
26.47619
66
0.503147
[ "MIT" ]
zdzdz/High-Quality-Code-HW
12. Test-Driven-Development-HW/TDD.PokerHandsChecker.IsFourOfAKind/PokerDemo/PokerHandsChecker.cs
2,226
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.Lex")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Lex Runtime Service. Amazon Lex is a service for building conversational interactions into any application using voice or text.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.3.104.9")]
46.3125
214
0.751012
[ "Apache-2.0" ]
gbent/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/Lex/Properties/AssemblyInfo.cs
1,482
C#
using System; using System.Collections.Generic; using System.Management.Automation; using Microsoft.SharePoint.Client; namespace SharePointPnP.PowerShell.Commands.Provider { internal class SPODriveInfo : PSDriveInfo { public Web Web { get; set; } internal int ItemTimeout { get; set; } internal int WebTimeout { get; set; } internal List<SPODriveCacheItem> CachedItems { get; set; } internal List<SPODriveCacheWeb> CachedWebs { get; set; } public SPODriveInfo(PSDriveInfo driveInfo) : base(driveInfo) { CachedItems = new List<SPODriveCacheItem>(); CachedWebs = new List<SPODriveCacheWeb>(); } } }
31.727273
68
0.669054
[ "MIT" ]
andreashebeisen/PnP-PowerShell
Commands/Provider/SPODriveInfo.cs
698
C#
using System; using Windows.UI.Notifications; using JetBrains.Annotations; namespace WebsitePoller.Workflow { public sealed class ToastNotifierWrapper : IToastNotifier { public ToastNotifierWrapper([NotNull]ToastNotifier toastNotifier) { ToastNotifier = toastNotifier ?? throw new ArgumentNullException(nameof(toastNotifier)); } [NotNull] public ToastNotifier ToastNotifier { get; } public void Show([NotNull]ToastNotification notification) { if(notification == null) throw new ArgumentNullException(nameof(notification)); ToastNotifier.Show(notification); } } }
29.434783
100
0.6839
[ "MIT" ]
MovGP0/WebsitePoller
WebsitePoller/Workflow/ToastNotifierWrapper.cs
677
C#
namespace Algorithms.Test { using System; using System.Linq; internal class AssertionsTest { static void Main() { int[] arr = new int[] { 3, -1, 15, 4, 17, 2, 33, 0 }; Console.WriteLine("arr = [{0}]", string.Join(", ", arr)); SortingAlgorithms.SelectionSort(arr); Console.WriteLine("sorted = [{0}]", string.Join(", ", arr)); //int[] nullArray = null; //SortingAlgorithms.SelectionSort(nullArray); // Test sorting null array //SortingAlgorithms.SelectionSort(new int[0]); // Test sorting empty array SortingAlgorithms.SelectionSort(new int[1]); // Test sorting single element array Console.WriteLine(SearchingAlgorithms.BinarySearch(arr, -1000)); Console.WriteLine(SearchingAlgorithms.BinarySearch(arr, 0)); Console.WriteLine(SearchingAlgorithms.BinarySearch(arr, 17)); Console.WriteLine(SearchingAlgorithms.BinarySearch(arr, 10)); Console.WriteLine(SearchingAlgorithms.BinarySearch(arr, 1000)); } } }
40.888889
93
0.613225
[ "MIT" ]
NinoSimeonov/Telerik-Academy
Programming with C#/4. C# High-Quality Code/08. Defensive Programming, Assertions and Exceptions/01. Assertions/AssertionsTest.cs
1,106
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using xTile; using xTile.ObjectModel; using xTile.Tiles; using xTile.Layers; using StardewValley; using Microsoft.Xna.Framework; using StardewModdingAPI; namespace FarmHouseRedone.Maps { public static class MapUtilities { public const int PASTE_DESTRUCTIVE = 0; public const int PASTE_NONDESTRUCTIVE = 1; public const int PASTE_PRESERVE_FLOORS = 2; public const int PASTE_REPLACE_FLOORS = 3; public static Vector2 GetMapSize(Map map) { return new Vector2(map.Layers[0].LayerWidth, map.Layers[0].LayerHeight); } public static void PasteTile(Map map, Map sectionMap, int x, int y, int mapX, int mapY, Dictionary<TileSheet, TileSheet> equivalentSheets, int pasteMode = PASTE_NONDESTRUCTIVE) { PasteTileInLayer(map, sectionMap, x, y, mapX, mapY, "Back", equivalentSheets, pasteMode); PasteTileInLayer(map, sectionMap, x, y, mapX, mapY, "Buildings", equivalentSheets, pasteMode); PasteTileInLayer(map, sectionMap, x, y, mapX, mapY, "Front", equivalentSheets, pasteMode); PasteTileInLayer(map, sectionMap, x, y, mapX, mapY, "AlwaysFront", equivalentSheets, pasteMode); } public static void PasteTileInLayer(Map map, Map sectionMap, int x, int y, int mapX, int mapY, string layer, Dictionary<TileSheet, TileSheet> equivalentSheets, int pasteMode) { if (sectionMap.GetLayer(layer) == null) return; if (mapX < 0 || mapY < 0 || map.GetLayer(layer).LayerWidth <= mapX || map.GetLayer(layer).LayerHeight <= mapY) return; if (sectionMap.GetLayer(layer).Tiles[x, y] != null) { Tile sectionTile = sectionMap.GetLayer(layer).Tiles[x, y]; if (layer == "Back" && pasteMode == PASTE_PRESERVE_FLOORS && map.GetLayer(layer).Tiles[mapX, mapY] != null) { } else { if (sectionTile is AnimatedTile) { int framesCount = (sectionTile as AnimatedTile).TileFrames.Length; StaticTile[] frames = new StaticTile[framesCount]; for (int i = 0; i < framesCount; i++) { StaticTile frame = (sectionTile as AnimatedTile).TileFrames[i]; frames[i] = new StaticTile(map.GetLayer(layer), equivalentSheets[sectionTile.TileSheet], frame.BlendMode, frame.TileIndex); } map.GetLayer(layer).Tiles[mapX, mapY] = new AnimatedTile(map.GetLayer(layer), frames, (sectionTile as AnimatedTile).FrameInterval); } else { map.GetLayer(layer).Tiles[mapX, mapY] = new StaticTile(map.GetLayer(layer), equivalentSheets[sectionTile.TileSheet], sectionTile.BlendMode, sectionTile.TileIndex); } } if (sectionTile != null && sectionTile.Properties.Keys.Count > 0 && map.GetLayer(layer).Tiles[mapX, mapY] != null) { foreach (KeyValuePair<string, PropertyValue> pair in sectionTile.Properties) { map.GetLayer(layer).Tiles[mapX, mapY].Properties[pair.Key] = pair.Value; } } } else if (pasteMode == PASTE_DESTRUCTIVE || (layer != "Back" && pasteMode == PASTE_PRESERVE_FLOORS) || (layer != "Back" && pasteMode == PASTE_REPLACE_FLOORS)) { map.GetLayer(layer).Tiles[mapX, mapY] = null; } } public static void CloneTile(Tile t, Dictionary<TileSheet,TileSheet> equivalentSheets, Layer destLayer, int x, int y) { if (t is AnimatedTile) { int framesCount = (t as AnimatedTile).TileFrames.Length; StaticTile[] frames = new StaticTile[framesCount]; for (int i = 0; i < framesCount; i++) { StaticTile frame = (t as AnimatedTile).TileFrames[i]; frames[i] = new StaticTile(destLayer, equivalentSheets[t.TileSheet], frame.BlendMode, frame.TileIndex); } destLayer.Tiles[x, y] = new AnimatedTile(destLayer, frames, (t as AnimatedTile).FrameInterval); } else { destLayer.Tiles[x, y] = new StaticTile(destLayer, equivalentSheets[t.TileSheet], t.BlendMode, t.TileIndex); } if (t.Properties.Keys.Count > 0) { foreach (KeyValuePair<string, PropertyValue> pair in t.Properties) { destLayer.Tiles[x, y].Properties[pair.Key] = pair.Value; } } } public static Map CloneMap(Map original) { Map map = new Map(); Dictionary<TileSheet, TileSheet> clonedSheets = GetEquivalentSheets(map, original, true); foreach(Layer layer in original.Layers) { Layer newLayer = new Layer(layer.Id, map, layer.LayerSize, layer.TileSize); map.AddLayer(newLayer); for(int x = 0; x < newLayer.LayerWidth; x++) { for(int y = 0; y < newLayer.LayerHeight; y++) { if (layer.Tiles[x, y] != null) CloneTile(layer.Tiles[x, y], clonedSheets, newLayer, x, y); } } } return map; } public static void OffsetProperties(Map map, int xOffset, int yOffset) { Dictionary<string, string> updatedProperties = new Dictionary<string, string>(); foreach(KeyValuePair<string,PropertyValue> property in map.Properties) { string name = property.Key; if(name == "Walls" || name == "Floors") { string adjusted = ""; string[] original = Strings.Cleanup(property.Value.ToString()).Split(' '); for(int i = 0; i < original.Length; i += 5) { try { adjusted += $"{Convert.ToInt32(original[i]) + xOffset} {Convert.ToInt32(original[i + 1]) + yOffset} {original[i + 2]} {original[i + 3]} {original[i + 4]} "; } catch (IndexOutOfRangeException) { string wallStringAttempt = ""; while (i < original.Length) { wallStringAttempt += original[i] + " "; i++; } Logger.Log(string.Format("Incomplete definition! Walls and Floors must be defined as [x y width height room]. There were insufficient values for the room {0}", wallStringAttempt), StardewModdingAPI.LogLevel.Warn); } catch (FormatException) { string wallStringAttempt = ""; for (int j = 0; j < 5; j++) { wallStringAttempt += original[i + j] + " "; } Logger.Log(string.Format("Invalid definition! Walls and Floors must be defined as [x y width height room]. The invalid wall definition was {0}\nThe invalid wall was skipped.", wallStringAttempt), StardewModdingAPI.LogLevel.Warn); } } updatedProperties[name] = Strings.Cleanup(adjusted); } if(name == "Warp") { string adjusted = ""; string[] original = Strings.Cleanup(property.Value.ToString()).Split(' '); for(int i = 0; i < original.Length; i += 5) { try { adjusted += $"{Convert.ToInt32(original[i]) + xOffset} {Convert.ToInt32(original[i + 1]) + yOffset} {original[i + 2]} {original[i + 3]} {original[i + 4]} "; } catch (IndexOutOfRangeException) { string warpStringAttempt = ""; while (i < original.Length) { warpStringAttempt += original[i] + " "; i++; } Logger.Log(string.Format("Incomplete definition! Warps must be defined as [x y Destination x y]. There were insufficient values for the warp {0}", warpStringAttempt), StardewModdingAPI.LogLevel.Warn); } catch (FormatException) { string warpStringAttempt = ""; for (int j = 0; j < 5; j++) { warpStringAttempt += original[i + j] + " "; } Logger.Log(string.Format("Invalid definition! Warps must be defined as [x y Destination x y]. There were invalid values for the warp {0}\nThis warp was skipped.", warpStringAttempt), StardewModdingAPI.LogLevel.Warn); } } updatedProperties[name] = Strings.Cleanup(adjusted); } if (name == "Return") { string adjusted = ""; string[] original = Strings.Cleanup(property.Value.ToString()).Split(' '); try { for (int index = 0; index < original.Length;) { string mapName = original[index]; int x = Convert.ToInt32(original[index + 1]); int y = Convert.ToInt32(original[index + 2]); if (index + 4 < original.Length && int.TryParse(original[index + 3], out int destX) && int.TryParse(original[index + 4], out int destY)) { adjusted += $"{mapName} {x + xOffset} {y + yOffset} {destX} {destY} "; index += 5; } else { adjusted += $"{mapName} {x + xOffset} {y + yOffset} "; index += 3; } } } catch (FormatException) { Logger.Log("Couldn't parse Return property! Given \"" + Strings.Cleanup(property.Value.ToString()) + "\". Make sure each Return Warp is in the format \"Name x y\" or \"Name x y destX destY\"", LogLevel.Warn); } updatedProperties[name] = Strings.Cleanup(adjusted); } } foreach(string key in updatedProperties.Keys) { map.Properties[key] = updatedProperties[key]; } } /// <summary> /// Safely and correctly adds a value to map properties on map. /// </summary> /// <param name="map">The map to append the value to.</param> /// <param name="propertyName">The property's name, whether map has it or not.</param> /// <param name="propertyValue">The value to append.</param> /// <param name="insertAt">Override the position to append the value at in the property.</param> /// <param name="replace">Completely clears the target property and keeps only the provided one.</param> /// <param name="autoSpace">Automatically provides a leading and/or trailing space as needed.</param> public static void MergeProperties(Map map, string propertyName, string propertyValue, int insertAt = -1, bool replace = false, bool autoSpace = true) { if (!map.Properties.ContainsKey(propertyName)) map.Properties.Add(propertyName, ""); string currentValue = map.Properties[propertyName]; if(insertAt >= 0 && insertAt <= currentValue.Length) { if (replace) { string subString = currentValue.Substring(0, insertAt); if (autoSpace && !subString.EndsWith(" ")) propertyValue = " " + propertyValue; subString += propertyValue; if (insertAt + propertyValue.Length < currentValue.Length) { if (autoSpace && !subString.EndsWith(" ") && currentValue[insertAt] != ' ') subString += " "; subString += currentValue.Substring(insertAt + propertyValue.Length); } map.Properties[propertyName] = subString; return; } else { string subString = currentValue.Substring(0, insertAt); if (autoSpace && !subString.EndsWith(" ")) propertyValue = " " + propertyValue; subString += propertyValue; if (insertAt < currentValue.Length) { if (autoSpace && !subString.EndsWith(" ") && currentValue[insertAt] != ' ') subString += " "; subString += currentValue.Substring(insertAt); } map.Properties[propertyName] = subString; return; } } else { if (replace) { map.Properties[propertyName] = propertyValue; return; } if (autoSpace && !map.Properties[propertyName].ToString().EndsWith(" ")) propertyValue = " " + propertyValue; map.Properties[propertyName] += propertyValue; } } public static Dictionary<TileSheet, TileSheet> GetEquivalentSheets(Map map, Map subMap, bool add = false) { Dictionary<TileSheet, TileSheet> equivalentSheets = new Dictionary<TileSheet, TileSheet>(); foreach (TileSheet sheet in subMap.TileSheets) { foreach (TileSheet locSheet in map.TileSheets) { if (CleanImageSource(locSheet.ImageSource).Equals(CleanImageSource(sheet.ImageSource))) { Logger.Log("Equivalent sheets: " + sheet.ImageSource + " and " + locSheet.ImageSource); equivalentSheets[sheet] = locSheet; break; } else { //Logger.Log(CleanImageSource(locSheet.ImageSource) + " was not the same as " + CleanImageSource(sheet.ImageSource)); } } if (equivalentSheets.ContainsKey(sheet)) continue; else { if (add) { TileSheet newSheet = new TileSheet(map, sheet.ImageSource, sheet.SheetSize, sheet.TileSize); foreach(KeyValuePair<string,PropertyValue> property in sheet.Properties) { newSheet.Properties[property.Key] = property.Value.ToString(); } for(int tileIndex = 0; tileIndex < sheet.TileCount; tileIndex++) { foreach(KeyValuePair<string,PropertyValue> property in sheet.TileIndexProperties[tileIndex]) { newSheet.TileIndexProperties[tileIndex][property.Key] = property.Value.ToString(); } } map.AddTileSheet(newSheet); Logger.Log("Equivalent sheets: " + sheet.ImageSource + " and " + newSheet.ImageSource); equivalentSheets[sheet] = newSheet; } else { Logger.Log("No equivalent sheet found for " + sheet.ImageSource + "! Using default (" + map.TileSheets[0].ImageSource + ")", StardewModdingAPI.LogLevel.Warn); equivalentSheets[sheet] = map.TileSheets[0]; } } } Logger.Log("Finished sheet equivalence calculation."); return equivalentSheets; } public static string CleanImageSource(string source) { string[] seasons = { "spring", "summer", "fall", "winter" }; if (source.Contains("\\")) { string[] path = source.Split('\\'); source = path.Last(); } if (source.Contains("/")) { string[] path = source.Split('/'); source = path.Last(); } if (source.Contains("_") && seasons.Contains(source.Split('_')[0].ToLower())) { source = source.Remove(0, (source.Split('_')[0]).Length + 1); } //Logger.Log("Cleaned as " + source); return source; } public static int GetTileSheet(Map map, string sourceToMatch) { for (int sheetIndex = 0; sheetIndex < map.TileSheets.Count; sheetIndex++) { TileSheet sheet = map.TileSheets[sheetIndex]; if (sheet.ImageSource.Contains(sourceToMatch)) return sheetIndex; } Logger.Log("Couldn't find any tilesheet that matches the source \"" + sourceToMatch + "\"! Using index 0.", StardewModdingAPI.LogLevel.Warn); return 0; } public static bool IsTileOnSheet(Map map, Tile tile, int tileSheetToMatch) { return tile != null && tile.TileSheet.Equals((object)map.TileSheets[tileSheetToMatch]); } public static bool IsTileOnSheet(Map map, string layer, int x, int y, int tileSheetToMatch) { return map.GetLayer(layer).Tiles[x, y] != null && map.GetLayer(layer).Tiles[x, y].TileSheet.Equals((object)map.TileSheets[tileSheetToMatch]); } public static bool IsTileOnSheet(Map map, string layer, int x, int y, int tileSheetToMatch, Rectangle region) { return IsTileOnSheet(map, layer, x, y, tileSheetToMatch) && IsIndexInRect(map.GetLayer(layer).Tiles[x, y].TileIndex, map.TileSheets[tileSheetToMatch], region); } public static bool IsIndexInRect(int index, TileSheet sheet, Rectangle region) { int x = index % sheet.SheetSize.Width; int y = (index / sheet.SheetSize.Width); return region.Contains(x, y); } /// <summary> /// Selectively updates a tile only if it matches a specific tilesheet. /// </summary> /// <param name="map"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="index"></param> /// <param name="layer"></param> /// <param name="tileSheetToMatch"></param> /// <param name="region"></param> public static void SetMapTileIndexIfOnTileSheet(Map map, int x, int y, int index, string layer, int tileSheetToMatch, Rectangle region) { if (IsTileOnSheet(map, layer, x, y, tileSheetToMatch, region)) { map.GetLayer(layer).Tiles[x, y].TileIndex = index; } } internal static void SetWallMapTileIndexForAnyLayer(Map map, int x, int y, int index) { SetMapTileIndexIfOnTileSheet(map, x, y, GetWallIndex(map, x, y, "Back", index), "Back", GetTileSheet(map, "walls_and_floors"), new Rectangle(0, 0, 16, 21)); SetMapTileIndexIfOnTileSheet(map, x, y, GetWallIndex(map, x, y, "Buildings", index), "Buildings", GetTileSheet(map, "walls_and_floors"), new Rectangle(0, 0, 16, 21)); SetMapTileIndexIfOnTileSheet(map, x, y, GetWallIndex(map, x, y, "Front", index), "Front", GetTileSheet(map, "walls_and_floors"), new Rectangle(0, 0, 16, 21)); } public static int GetWallpaperIndex(Map map, int x, int y) { int wallIndex = GetWallSpriteIndex(map, x, y); if (wallIndex == -1) return -1; int wallPaperX = wallIndex % 16; int wallPaperY = wallIndex / 48; int wallPaperIndex = (wallPaperY * 16) + wallPaperX; Logger.Log("Found wallpaper index of " + wallPaperIndex + " for tilesheet index " + wallIndex + "."); return wallPaperIndex; } public static int GetWallSpriteIndex(Map map, int x, int y) { int index = -1; if (IsTileOnSheet(map, "Back", x, y, GetTileSheet(map, "walls_and_floors"), new Rectangle(0, 0, 16, 21))) { index = map.GetLayer("Back").Tiles[x, y].TileIndex; } else if (IsTileOnSheet(map, "Buildings", x, y, GetTileSheet(map, "walls_and_floors"), new Rectangle(0, 0, 16, 21))) { index = map.GetLayer("Buildings").Tiles[x, y].TileIndex; } else if (IsTileOnSheet(map, "Front", x, y, GetTileSheet(map, "walls_and_floors"), new Rectangle(0, 0, 16, 21))) { index = map.GetLayer("Front").Tiles[x, y].TileIndex; } return index; } public static int GetFloorIndex(Map map, int x, int y) { int floorIndex = GetFloorSpriteIndex(map, x, y); if (floorIndex == -1) return -1; floorIndex -= 336; int floorX = (floorIndex / 2) % 8; int floorY = floorIndex / 32; int floor = (floorY * 8) + floorX; Logger.Log("Found floor index of " + floor + " for tilesheet index " + floorIndex + "."); return floor; } public static int GetFloorSpriteIndex(Map map, int x, int y) { int index = -1; if (IsTileOnSheet(map, "Back", x, y, GetTileSheet(map, "walls_and_floors"), new Rectangle(0, 21, 16, 20))) { index = map.GetLayer("Back").Tiles[x, y].TileIndex; } return index; } internal static int GetWallIndex(Map map, int x, int y, string layer, int destinationIndex) { if (map.GetLayer(layer).Tiles[x, y] == null) return -1; int currentIndex = map.GetLayer(layer).Tiles[x, y].TileIndex; int whichHeight = (currentIndex % 48) / 16; return destinationIndex + (whichHeight * 16); } internal static int GetFloorIndex(Map map, int x, int y, string layer, int destinationIndex) { if (map.GetLayer(layer).Tiles[x, y] == null) return -1; int currentIndex = map.GetLayer(layer).Tiles[x, y].TileIndex; int horizontalOffset = currentIndex % 2; int verticalOffset = ((currentIndex - 336) / 16) % 2; return destinationIndex + horizontalOffset + (verticalOffset * 16); //TODO: this math is wrong - it's for walls //I'm very sleepy right now and can't do math //int whichHeight = (currentIndex % 48) / 16; //return destinationIndex + (whichHeight * 16); } internal static void SetFloorMapTileIndexForAnyLayer(Map map, int x, int y, int index) { SetMapTileIndexIfOnTileSheet(map, x, y, GetFloorIndex(map, x, y, "Back", index), "Back", GetTileSheet(map, "walls_and_floors"), new Rectangle(0, 21, 16, 10)); SetMapTileIndexIfOnTileSheet(map, x, y, GetFloorIndex(map, x, y, "Buildings", index), "Buildings", GetTileSheet(map, "walls_and_floors"), new Rectangle(0, 21, 16, 10)); SetMapTileIndexIfOnTileSheet(map, x, y, GetFloorIndex(map, x, y, "Front", index), "Front", GetTileSheet(map, "walls_and_floors"), new Rectangle(0, 21, 16, 10)); } internal static void ResizeMapAtLeast(Map map, int width, int height, int xOffset, int yOffset) { int mapWidth = map.Layers[0].LayerWidth; int mapHeight = map.Layers[0].LayerHeight; ResizeMap(map, Math.Max(mapWidth, width) + xOffset, Math.Max(mapHeight, height) + yOffset, xOffset, yOffset); } internal static void ResizeMap(Map map, int width, int height, int xOffset, int yOffset) { Dictionary<TileSheet, TileSheet> equivalentSheets = GetEquivalentSheets(map, map); Logger.Log("Resizing map from (" + GetMapSize(map).X + ", " + GetMapSize(map).Y + "), to (" + width + ", " + height + ") and shifting it by (" + xOffset + ", " + yOffset + ")"); foreach (Layer layer in map.Layers) { Layer tempLayer = new Layer(layer.Id + "_temporary", map, new xTile.Dimensions.Size(width, height), layer.TileSize); for(int x = 0; x < width; x++) { for(int y = 0; y < height; y++) { int sourceX = x - xOffset; int sourceY = y - yOffset; if(sourceX >= 0 && sourceY >= 0 && sourceX < layer.LayerWidth && sourceY < layer.LayerHeight && layer.Tiles[sourceX,sourceY] != null) { CloneTile(layer.Tiles[sourceX, sourceY], equivalentSheets, tempLayer, x, y); } } } layer.LayerSize = new xTile.Dimensions.Size(width, height); for(int x = 0; x < width; x++) { for(int y = 0; y < height; y++) { if (tempLayer.Tiles[x, y] == null) layer.Tiles[x, y] = null; else CloneTile(tempLayer.Tiles[x, y], equivalentSheets, layer, x, y); } } } } } }
48.915315
259
0.502357
[ "MIT" ]
mjSurber/FarmHouseRedone-2
FarmHouseRedone/Maps/MapUtilities.cs
27,150
C#
// // ecore.cs: Core of the Expression representation for the intermediate tree. // // Author: // Miguel de Icaza (miguel@ximian.com) // Marek Safar (marek.safar@gmail.com) // // Copyright 2001, 2002, 2003 Ximian, Inc. // Copyright 2003-2008 Novell, Inc. // Copyright 2011-2012 Xamarin Inc. // // using System; using System.Collections.Generic; using System.Text; using SLE = System.Linq.Expressions; using System.Linq; #if STATIC using IKVM.Reflection; using IKVM.Reflection.Emit; #else using System.Reflection; using System.Reflection.Emit; #endif namespace Mono.CSharp { /// <remarks> /// The ExprClass class contains the is used to pass the /// classification of an expression (value, variable, namespace, /// type, method group, property access, event access, indexer access, /// nothing). /// </remarks> public enum ExprClass : byte { Unresolved = 0, Value, Variable, Namespace, Type, TypeParameter, MethodGroup, PropertyAccess, EventAccess, IndexerAccess, Nothing, } /// <remarks> /// This is used to tell Resolve in which types of expressions we're /// interested. /// </remarks> [Flags] public enum ResolveFlags { // Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess. VariableOrValue = 1, // Returns a type expression. Type = 1 << 1, // Returns a method group. MethodGroup = 1 << 2, TypeParameter = 1 << 3, // Mask of all the expression class flags. MaskExprClass = VariableOrValue | Type | MethodGroup | TypeParameter, } // // This is just as a hint to AddressOf of what will be done with the // address. [Flags] public enum AddressOp { Store = 1, Load = 2, LoadStore = 3 }; /// <summary> /// This interface is implemented by variables /// </summary> public interface IMemoryLocation { /// <summary> /// The AddressOf method should generate code that loads /// the address of the object and leaves it on the stack. /// /// The `mode' argument is used to notify the expression /// of whether this will be used to read from the address or /// write to the address. /// /// This is just a hint that can be used to provide good error /// reporting, and should have no other side effects. /// </summary> void AddressOf (EmitContext ec, AddressOp mode); } // // An expressions resolved as a direct variable reference // public interface IVariableReference : IFixedExpression { bool IsHoisted { get; } string Name { get; } VariableInfo VariableInfo { get; } void SetHasAddressTaken (); } // // Implemented by an expression which could be or is always // fixed // public interface IFixedExpression { bool IsFixed { get; } } public interface IExpressionCleanup { void EmitCleanup (EmitContext ec); } /// <remarks> /// Base class for expressions /// </remarks> public abstract class Expression { public ExprClass eclass; protected TypeSpec type; protected Location loc; public TypeSpec Type { get { return type; } set { type = value; } } public virtual bool IsSideEffectFree { get { return false; } } public Location Location { get { return loc; } } public virtual bool IsNull { get { return false; } } // // Used to workaround parser limitation where we cannot get // start of statement expression location // public virtual Location StartLocation { get { return loc; } } public virtual MethodGroupExpr CanReduceLambda (AnonymousMethodBody body) { // // Return method-group expression when the expression can be used as // lambda replacement. A good example is array sorting where instead of // code like // // Array.Sort (s, (a, b) => String.Compare (a, b)); // // we can use method group directly // // Array.Sort (s, String.Compare); // // Correct overload will be used because we do the reduction after // best candidate was found. // return null; } // // Returns true when the expression during Emit phase breaks stack // by using await expression // public virtual bool ContainsEmitWithAwait () { return false; } /// <summary> /// Performs semantic analysis on the Expression /// </summary> /// /// <remarks> /// The Resolve method is invoked to perform the semantic analysis /// on the node. /// /// The return value is an expression (it can be the /// same expression in some cases) or a new /// expression that better represents this node. /// /// For example, optimizations of Unary (LiteralInt) /// would return a new LiteralInt with a negated /// value. /// /// If there is an error during semantic analysis, /// then an error should be reported (using Report) /// and a null value should be returned. /// /// There are two side effects expected from calling /// Resolve(): the the field variable "eclass" should /// be set to any value of the enumeration /// `ExprClass' and the type variable should be set /// to a valid type (this is the type of the /// expression). /// </remarks> protected abstract Expression DoResolve (ResolveContext rc); public virtual Expression DoResolveLValue (ResolveContext rc, Expression right_side) { return null; } // // This is used if the expression should be resolved as a type or namespace name. // the default implementation fails. // public virtual TypeSpec ResolveAsType (IMemberContext mc, bool allowUnboundTypeArguments = false) { var rc = mc as ResolveContext ?? new ResolveContext (mc); Expression e = Resolve (rc); if (e != null) e.Error_UnexpectedKind (rc, ResolveFlags.Type, loc); return null; } public static void ErrorIsInaccesible (IMemberContext rc, string member, Location loc) { rc.Module.Compiler.Report.Error (122, loc, "`{0}' is inaccessible due to its protection level", member); } public void Error_ExpressionMustBeConstant (ResolveContext rc, Location loc, string e_name) { rc.Report.Error (133, loc, "The expression being assigned to `{0}' must be constant", e_name); } public void Error_ConstantCanBeInitializedWithNullOnly (ResolveContext rc, TypeSpec type, Location loc, string name) { rc.Report.Error (134, loc, "A constant `{0}' of reference type `{1}' can only be initialized with null", name, type.GetSignatureForError ()); } protected virtual void Error_InvalidExpressionStatement (Report report, Location loc) { report.Error (201, loc, "Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement"); } public void Error_InvalidExpressionStatement (BlockContext bc) { Error_InvalidExpressionStatement (bc.Report, loc); } public void Error_InvalidExpressionStatement (Report report) { Error_InvalidExpressionStatement (report, loc); } public static void Error_VoidInvalidInTheContext (Location loc, Report Report) { Report.Error (1547, loc, "Keyword `void' cannot be used in this context"); } public virtual void Error_ValueCannotBeConverted (ResolveContext ec, TypeSpec target, bool expl) { Error_ValueCannotBeConvertedCore (ec, loc, target, expl); } protected void Error_ValueCannotBeConvertedCore (ResolveContext ec, Location loc, TypeSpec target, bool expl) { // The error was already reported as CS1660 if (type == InternalType.AnonymousMethod) return; if (type == InternalType.ErrorType || target == InternalType.ErrorType) return; string from_type = type.GetSignatureForError (); string to_type = target.GetSignatureForError (); if (from_type == to_type) { from_type = type.GetSignatureForErrorIncludingAssemblyName (); to_type = target.GetSignatureForErrorIncludingAssemblyName (); } if (expl) { ec.Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'", from_type, to_type); return; } ec.Report.DisableReporting (); bool expl_exists = Convert.ExplicitConversion (ec, this, target, Location.Null) != null; ec.Report.EnableReporting (); if (expl_exists) { ec.Report.Error (266, loc, "Cannot implicitly convert type `{0}' to `{1}'. An explicit conversion exists (are you missing a cast?)", from_type, to_type); } else { ec.Report.Error (29, loc, "Cannot implicitly convert type `{0}' to `{1}'", from_type, to_type); } } public void Error_TypeArgumentsCannotBeUsed (IMemberContext context, MemberSpec member, Location loc) { // Better message for possible generic expressions if (member != null && (member.Kind & MemberKind.GenericMask) != 0) { var report = context.Module.Compiler.Report; report.SymbolRelatedToPreviousError (member); if (member is TypeSpec) member = ((TypeSpec) member).GetDefinition (); else member = ((MethodSpec) member).GetGenericMethodDefinition (); string name = member.Kind == MemberKind.Method ? "method" : "type"; if (member.IsGeneric) { report.Error (305, loc, "Using the generic {0} `{1}' requires `{2}' type argument(s)", name, member.GetSignatureForError (), member.Arity.ToString ()); } else { report.Error (308, loc, "The non-generic {0} `{1}' cannot be used with the type arguments", name, member.GetSignatureForError ()); } } else { Error_TypeArgumentsCannotBeUsed (context, ExprClassName, GetSignatureForError (), loc); } } public static void Error_TypeArgumentsCannotBeUsed (IMemberContext context, string exprType, string name, Location loc) { context.Module.Compiler.Report.Error (307, loc, "The {0} `{1}' cannot be used with type arguments", exprType, name); } protected virtual void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name) { Error_TypeDoesNotContainDefinition (ec, loc, type, name); } public static void Error_TypeDoesNotContainDefinition (ResolveContext ec, Location loc, TypeSpec type, string name) { ec.Report.SymbolRelatedToPreviousError (type); ec.Report.Error (117, loc, "`{0}' does not contain a definition for `{1}'", type.GetSignatureForError (), name); } public virtual void Error_ValueAssignment (ResolveContext rc, Expression rhs) { if (rhs == EmptyExpression.LValueMemberAccess || rhs == EmptyExpression.LValueMemberOutAccess) { // Already reported as CS1612 } else if (rhs == EmptyExpression.OutAccess) { rc.Report.Error (1510, loc, "A ref or out argument must be an assignable variable"); } else { rc.Report.Error (131, loc, "The left-hand side of an assignment must be a variable, a property or an indexer"); } } protected void Error_VoidPointerOperation (ResolveContext rc) { rc.Report.Error (242, loc, "The operation in question is undefined on void pointers"); } public static void Warning_UnreachableExpression (ResolveContext rc, Location loc) { rc.Report.Warning (429, 4, loc, "Unreachable expression code detected"); } public ResolveFlags ExprClassToResolveFlags { get { switch (eclass) { case ExprClass.Type: case ExprClass.Namespace: return ResolveFlags.Type; case ExprClass.MethodGroup: return ResolveFlags.MethodGroup; case ExprClass.TypeParameter: return ResolveFlags.TypeParameter; case ExprClass.Value: case ExprClass.Variable: case ExprClass.PropertyAccess: case ExprClass.EventAccess: case ExprClass.IndexerAccess: return ResolveFlags.VariableOrValue; default: throw new InternalErrorException (loc.ToString () + " " + GetType () + " ExprClass is Invalid after resolve"); } } } // // Implements identical simple name and type-name resolution // public Expression ProbeIdenticalTypeName (ResolveContext rc, Expression left, SimpleName name) { var t = left.Type; if (t.Kind == MemberKind.InternalCompilerType || t is ElementTypeSpec || t.Arity > 0) return left; // In a member access of the form E.I, if E is a single identifier, and if the meaning of E as a simple-name is // a constant, field, property, local variable, or parameter with the same type as the meaning of E as a type-name if (left is MemberExpr || left is VariableReference) { var identical_type = rc.LookupNamespaceOrType (name.Name, 0, LookupMode.Probing, loc) as TypeExpr; if (identical_type != null && identical_type.Type == left.Type) return identical_type; } return left; } public virtual string GetSignatureForError () { return type.GetDefinition ().GetSignatureForError (); } public static bool IsNeverNull (Expression expr) { if (expr is This || expr is New || expr is ArrayCreation || expr is DelegateCreation || expr is ConditionalMemberAccess) return true; var c = expr as Constant; if (c != null) return !c.IsNull; var tc = expr as TypeCast; if (tc != null) return IsNeverNull (tc.Child); return false; } protected static bool IsNullPropagatingValid (TypeSpec type) { switch (type.Kind) { case MemberKind.Struct: return type.IsNullableType; case MemberKind.Enum: case MemberKind.Void: case MemberKind.PointerType: return false; case MemberKind.InternalCompilerType: return type.BuiltinType == BuiltinTypeSpec.Type.Dynamic; case MemberKind.TypeParameter: return !((TypeParameterSpec) type).IsValueType; default: return true; } } public virtual bool HasConditionalAccess () { return false; } protected static TypeSpec LiftMemberType (ResolveContext rc, TypeSpec type) { return TypeSpec.IsValueType (type) && !type.IsNullableType ? Nullable.NullableInfo.MakeType (rc.Module, type) : type; } /// <summary> /// Resolves an expression and performs semantic analysis on it. /// </summary> /// /// <remarks> /// Currently Resolve wraps DoResolve to perform sanity /// checking and assertion checking on what we expect from Resolve. /// </remarks> public Expression Resolve (ResolveContext ec, ResolveFlags flags) { if (eclass != ExprClass.Unresolved) { if ((flags & ExprClassToResolveFlags) == 0) { Error_UnexpectedKind (ec, flags, loc); return null; } return this; } Expression e; try { e = DoResolve (ec); if (e == null) return null; if ((flags & e.ExprClassToResolveFlags) == 0) { e.Error_UnexpectedKind (ec, flags, loc); return null; } if (e.type == null) throw new InternalErrorException ("Expression `{0}' didn't set its type in DoResolve", e.GetType ()); return e; } catch (Exception ex) { if (loc.IsNull || ec.Module.Compiler.Settings.BreakOnInternalError || ex is CompletionResult || ec.Report.IsDisabled || ex is FatalException || ec.Report.Printer is NullReportPrinter) throw; ec.Report.Error (584, loc, "Internal compiler error: {0}", ex.Message); return ErrorExpression.Instance; // TODO: Add location } } /// <summary> /// Resolves an expression and performs semantic analysis on it. /// </summary> public Expression Resolve (ResolveContext rc) { return Resolve (rc, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup); } /// <summary> /// Resolves an expression for LValue assignment /// </summary> /// /// <remarks> /// Currently ResolveLValue wraps DoResolveLValue to perform sanity /// checking and assertion checking on what we expect from Resolve /// </remarks> public Expression ResolveLValue (ResolveContext ec, Expression right_side) { int errors = ec.Report.Errors; bool out_access = right_side == EmptyExpression.OutAccess; Expression e = DoResolveLValue (ec, right_side); if (e != null && out_access && !(e is IMemoryLocation)) { // FIXME: There's no problem with correctness, the 'Expr = null' handles that. // Enabling this 'throw' will "only" result in deleting useless code elsewhere, //throw new InternalErrorException ("ResolveLValue didn't return an IMemoryLocation: " + // e.GetType () + " " + e.GetSignatureForError ()); e = null; } if (e == null) { if (errors == ec.Report.Errors) { Error_ValueAssignment (ec, right_side); } return null; } if (e.eclass == ExprClass.Unresolved) throw new Exception ("Expression " + e + " ExprClass is Invalid after resolve"); if ((e.type == null) && !(e is GenericTypeExpr)) throw new Exception ("Expression " + e + " did not set its type after Resolve"); return e; } public Constant ResolveLabelConstant (ResolveContext rc) { var expr = Resolve (rc); if (expr == null) return null; Constant c = expr as Constant; if (c == null) { if (expr.type != InternalType.ErrorType) rc.Report.Error (150, expr.StartLocation, "A constant value is expected"); return null; } return c; } public virtual void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType) { if (Attribute.IsValidArgumentType (parameterType)) { rc.Module.Compiler.Report.Error (182, loc, "An attribute argument must be a constant expression, typeof expression or array creation expression"); } else { rc.Module.Compiler.Report.Error (181, loc, "Attribute constructor parameter has type `{0}', which is not a valid attribute parameter type", targetType.GetSignatureForError ()); } } /// <summary> /// Emits the code for the expression /// </summary> /// /// <remarks> /// The Emit method is invoked to generate the code /// for the expression. /// </remarks> public abstract void Emit (EmitContext ec); // Emit code to branch to @target if this expression is equivalent to @on_true. // The default implementation is to emit the value, and then emit a brtrue or brfalse. // Subclasses can provide more efficient implementations, but those MUST be equivalent, // including the use of conditional branches. Note also that a branch MUST be emitted public virtual void EmitBranchable (EmitContext ec, Label target, bool on_true) { Emit (ec); ec.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target); } // Emit this expression for its side effects, not for its value. // The default implementation is to emit the value, and then throw it away. // Subclasses can provide more efficient implementations, but those MUST be equivalent public virtual void EmitSideEffect (EmitContext ec) { Emit (ec); ec.Emit (OpCodes.Pop); } // // Emits the expression into temporary field variable. The method // should be used for await expressions only // public virtual Expression EmitToField (EmitContext ec) { // // This is the await prepare Emit method. When emitting code like // a + b we emit code like // // a.Emit () // b.Emit () // Opcodes.Add // // For await a + await b we have to interfere the flow to keep the // stack clean because await yields from the expression. The emit // then changes to // // a = a.EmitToField () // a is changed to temporary field access // b = b.EmitToField () // a.Emit () // b.Emit () // Opcodes.Add // // // The idea is to emit expression and leave the stack empty with // result value still available. // // Expressions should override this default implementation when // optimized version can be provided (e.g. FieldExpr) // // // We can optimize for side-effect free expressions, they can be // emitted out of order // if (IsSideEffectFree) return this; bool needs_temporary = ContainsEmitWithAwait (); if (!needs_temporary) ec.EmitThis (); // Emit original code var field = EmitToFieldSource (ec); if (field == null) { // // Store the result to temporary field when we // cannot load `this' directly // field = ec.GetTemporaryField (type); if (needs_temporary) { // // Create temporary local (we cannot load `this' before Emit) // var temp = ec.GetTemporaryLocal (type); ec.Emit (OpCodes.Stloc, temp); ec.EmitThis (); ec.Emit (OpCodes.Ldloc, temp); field.EmitAssignFromStack (ec); ec.FreeTemporaryLocal (temp, type); } else { field.EmitAssignFromStack (ec); } } return field; } protected virtual FieldExpr EmitToFieldSource (EmitContext ec) { // // Default implementation calls Emit method // Emit (ec); return null; } protected static void EmitExpressionsList (EmitContext ec, List<Expression> expressions) { if (ec.HasSet (BuilderContext.Options.AsyncBody)) { bool contains_await = false; for (int i = 1; i < expressions.Count; ++i) { if (expressions[i].ContainsEmitWithAwait ()) { contains_await = true; break; } } if (contains_await) { for (int i = 0; i < expressions.Count; ++i) { expressions[i] = expressions[i].EmitToField (ec); } } } for (int i = 0; i < expressions.Count; ++i) { expressions[i].Emit (ec); } } /// <summary> /// Protected constructor. Only derivate types should /// be able to be created /// </summary> protected Expression () { } /// <summary> /// Returns a fully formed expression after a MemberLookup /// </summary> /// static Expression ExprClassFromMemberInfo (MemberSpec spec, Location loc) { if (spec is EventSpec) return new EventExpr ((EventSpec) spec, loc); if (spec is ConstSpec) return new ConstantExpr ((ConstSpec) spec, loc); if (spec is FieldSpec) return new FieldExpr ((FieldSpec) spec, loc); if (spec is PropertySpec) return new PropertyExpr ((PropertySpec) spec, loc); if (spec is TypeSpec) return new TypeExpression (((TypeSpec) spec), loc); return null; } public static MethodSpec ConstructorLookup (ResolveContext rc, TypeSpec type, ref Arguments args, Location loc) { var ctors = MemberCache.FindMembers (type, Constructor.ConstructorName, true); if (ctors == null) { switch (type.Kind) { case MemberKind.Struct: // Every struct has implicit default constructor if not provided by user if (args == null) return null; rc.Report.SymbolRelatedToPreviousError (type); // Report meaningful error for struct as they always have default ctor in C# context OverloadResolver.Error_ConstructorMismatch (rc, type, args == null ? 0 : args.Count, loc); break; case MemberKind.MissingType: case MemberKind.InternalCompilerType: // LAMESPEC: dynamic is not really object // if (type.BuiltinType == BuiltinTypeSpec.Type.Object) // goto default; break; default: rc.Report.SymbolRelatedToPreviousError (type); rc.Report.Error (143, loc, "The class `{0}' has no constructors defined", type.GetSignatureForError ()); break; } return null; } if (args == null && type.IsStruct) { bool includes_empty = false; foreach (MethodSpec ctor in ctors) { if (ctor.Parameters.IsEmpty) { includes_empty = true; } } if (!includes_empty) return null; } var r = new OverloadResolver (ctors, OverloadResolver.Restrictions.NoBaseMembers, loc); if (!rc.HasSet (ResolveContext.Options.BaseInitializer)) { r.InstanceQualifier = new ConstructorInstanceQualifier (type); } return r.ResolveMember<MethodSpec> (rc, ref args); } [Flags] public enum MemberLookupRestrictions { None = 0, InvocableOnly = 1, ExactArity = 1 << 2, ReadAccess = 1 << 3, EmptyArguments = 1 << 4, IgnoreArity = 1 << 5, IgnoreAmbiguity = 1 << 6 } // // Lookup type `queried_type' for code in class `container_type' with a qualifier of // `qualifier_type' or null to lookup members in the current class. // public static Expression MemberLookup (IMemberContext rc, bool errorMode, TypeSpec queried_type, string name, int arity, MemberLookupRestrictions restrictions, Location loc) { var members = MemberCache.FindMembers (queried_type, name, false); if (members == null) return null; MemberSpec non_method = null; MemberSpec ambig_non_method = null; do { for (int i = 0; i < members.Count; ++i) { var member = members[i]; // HACK: for events because +=/-= can appear at same class only, should use OverrideToBase there if ((member.Modifiers & Modifiers.OVERRIDE) != 0 && member.Kind != MemberKind.Event) continue; if ((member.Modifiers & Modifiers.BACKING_FIELD) != 0 || member.Kind == MemberKind.Operator) continue; if ((arity > 0 || (restrictions & MemberLookupRestrictions.ExactArity) != 0) && member.Arity != arity) continue; if (!errorMode) { if (!member.IsAccessible (rc)) continue; // // With runtime binder we can have a situation where queried type is inaccessible // because it came via dynamic object, the check about inconsisted accessibility // had no effect as the type was unknown during compilation // // class A { // private class N { } // // public dynamic Foo () // { // return new N (); // } // } // if (rc.Module.Compiler.IsRuntimeBinder && !member.DeclaringType.IsAccessible (rc)) continue; } if ((restrictions & MemberLookupRestrictions.InvocableOnly) != 0) { if (member is MethodSpec) { // // Interface members that are hidden by class members are removed from the set. This // step only has an effect if T is a type parameter and T has both an effective base // class other than object and a non-empty effective interface set // var tps = queried_type as TypeParameterSpec; if (tps != null && tps.HasTypeConstraint) members = RemoveHiddenTypeParameterMethods (members); return new MethodGroupExpr (members, queried_type, loc); } if (!Invocation.IsMemberInvocable (member)) continue; } if (non_method == null || member is MethodSpec || non_method.IsNotCSharpCompatible) { non_method = member; } else if (!errorMode && !member.IsNotCSharpCompatible) { // // Interface members that are hidden by class members are removed from the set when T is a type parameter and // T has both an effective base class other than object and a non-empty effective interface set. // // The spec has more complex rules but we simply remove all members declared in an interface declaration. // var tps = queried_type as TypeParameterSpec; if (tps != null && tps.HasTypeConstraint) { if (non_method.DeclaringType.IsClass && member.DeclaringType.IsInterface) continue; if (non_method.DeclaringType.IsInterface && member.DeclaringType.IsInterface) { non_method = member; continue; } } ambig_non_method = member; } } if (non_method != null) { if (ambig_non_method != null && rc != null && (restrictions & MemberLookupRestrictions.IgnoreAmbiguity) == 0) { var report = rc.Module.Compiler.Report; report.SymbolRelatedToPreviousError (non_method); report.SymbolRelatedToPreviousError (ambig_non_method); report.Error (229, loc, "Ambiguity between `{0}' and `{1}'", non_method.GetSignatureForError (), ambig_non_method.GetSignatureForError ()); } if (non_method is MethodSpec) return new MethodGroupExpr (members, queried_type, loc); return ExprClassFromMemberInfo (non_method, loc); } if (members[0].DeclaringType.BaseType == null) members = null; else members = MemberCache.FindMembers (members[0].DeclaringType.BaseType, name, false); } while (members != null); return null; } static IList<MemberSpec> RemoveHiddenTypeParameterMethods (IList<MemberSpec> members) { if (members.Count < 2) return members; // // If M is a method, then all non-method members declared in an interface declaration // are removed from the set, and all methods with the same signature as M declared in // an interface declaration are removed from the set // bool copied = false; for (int i = 0; i < members.Count; ++i) { var method = members[i] as MethodSpec; if (method == null) { if (!copied) { copied = true; members = new List<MemberSpec> (members); } members.RemoveAt (i--); continue; } if (!method.DeclaringType.IsInterface) continue; for (int ii = 0; ii < members.Count; ++ii) { var candidate = members[ii] as MethodSpec; if (candidate == null || !candidate.DeclaringType.IsClass) continue; if (!TypeSpecComparer.Override.IsEqual (candidate.Parameters, method.Parameters)) continue; if (!copied) { copied = true; members = new List<MemberSpec> (members); } members.RemoveAt (i--); break; } } return members; } protected virtual void Error_NegativeArrayIndex (ResolveContext ec, Location loc) { throw new NotImplementedException (); } public virtual void Error_OperatorCannotBeApplied (ResolveContext rc, Location loc, string oper, TypeSpec t) { if (t == InternalType.ErrorType) return; rc.Report.Error (23, loc, "The `{0}' operator cannot be applied to operand of type `{1}'", oper, t.GetSignatureForError ()); } protected void Error_PointerInsideExpressionTree (ResolveContext ec) { ec.Report.Error (1944, loc, "An expression tree cannot contain an unsafe pointer operation"); } protected void Error_NullShortCircuitInsideExpressionTree (ResolveContext rc) { rc.Report.Error (8072, loc, "An expression tree cannot contain a null propagating operator"); } public virtual void FlowAnalysis (FlowAnalysisContext fc) { } // // Special version of flow analysis for expressions which can return different // on-true and on-false result. Used by &&, ||, ?: expressions // public virtual void FlowAnalysisConditional (FlowAnalysisContext fc) { FlowAnalysis (fc); fc.DefiniteAssignmentOnTrue = fc.DefiniteAssignmentOnFalse = fc.DefiniteAssignment; } /// <summary> /// Returns an expression that can be used to invoke operator true /// on the expression if it exists. /// </summary> protected static Expression GetOperatorTrue (ResolveContext ec, Expression e, Location loc) { return GetOperatorTrueOrFalse (ec, e, true, loc); } /// <summary> /// Returns an expression that can be used to invoke operator false /// on the expression if it exists. /// </summary> protected static Expression GetOperatorFalse (ResolveContext ec, Expression e, Location loc) { return GetOperatorTrueOrFalse (ec, e, false, loc); } static Expression GetOperatorTrueOrFalse (ResolveContext ec, Expression e, bool is_true, Location loc) { var op = is_true ? Operator.OpType.True : Operator.OpType.False; var type = e.type; if (type.IsNullableType) type = Nullable.NullableInfo.GetUnderlyingType (type); var methods = MemberCache.GetUserOperator (type, op, false); if (methods == null) return null; Arguments arguments = new Arguments (1); arguments.Add (new Argument (e)); var res = new OverloadResolver (methods, OverloadResolver.Restrictions.BaseMembersIncluded | OverloadResolver.Restrictions.NoBaseMembers, loc); var oper = res.ResolveOperator (ec, ref arguments); if (oper == null) return null; return new UserOperatorCall (oper, arguments, null, loc); } public virtual string ExprClassName { get { switch (eclass){ case ExprClass.Unresolved: return "Unresolved"; case ExprClass.Value: return "value"; case ExprClass.Variable: return "variable"; case ExprClass.Namespace: return "namespace"; case ExprClass.Type: return "type"; case ExprClass.MethodGroup: return "method group"; case ExprClass.PropertyAccess: return "property access"; case ExprClass.EventAccess: return "event access"; case ExprClass.IndexerAccess: return "indexer access"; case ExprClass.Nothing: return "null"; case ExprClass.TypeParameter: return "type parameter"; } throw new Exception ("Should not happen"); } } /// <summary> /// Reports that we were expecting `expr' to be of class `expected' /// </summary> public static void Error_UnexpectedKind (IMemberContext ctx, Expression memberExpr, string expected, string was, Location loc) { var name = memberExpr.GetSignatureForError (); ctx.Module.Compiler.Report.Error (118, loc, "`{0}' is a `{1}' but a `{2}' was expected", name, was, expected); } public virtual void Error_UnexpectedKind (ResolveContext ec, ResolveFlags flags, Location loc) { string [] valid = new string [4]; int count = 0; if ((flags & ResolveFlags.VariableOrValue) != 0) { valid [count++] = "variable"; valid [count++] = "value"; } if ((flags & ResolveFlags.Type) != 0) valid [count++] = "type"; if ((flags & ResolveFlags.MethodGroup) != 0) valid [count++] = "method group"; if (count == 0) valid [count++] = "unknown"; StringBuilder sb = new StringBuilder (valid [0]); for (int i = 1; i < count - 1; i++) { sb.Append ("', `"); sb.Append (valid [i]); } if (count > 1) { sb.Append ("' or `"); sb.Append (valid [count - 1]); } ec.Report.Error (119, loc, "Expression denotes a `{0}', where a `{1}' was expected", ExprClassName, sb.ToString ()); } public static void UnsafeError (ResolveContext ec, Location loc) { UnsafeError (ec.Report, loc); } public static void UnsafeError (Report Report, Location loc) { Report.Error (214, loc, "Pointers and fixed size buffers may only be used in an unsafe context"); } // // Converts `source' to an int, uint, long or ulong. // protected Expression ConvertExpressionToArrayIndex (ResolveContext ec, Expression source, bool pointerArray = false) { var btypes = ec.BuiltinTypes; if (source.type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) { Arguments args = new Arguments (1); args.Add (new Argument (source)); return new DynamicConversion (btypes.Int, CSharpBinderFlags.ConvertArrayIndex, args, loc).Resolve (ec); } Expression converted; using (ec.Set (ResolveContext.Options.CheckedScope)) { converted = Convert.ImplicitConversion (ec, source, btypes.Int, source.loc); if (converted == null) converted = Convert.ImplicitConversion (ec, source, btypes.UInt, source.loc); if (converted == null) converted = Convert.ImplicitConversion (ec, source, btypes.Long, source.loc); if (converted == null) converted = Convert.ImplicitConversion (ec, source, btypes.ULong, source.loc); if (converted == null) { source.Error_ValueCannotBeConverted (ec, btypes.Int, false); return null; } } if (pointerArray) return converted; // // Only positive constants are allowed at compile time // Constant c = converted as Constant; if (c != null && c.IsNegative) Error_NegativeArrayIndex (ec, source.loc); // No conversion needed to array index if (converted.Type.BuiltinType == BuiltinTypeSpec.Type.Int) return converted; return new ArrayIndexCast (converted, btypes.Int).Resolve (ec); } // // Derived classes implement this method by cloning the fields that // could become altered during the Resolve stage // // Only expressions that are created for the parser need to implement // this. // protected virtual void CloneTo (CloneContext clonectx, Expression target) { throw new NotImplementedException ( String.Format ( "CloneTo not implemented for expression {0}", this.GetType ())); } // // Clones an expression created by the parser. // // We only support expressions created by the parser so far, not // expressions that have been resolved (many more classes would need // to implement CloneTo). // // This infrastructure is here merely for Lambda expressions which // compile the same code using different type values for the same // arguments to find the correct overload // public virtual Expression Clone (CloneContext clonectx) { Expression cloned = (Expression) MemberwiseClone (); CloneTo (clonectx, cloned); return cloned; } // // Implementation of expression to expression tree conversion // public abstract Expression CreateExpressionTree (ResolveContext ec); protected Expression CreateExpressionFactoryCall (ResolveContext ec, string name, Arguments args) { return CreateExpressionFactoryCall (ec, name, null, args, loc); } protected Expression CreateExpressionFactoryCall (ResolveContext ec, string name, TypeArguments typeArguments, Arguments args) { return CreateExpressionFactoryCall (ec, name, typeArguments, args, loc); } public static Expression CreateExpressionFactoryCall (ResolveContext ec, string name, TypeArguments typeArguments, Arguments args, Location loc) { return new Invocation (new MemberAccess (CreateExpressionTypeExpression (ec, loc), name, typeArguments, loc), args); } protected static TypeExpr CreateExpressionTypeExpression (ResolveContext ec, Location loc) { var t = ec.Module.PredefinedTypes.Expression.Resolve (); if (t == null) return null; return new TypeExpression (t, loc); } // // Implemented by all expressions which support conversion from // compiler expression to invokable runtime expression. Used by // dynamic C# binder. // public virtual SLE.Expression MakeExpression (BuilderContext ctx) { throw new NotImplementedException ("MakeExpression for " + GetType ()); } public virtual object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } /// <summary> /// This is just a base class for expressions that can /// appear on statements (invocations, object creation, /// assignments, post/pre increment and decrement). The idea /// being that they would support an extra Emition interface that /// does not leave a result on the stack. /// </summary> public abstract class ExpressionStatement : Expression { public virtual void MarkReachable (Reachability rc) { } public ExpressionStatement ResolveStatement (BlockContext ec) { Expression e = Resolve (ec); if (e == null) return null; ExpressionStatement es = e as ExpressionStatement; if (es == null || e is AnonymousMethodBody) Error_InvalidExpressionStatement (ec); // // This is quite expensive warning, try to limit the damage // if (MemberAccess.IsValidDotExpression (e.Type) && !(e is Assign || e is Await)) { WarningAsyncWithoutWait (ec, e); } return es; } static void WarningAsyncWithoutWait (BlockContext bc, Expression e) { if (bc.CurrentAnonymousMethod is AsyncInitializer) { var awaiter = new AwaitStatement.AwaitableMemberAccess (e) { ProbingMode = true }; // // Need to do full resolve because GetAwaiter can be extension method // available only in this context // var mg = awaiter.Resolve (bc) as MethodGroupExpr; if (mg == null) return; var arguments = new Arguments (0); mg = mg.OverloadResolve (bc, ref arguments, null, OverloadResolver.Restrictions.ProbingOnly); if (mg == null) return; // // Use same check rules as for real await // var awaiter_definition = bc.Module.GetAwaiter (mg.BestCandidateReturnType); if (!awaiter_definition.IsValidPattern || !awaiter_definition.INotifyCompletion) return; bc.Report.Warning (4014, 1, e.Location, "The statement is not awaited and execution of current method continues before the call is completed. Consider using `await' operator"); return; } var inv = e as Invocation; if (inv != null && inv.MethodGroup != null && inv.MethodGroup.BestCandidate.IsAsync) { // The warning won't be reported for imported methods to maintain warning compatiblity with csc bc.Report.Warning (4014, 1, e.Location, "The statement is not awaited and execution of current method continues before the call is completed. Consider using `await' operator or calling `Wait' method"); return; } } /// <summary> /// Requests the expression to be emitted in a `statement' /// context. This means that no new value is left on the /// stack after invoking this method (constrasted with /// Emit that will always leave a value on the stack). /// </summary> public abstract void EmitStatement (EmitContext ec); public override void EmitSideEffect (EmitContext ec) { EmitStatement (ec); } } /// <summary> /// This kind of cast is used to encapsulate the child /// whose type is child.Type into an expression that is /// reported to return "return_type". This is used to encapsulate /// expressions which have compatible types, but need to be dealt /// at higher levels with. /// /// For example, a "byte" expression could be encapsulated in one /// of these as an "unsigned int". The type for the expression /// would be "unsigned int". /// /// </summary> public abstract class TypeCast : Expression { protected readonly Expression child; protected TypeCast (Expression child, TypeSpec return_type) { eclass = child.eclass; loc = child.Location; type = return_type; this.child = child; } public Expression Child { get { return child; } } public override bool ContainsEmitWithAwait () { return child.ContainsEmitWithAwait (); } public override Expression CreateExpressionTree (ResolveContext ec) { Arguments args = new Arguments (2); args.Add (new Argument (child.CreateExpressionTree (ec))); args.Add (new Argument (new TypeOf (type, loc))); if (type.IsPointer || child.Type.IsPointer) Error_PointerInsideExpressionTree (ec); return CreateExpressionFactoryCall (ec, ec.HasSet (ResolveContext.Options.CheckedScope) ? "ConvertChecked" : "Convert", args); } protected override Expression DoResolve (ResolveContext ec) { // This should never be invoked, we are born in fully // initialized state. return this; } public override void Emit (EmitContext ec) { child.Emit (ec); } public override void FlowAnalysis (FlowAnalysisContext fc) { child.FlowAnalysis (fc); } public override SLE.Expression MakeExpression (BuilderContext ctx) { #if STATIC return base.MakeExpression (ctx); #else return ctx.HasSet (BuilderContext.Options.CheckedScope) ? SLE.Expression.ConvertChecked (child.MakeExpression (ctx), type.GetMetaInfo ()) : SLE.Expression.Convert (child.MakeExpression (ctx), type.GetMetaInfo ()); #endif } protected override void CloneTo (CloneContext clonectx, Expression t) { // Nothing to clone } public override bool IsNull { get { return child.IsNull; } } } public class EmptyCast : TypeCast { EmptyCast (Expression child, TypeSpec target_type) : base (child, target_type) { } public static Expression Create (Expression child, TypeSpec type) { Constant c = child as Constant; if (c != null) { var enum_constant = c as EnumConstant; if (enum_constant != null) c = enum_constant.Child; if (!(c is ReducedExpression.ReducedConstantExpression)) { if (c.Type == type) return c; var res = c.ConvertImplicitly (type); if (res != null) return res; } } EmptyCast e = child as EmptyCast; if (e != null) return new EmptyCast (e.child, type); return new EmptyCast (child, type); } public override void EmitBranchable (EmitContext ec, Label label, bool on_true) { child.EmitBranchable (ec, label, on_true); } public override void EmitSideEffect (EmitContext ec) { child.EmitSideEffect (ec); } } // // Used for predefined type user operator (no obsolete check, etc.) // public class OperatorCast : TypeCast { readonly MethodSpec conversion_operator; public OperatorCast (Expression expr, TypeSpec target_type) : this (expr, target_type, target_type, false) { } public OperatorCast (Expression expr, TypeSpec target_type, bool find_explicit) : this (expr, target_type, target_type, find_explicit) { } public OperatorCast (Expression expr, TypeSpec declaringType, TypeSpec returnType, bool isExplicit) : base (expr, returnType) { var op = isExplicit ? Operator.OpType.Explicit : Operator.OpType.Implicit; var mi = MemberCache.GetUserOperator (declaringType, op, true); if (mi != null) { foreach (MethodSpec oper in mi) { if (oper.ReturnType != returnType) continue; if (oper.Parameters.Types[0] == expr.Type) { conversion_operator = oper; return; } } } throw new InternalErrorException ("Missing predefined user operator between `{0}' and `{1}'", returnType.GetSignatureForError (), expr.Type.GetSignatureForError ()); } public override void Emit (EmitContext ec) { child.Emit (ec); ec.Emit (OpCodes.Call, conversion_operator); } } // // Constant specialization of EmptyCast. // We need to special case this since an empty cast of // a constant is still a constant. // public class EmptyConstantCast : Constant { public readonly Constant child; public EmptyConstantCast (Constant child, TypeSpec type) : base (child.Location) { if (child == null) throw new ArgumentNullException ("child"); this.child = child; this.eclass = child.eclass; this.type = type; } public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type) { if (child.Type == target_type) return child; // FIXME: check that 'type' can be converted to 'target_type' first return child.ConvertExplicitly (in_checked_context, target_type); } public override Expression CreateExpressionTree (ResolveContext ec) { Arguments args = Arguments.CreateForExpressionTree (ec, null, child.CreateExpressionTree (ec), new TypeOf (type, loc)); if (type.IsPointer) Error_PointerInsideExpressionTree (ec); return CreateExpressionFactoryCall (ec, "Convert", args); } public override bool IsDefaultValue { get { return child.IsDefaultValue; } } public override bool IsNegative { get { return child.IsNegative; } } public override bool IsNull { get { return child.IsNull; } } public override bool IsOneInteger { get { return child.IsOneInteger; } } public override bool IsSideEffectFree { get { return child.IsSideEffectFree; } } public override bool IsZeroInteger { get { return child.IsZeroInteger; } } public override void Emit (EmitContext ec) { child.Emit (ec); } public override void EmitBranchable (EmitContext ec, Label label, bool on_true) { child.EmitBranchable (ec, label, on_true); // Only to make verifier happy if (TypeManager.IsGenericParameter (type) && child.IsNull) ec.Emit (OpCodes.Unbox_Any, type); } public override void EmitSideEffect (EmitContext ec) { child.EmitSideEffect (ec); } public override object GetValue () { return child.GetValue (); } public override string GetValueAsLiteral () { return child.GetValueAsLiteral (); } public override long GetValueAsLong () { return child.GetValueAsLong (); } public override Constant ConvertImplicitly (TypeSpec target_type) { if (type == target_type) return this; // FIXME: Do we need to check user conversions? if (!Convert.ImplicitStandardConversionExists (this, target_type)) return null; return child.ConvertImplicitly (target_type); } } /// <summary> /// This class is used to wrap literals which belong inside Enums /// </summary> public class EnumConstant : Constant { public Constant Child; public EnumConstant (Constant child, TypeSpec enum_type) : base (child.Location) { this.Child = child; this.eclass = ExprClass.Value; this.type = enum_type; } protected EnumConstant (Location loc) : base (loc) { } public override void Emit (EmitContext ec) { Child.Emit (ec); } public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType) { Child.EncodeAttributeValue (rc, enc, Child.Type, parameterType); } public override void EmitBranchable (EmitContext ec, Label label, bool on_true) { Child.EmitBranchable (ec, label, on_true); } public override void EmitSideEffect (EmitContext ec) { Child.EmitSideEffect (ec); } public override string GetSignatureForError() { return Type.GetSignatureForError (); } public override object GetValue () { return Child.GetValue (); } #if !STATIC public override object GetTypedValue () { // // The method can be used in dynamic context only (on closed types) // // System.Enum.ToObject cannot be called on dynamic types // EnumBuilder has to be used, but we cannot use EnumBuilder // because it does not properly support generics // return System.Enum.ToObject (type.GetMetaInfo (), Child.GetValue ()); } #endif public override string GetValueAsLiteral () { return Child.GetValueAsLiteral (); } public override long GetValueAsLong () { return Child.GetValueAsLong (); } public EnumConstant Increment() { return new EnumConstant (((IntegralConstant) Child).Increment (), type); } public override bool IsDefaultValue { get { return Child.IsDefaultValue; } } public override bool IsSideEffectFree { get { return Child.IsSideEffectFree; } } public override bool IsZeroInteger { get { return Child.IsZeroInteger; } } public override bool IsNegative { get { return Child.IsNegative; } } public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type) { if (Child.Type == target_type) return Child; return Child.ConvertExplicitly (in_checked_context, target_type); } public override Constant ConvertImplicitly (TypeSpec type) { if (this.type == type) { return this; } if (!Convert.ImplicitStandardConversionExists (this, type)){ return null; } return Child.ConvertImplicitly (type); } } /// <summary> /// This kind of cast is used to encapsulate Value Types in objects. /// /// The effect of it is to box the value type emitted by the previous /// operation. /// </summary> public class BoxedCast : TypeCast { public BoxedCast (Expression expr, TypeSpec target_type) : base (expr, target_type) { eclass = ExprClass.Value; } protected override Expression DoResolve (ResolveContext ec) { // This should never be invoked, we are born in fully // initialized state. return this; } public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType) { // Only boxing to object type is supported if (targetType.BuiltinType != BuiltinTypeSpec.Type.Object) { base.EncodeAttributeValue (rc, enc, targetType, parameterType); return; } enc.Encode (child.Type); child.EncodeAttributeValue (rc, enc, child.Type, parameterType); } public override void Emit (EmitContext ec) { base.Emit (ec); ec.Emit (OpCodes.Box, child.Type); } public override void EmitSideEffect (EmitContext ec) { // boxing is side-effectful, since it involves runtime checks, except when boxing to Object or ValueType // so, we need to emit the box+pop instructions in most cases if (child.Type.IsStruct && (type.BuiltinType == BuiltinTypeSpec.Type.Object || type.BuiltinType == BuiltinTypeSpec.Type.ValueType)) child.EmitSideEffect (ec); else base.EmitSideEffect (ec); } } public class UnboxCast : TypeCast { public UnboxCast (Expression expr, TypeSpec return_type) : base (expr, return_type) { } protected override Expression DoResolve (ResolveContext ec) { // This should never be invoked, we are born in fully // initialized state. return this; } public override void Emit (EmitContext ec) { base.Emit (ec); ec.Emit (OpCodes.Unbox_Any, type); } } /// <summary> /// This is used to perform explicit numeric conversions. /// /// Explicit numeric conversions might trigger exceptions in a checked /// context, so they should generate the conv.ovf opcodes instead of /// conv opcodes. /// </summary> public class ConvCast : TypeCast { public enum Mode : byte { I1_U1, I1_U2, I1_U4, I1_U8, I1_CH, U1_I1, U1_CH, I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH, U2_I1, U2_U1, U2_I2, U2_CH, I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH, U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH, I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH, I8_I, U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH, U8_I, CH_I1, CH_U1, CH_I2, R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH, R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4, I_I8, } Mode mode; public ConvCast (Expression child, TypeSpec return_type, Mode m) : base (child, return_type) { mode = m; } protected override Expression DoResolve (ResolveContext ec) { // This should never be invoked, we are born in fully // initialized state. return this; } public override string ToString () { return String.Format ("ConvCast ({0}, {1})", mode, child); } public override void Emit (EmitContext ec) { base.Emit (ec); Emit (ec, mode); } public static void Emit (EmitContext ec, Mode mode) { if (ec.HasSet (EmitContext.Options.CheckedScope)) { switch (mode){ case Mode.I1_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break; case Mode.I1_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break; case Mode.I1_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break; case Mode.I1_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break; case Mode.I1_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break; case Mode.U1_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break; case Mode.U1_CH: /* nothing */ break; case Mode.I2_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break; case Mode.I2_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break; case Mode.I2_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break; case Mode.I2_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break; case Mode.I2_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break; case Mode.I2_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break; case Mode.U2_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break; case Mode.U2_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break; case Mode.U2_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break; case Mode.U2_CH: /* nothing */ break; case Mode.I4_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break; case Mode.I4_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break; case Mode.I4_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break; case Mode.I4_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break; case Mode.I4_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break; case Mode.I4_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break; case Mode.I4_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break; case Mode.U4_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break; case Mode.U4_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break; case Mode.U4_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break; case Mode.U4_U2: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break; case Mode.U4_I4: ec.Emit (OpCodes.Conv_Ovf_I4_Un); break; case Mode.U4_CH: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break; case Mode.I8_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break; case Mode.I8_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break; case Mode.I8_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break; case Mode.I8_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break; case Mode.I8_I4: ec.Emit (OpCodes.Conv_Ovf_I4); break; case Mode.I8_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break; case Mode.I8_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break; case Mode.I8_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break; case Mode.I8_I: ec.Emit (OpCodes.Conv_Ovf_U); break; case Mode.U8_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break; case Mode.U8_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break; case Mode.U8_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break; case Mode.U8_U2: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break; case Mode.U8_I4: ec.Emit (OpCodes.Conv_Ovf_I4_Un); break; case Mode.U8_U4: ec.Emit (OpCodes.Conv_Ovf_U4_Un); break; case Mode.U8_I8: ec.Emit (OpCodes.Conv_Ovf_I8_Un); break; case Mode.U8_CH: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break; case Mode.U8_I: ec.Emit (OpCodes.Conv_Ovf_U_Un); break; case Mode.CH_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break; case Mode.CH_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break; case Mode.CH_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break; case Mode.R4_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break; case Mode.R4_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break; case Mode.R4_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break; case Mode.R4_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break; case Mode.R4_I4: ec.Emit (OpCodes.Conv_Ovf_I4); break; case Mode.R4_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break; case Mode.R4_I8: ec.Emit (OpCodes.Conv_Ovf_I8); break; case Mode.R4_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break; case Mode.R4_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break; case Mode.R8_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break; case Mode.R8_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break; case Mode.R8_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break; case Mode.R8_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break; case Mode.R8_I4: ec.Emit (OpCodes.Conv_Ovf_I4); break; case Mode.R8_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break; case Mode.R8_I8: ec.Emit (OpCodes.Conv_Ovf_I8); break; case Mode.R8_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break; case Mode.R8_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break; case Mode.R8_R4: ec.Emit (OpCodes.Conv_R4); break; case Mode.I_I8: ec.Emit (OpCodes.Conv_Ovf_I8_Un); break; } } else { switch (mode){ case Mode.I1_U1: ec.Emit (OpCodes.Conv_U1); break; case Mode.I1_U2: ec.Emit (OpCodes.Conv_U2); break; case Mode.I1_U4: ec.Emit (OpCodes.Conv_U4); break; case Mode.I1_U8: ec.Emit (OpCodes.Conv_I8); break; case Mode.I1_CH: ec.Emit (OpCodes.Conv_U2); break; case Mode.U1_I1: ec.Emit (OpCodes.Conv_I1); break; case Mode.U1_CH: ec.Emit (OpCodes.Conv_U2); break; case Mode.I2_I1: ec.Emit (OpCodes.Conv_I1); break; case Mode.I2_U1: ec.Emit (OpCodes.Conv_U1); break; case Mode.I2_U2: ec.Emit (OpCodes.Conv_U2); break; case Mode.I2_U4: ec.Emit (OpCodes.Conv_U4); break; case Mode.I2_U8: ec.Emit (OpCodes.Conv_I8); break; case Mode.I2_CH: ec.Emit (OpCodes.Conv_U2); break; case Mode.U2_I1: ec.Emit (OpCodes.Conv_I1); break; case Mode.U2_U1: ec.Emit (OpCodes.Conv_U1); break; case Mode.U2_I2: ec.Emit (OpCodes.Conv_I2); break; case Mode.U2_CH: /* nothing */ break; case Mode.I4_I1: ec.Emit (OpCodes.Conv_I1); break; case Mode.I4_U1: ec.Emit (OpCodes.Conv_U1); break; case Mode.I4_I2: ec.Emit (OpCodes.Conv_I2); break; case Mode.I4_U4: /* nothing */ break; case Mode.I4_U2: ec.Emit (OpCodes.Conv_U2); break; case Mode.I4_U8: ec.Emit (OpCodes.Conv_I8); break; case Mode.I4_CH: ec.Emit (OpCodes.Conv_U2); break; case Mode.U4_I1: ec.Emit (OpCodes.Conv_I1); break; case Mode.U4_U1: ec.Emit (OpCodes.Conv_U1); break; case Mode.U4_I2: ec.Emit (OpCodes.Conv_I2); break; case Mode.U4_U2: ec.Emit (OpCodes.Conv_U2); break; case Mode.U4_I4: /* nothing */ break; case Mode.U4_CH: ec.Emit (OpCodes.Conv_U2); break; case Mode.I8_I1: ec.Emit (OpCodes.Conv_I1); break; case Mode.I8_U1: ec.Emit (OpCodes.Conv_U1); break; case Mode.I8_I2: ec.Emit (OpCodes.Conv_I2); break; case Mode.I8_U2: ec.Emit (OpCodes.Conv_U2); break; case Mode.I8_I4: ec.Emit (OpCodes.Conv_I4); break; case Mode.I8_U4: ec.Emit (OpCodes.Conv_U4); break; case Mode.I8_U8: /* nothing */ break; case Mode.I8_CH: ec.Emit (OpCodes.Conv_U2); break; case Mode.I8_I: ec.Emit (OpCodes.Conv_U); break; case Mode.U8_I1: ec.Emit (OpCodes.Conv_I1); break; case Mode.U8_U1: ec.Emit (OpCodes.Conv_U1); break; case Mode.U8_I2: ec.Emit (OpCodes.Conv_I2); break; case Mode.U8_U2: ec.Emit (OpCodes.Conv_U2); break; case Mode.U8_I4: ec.Emit (OpCodes.Conv_I4); break; case Mode.U8_U4: ec.Emit (OpCodes.Conv_U4); break; case Mode.U8_I8: /* nothing */ break; case Mode.U8_CH: ec.Emit (OpCodes.Conv_U2); break; case Mode.U8_I: ec.Emit (OpCodes.Conv_U); break; case Mode.CH_I1: ec.Emit (OpCodes.Conv_I1); break; case Mode.CH_U1: ec.Emit (OpCodes.Conv_U1); break; case Mode.CH_I2: ec.Emit (OpCodes.Conv_I2); break; case Mode.R4_I1: ec.Emit (OpCodes.Conv_I1); break; case Mode.R4_U1: ec.Emit (OpCodes.Conv_U1); break; case Mode.R4_I2: ec.Emit (OpCodes.Conv_I2); break; case Mode.R4_U2: ec.Emit (OpCodes.Conv_U2); break; case Mode.R4_I4: ec.Emit (OpCodes.Conv_I4); break; case Mode.R4_U4: ec.Emit (OpCodes.Conv_U4); break; case Mode.R4_I8: ec.Emit (OpCodes.Conv_I8); break; case Mode.R4_U8: ec.Emit (OpCodes.Conv_U8); break; case Mode.R4_CH: ec.Emit (OpCodes.Conv_U2); break; case Mode.R8_I1: ec.Emit (OpCodes.Conv_I1); break; case Mode.R8_U1: ec.Emit (OpCodes.Conv_U1); break; case Mode.R8_I2: ec.Emit (OpCodes.Conv_I2); break; case Mode.R8_U2: ec.Emit (OpCodes.Conv_U2); break; case Mode.R8_I4: ec.Emit (OpCodes.Conv_I4); break; case Mode.R8_U4: ec.Emit (OpCodes.Conv_U4); break; case Mode.R8_I8: ec.Emit (OpCodes.Conv_I8); break; case Mode.R8_U8: ec.Emit (OpCodes.Conv_U8); break; case Mode.R8_CH: ec.Emit (OpCodes.Conv_U2); break; case Mode.R8_R4: ec.Emit (OpCodes.Conv_R4); break; case Mode.I_I8: ec.Emit (OpCodes.Conv_U8); break; } } } } class OpcodeCast : TypeCast { readonly OpCode op; public OpcodeCast (Expression child, TypeSpec return_type, OpCode op) : base (child, return_type) { this.op = op; } protected override Expression DoResolve (ResolveContext ec) { // This should never be invoked, we are born in fully // initialized state. return this; } public override void Emit (EmitContext ec) { base.Emit (ec); ec.Emit (op); } public TypeSpec UnderlyingType { get { return child.Type; } } } // // Opcode casts expression with 2 opcodes but only // single expression tree node // class OpcodeCastDuplex : OpcodeCast { readonly OpCode second; public OpcodeCastDuplex (Expression child, TypeSpec returnType, OpCode first, OpCode second) : base (child, returnType, first) { this.second = second; } public override void Emit (EmitContext ec) { base.Emit (ec); ec.Emit (second); } } /// <summary> /// This kind of cast is used to encapsulate a child and cast it /// to the class requested /// </summary> public sealed class ClassCast : TypeCast { readonly bool forced; public ClassCast (Expression child, TypeSpec return_type) : base (child, return_type) { } public ClassCast (Expression child, TypeSpec return_type, bool forced) : base (child, return_type) { this.forced = forced; } public override void Emit (EmitContext ec) { base.Emit (ec); bool gen = TypeManager.IsGenericParameter (child.Type); if (gen) ec.Emit (OpCodes.Box, child.Type); if (type.IsGenericParameter) { ec.Emit (OpCodes.Unbox_Any, type); return; } if (gen && !forced) return; ec.Emit (OpCodes.Castclass, type); } } // // Created during resolving pahse when an expression is wrapped or constantified // and original expression can be used later (e.g. for expression trees) // public class ReducedExpression : Expression { public sealed class ReducedConstantExpression : EmptyConstantCast { readonly Expression orig_expr; public ReducedConstantExpression (Constant expr, Expression orig_expr) : base (expr, expr.Type) { this.orig_expr = orig_expr; } public Expression OriginalExpression { get { return orig_expr; } } public override Constant ConvertImplicitly (TypeSpec target_type) { Constant c = base.ConvertImplicitly (target_type); if (c != null) c = new ReducedConstantExpression (c, orig_expr); return c; } public override Expression CreateExpressionTree (ResolveContext ec) { return orig_expr.CreateExpressionTree (ec); } public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type) { Constant c = base.ConvertExplicitly (in_checked_context, target_type); if (c != null) c = new ReducedConstantExpression (c, orig_expr); return c; } public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType, TypeSpec parameterType) { // // LAMESPEC: Reduced conditional expression is allowed as an attribute argument // if (orig_expr is Conditional) child.EncodeAttributeValue (rc, enc, targetType,parameterType); else base.EncodeAttributeValue (rc, enc, targetType, parameterType); } } sealed class ReducedExpressionStatement : ExpressionStatement { readonly Expression orig_expr; readonly ExpressionStatement stm; public ReducedExpressionStatement (ExpressionStatement stm, Expression orig) { this.orig_expr = orig; this.stm = stm; this.eclass = stm.eclass; this.type = stm.Type; this.loc = orig.Location; } public override bool ContainsEmitWithAwait () { return stm.ContainsEmitWithAwait (); } public override Expression CreateExpressionTree (ResolveContext ec) { return orig_expr.CreateExpressionTree (ec); } protected override Expression DoResolve (ResolveContext ec) { return this; } public override void Emit (EmitContext ec) { stm.Emit (ec); } public override void EmitStatement (EmitContext ec) { stm.EmitStatement (ec); } public override void FlowAnalysis (FlowAnalysisContext fc) { stm.FlowAnalysis (fc); } } readonly Expression expr, orig_expr; private ReducedExpression (Expression expr, Expression orig_expr) { this.expr = expr; this.eclass = expr.eclass; this.type = expr.Type; this.orig_expr = orig_expr; this.loc = orig_expr.Location; } #region Properties public override bool IsSideEffectFree { get { return expr.IsSideEffectFree; } } public Expression OriginalExpression { get { return orig_expr; } } #endregion public override bool ContainsEmitWithAwait () { return expr.ContainsEmitWithAwait (); } // // Creates fully resolved expression switcher // public static Constant Create (Constant expr, Expression original_expr) { if (expr.eclass == ExprClass.Unresolved) throw new ArgumentException ("Unresolved expression"); return new ReducedConstantExpression (expr, original_expr); } public static ExpressionStatement Create (ExpressionStatement s, Expression orig) { return new ReducedExpressionStatement (s, orig); } public static Expression Create (Expression expr, Expression original_expr) { return Create (expr, original_expr, true); } // // Creates unresolved reduce expression. The original expression has to be // already resolved. Created expression is constant based based on `expr' // value unless canBeConstant is used // public static Expression Create (Expression expr, Expression original_expr, bool canBeConstant) { if (canBeConstant) { Constant c = expr as Constant; if (c != null) return Create (c, original_expr); } ExpressionStatement s = expr as ExpressionStatement; if (s != null) return Create (s, original_expr); if (expr.eclass == ExprClass.Unresolved) throw new ArgumentException ("Unresolved expression"); return new ReducedExpression (expr, original_expr); } public override Expression CreateExpressionTree (ResolveContext ec) { return orig_expr.CreateExpressionTree (ec); } protected override Expression DoResolve (ResolveContext ec) { return this; } public override void Emit (EmitContext ec) { expr.Emit (ec); } public override Expression EmitToField (EmitContext ec) { return expr.EmitToField(ec); } public override void EmitBranchable (EmitContext ec, Label target, bool on_true) { expr.EmitBranchable (ec, target, on_true); } public override void FlowAnalysis (FlowAnalysisContext fc) { expr.FlowAnalysis (fc); } public override SLE.Expression MakeExpression (BuilderContext ctx) { return orig_expr.MakeExpression (ctx); } } // // Standard composite pattern // public abstract class CompositeExpression : Expression { protected Expression expr; protected CompositeExpression (Expression expr) { this.expr = expr; this.loc = expr.Location; } public override bool ContainsEmitWithAwait () { return expr.ContainsEmitWithAwait (); } public override Expression CreateExpressionTree (ResolveContext rc) { return expr.CreateExpressionTree (rc); } public Expression Child { get { return expr; } } protected override Expression DoResolve (ResolveContext rc) { expr = expr.Resolve (rc); if (expr == null) return null; type = expr.Type; eclass = expr.eclass; return this; } public override void Emit (EmitContext ec) { expr.Emit (ec); } public override bool IsNull { get { return expr.IsNull; } } } // // Base of expressions used only to narrow resolve flow // public abstract class ShimExpression : Expression { protected Expression expr; protected ShimExpression (Expression expr) { this.expr = expr; } public Expression Expr { get { return expr; } } protected override void CloneTo (CloneContext clonectx, Expression t) { if (expr == null) return; ShimExpression target = (ShimExpression) t; target.expr = expr.Clone (clonectx); } public override bool ContainsEmitWithAwait () { return expr.ContainsEmitWithAwait (); } public override Expression CreateExpressionTree (ResolveContext ec) { throw new NotSupportedException ("ET"); } public override void Emit (EmitContext ec) { throw new InternalErrorException ("Missing Resolve call"); } } public class UnreachableExpression : Expression { public UnreachableExpression (Expression expr) { this.loc = expr.Location; } public override Expression CreateExpressionTree (ResolveContext ec) { // TODO: is it ok throw new NotImplementedException (); } protected override Expression DoResolve (ResolveContext rc) { throw new NotSupportedException (); } public override void FlowAnalysis (FlowAnalysisContext fc) { fc.Report.Warning (429, 4, loc, "Unreachable expression code detected"); } public override void Emit (EmitContext ec) { } public override void EmitBranchable (EmitContext ec, Label target, bool on_true) { } } // // Unresolved type name expressions // public abstract class ATypeNameExpression : FullNamedExpression { string name; protected TypeArguments targs; protected ATypeNameExpression (string name, Location l) { this.name = name; loc = l; } protected ATypeNameExpression (string name, TypeArguments targs, Location l) { this.name = name; this.targs = targs; loc = l; } protected ATypeNameExpression (string name, int arity, Location l) : this (name, new UnboundTypeArguments (arity), l) { } #region Properties protected int Arity { get { return targs == null ? 0 : targs.Count; } } public bool HasTypeArguments { get { return targs != null && !targs.IsEmpty; } } public string Name { get { return name; } set { name = value; } } public TypeArguments TypeArguments { get { return targs; } } #endregion public override bool Equals (object obj) { ATypeNameExpression atne = obj as ATypeNameExpression; return atne != null && atne.Name == Name && (targs == null || targs.Equals (atne.targs)); } protected void Error_OpenGenericTypeIsNotAllowed (IMemberContext mc) { mc.Module.Compiler.Report.Error (7003, Location, "Unbound generic name is not valid in this context"); } public override int GetHashCode () { return Name.GetHashCode (); } // TODO: Move it to MemberCore public static string GetMemberType (MemberCore mc) { if (mc is Property) return "property"; if (mc is Indexer) return "indexer"; if (mc is FieldBase) return "field"; if (mc is MethodCore) return "method"; if (mc is EnumMember) return "enum"; if (mc is Event) return "event"; return "type"; } public override string GetSignatureForError () { if (targs != null) { return Name + "<" + targs.GetSignatureForError () + ">"; } return Name; } public abstract Expression LookupNameExpression (ResolveContext rc, MemberLookupRestrictions restriction); } /// <summary> /// SimpleName expressions are formed of a single word and only happen at the beginning /// of a dotted-name. /// </summary> public class SimpleName : ATypeNameExpression { public SimpleName (string name, Location l) : base (name, l) { } public SimpleName (string name, TypeArguments args, Location l) : base (name, args, l) { } public SimpleName (string name, int arity, Location l) : base (name, arity, l) { } public SimpleName GetMethodGroup () { return new SimpleName (Name, targs, loc); } protected override Expression DoResolve (ResolveContext rc) { return SimpleNameResolve (rc, null); } public override Expression DoResolveLValue (ResolveContext ec, Expression right_side) { return SimpleNameResolve (ec, right_side); } public void Error_NameDoesNotExist (ResolveContext rc) { rc.Report.Error (103, loc, "The name `{0}' does not exist in the current context", Name); } protected virtual void Error_TypeOrNamespaceNotFound (IMemberContext ctx) { if (ctx.CurrentType != null) { var member = MemberLookup (ctx, false, ctx.CurrentType, Name, 0, MemberLookupRestrictions.ExactArity, loc) as MemberExpr; if (member != null) { Error_UnexpectedKind (ctx, member, "type", member.KindName, loc); return; } } var report = ctx.Module.Compiler.Report; var retval = ctx.LookupNamespaceOrType (Name, Arity, LookupMode.IgnoreAccessibility, loc); if (retval != null) { report.SymbolRelatedToPreviousError (retval.Type); ErrorIsInaccesible (ctx, retval.GetSignatureForError (), loc); return; } retval = ctx.LookupNamespaceOrType (Name, -System.Math.Max (1, Arity), LookupMode.Probing, loc); if (retval != null) { Error_TypeArgumentsCannotBeUsed (ctx, retval.Type, loc); return; } var ns_candidates = ctx.Module.GlobalRootNamespace.FindTypeNamespaces (ctx, Name, Arity); if (ns_candidates != null) { if (ctx is UsingAliasNamespace.AliasContext) { report.Error (246, loc, "The type or namespace name `{1}' could not be found. Consider using fully qualified name `{0}.{1}'", ns_candidates[0], Name); } else { string usings = string.Join ("' or `", ns_candidates.ToArray ()); report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing `{1}' using directive?", Name, usings); } } else { report.Error (246, loc, "The type or namespace name `{0}' could not be found. Are you missing an assembly reference?", Name); } } public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc, bool allowUnboundTypeArguments) { FullNamedExpression fne = mc.LookupNamespaceOrType (Name, Arity, LookupMode.Normal, loc); if (fne != null) { if (fne.Type != null && Arity > 0) { if (HasTypeArguments) { GenericTypeExpr ct = new GenericTypeExpr (fne.Type, targs, loc); if (ct.ResolveAsType (mc) == null) return null; return ct; } if (!allowUnboundTypeArguments) Error_OpenGenericTypeIsNotAllowed (mc); return new GenericOpenTypeExpr (fne.Type, loc); } // // dynamic namespace is ignored when dynamic is allowed (does not apply to types) // if (!(fne is NamespaceExpression)) return fne; } if (Arity == 0 && Name == "dynamic" && mc.Module.Compiler.Settings.Version > LanguageVersion.V_3) { if (!mc.Module.PredefinedAttributes.Dynamic.IsDefined) { mc.Module.Compiler.Report.Error (1980, Location, "Dynamic keyword requires `{0}' to be defined. Are you missing System.Core.dll assembly reference?", mc.Module.PredefinedAttributes.Dynamic.GetSignatureForError ()); } fne = new DynamicTypeExpr (loc); fne.ResolveAsType (mc); } if (fne != null) return fne; Error_TypeOrNamespaceNotFound (mc); return null; } public bool IsPossibleTypeOrNamespace (IMemberContext mc) { return mc.LookupNamespaceOrType (Name, Arity, LookupMode.Probing, loc) != null; } public override Expression LookupNameExpression (ResolveContext rc, MemberLookupRestrictions restrictions) { int lookup_arity = Arity; bool errorMode = false; Expression e; Block current_block = rc.CurrentBlock; INamedBlockVariable variable = null; bool variable_found = false; while (true) { // // Stage 1: binding to local variables or parameters // // LAMESPEC: It should take invocableOnly into account but that would break csc compatibility // if (current_block != null && lookup_arity == 0) { if (current_block.ParametersBlock.TopBlock.GetLocalName (Name, current_block.Original, ref variable)) { if (!variable.IsDeclared) { // We found local name in accessible block but it's not // initialized yet, maybe the user wanted to bind to something else errorMode = true; variable_found = true; } else { e = variable.CreateReferenceExpression (rc, loc); if (e != null) { if (Arity > 0) Error_TypeArgumentsCannotBeUsed (rc, "variable", Name, loc); return e; } } } } // // Stage 2: Lookup members if we are inside a type up to top level type for nested types // TypeSpec member_type = rc.CurrentType; for (; member_type != null; member_type = member_type.DeclaringType) { e = MemberLookup (rc, errorMode, member_type, Name, lookup_arity, restrictions, loc); if (e == null) continue; var me = e as MemberExpr; if (me == null) { // The name matches a type, defer to ResolveAsTypeStep if (e is TypeExpr) break; continue; } if (errorMode) { if (variable != null) { if (me is FieldExpr || me is ConstantExpr || me is EventExpr || me is PropertyExpr) { rc.Report.Error (844, loc, "A local variable `{0}' cannot be used before it is declared. Consider renaming the local variable when it hides the member `{1}'", Name, me.GetSignatureForError ()); } else { break; } } else if (me is MethodGroupExpr || me is PropertyExpr || me is IndexerExpr) { // Leave it to overload resolution to report correct error } else { // TODO: rc.Report.SymbolRelatedToPreviousError () ErrorIsInaccesible (rc, me.GetSignatureForError (), loc); } } else { // LAMESPEC: again, ignores InvocableOnly if (variable != null) { rc.Report.SymbolRelatedToPreviousError (variable.Location, Name); rc.Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", Name); } // // MemberLookup does not check accessors availability, this is actually needed for properties only // var pe = me as PropertyExpr; if (pe != null) { // Break as there is no other overload available anyway if ((restrictions & MemberLookupRestrictions.ReadAccess) != 0) { if (!pe.PropertyInfo.HasGet || !pe.PropertyInfo.Get.IsAccessible (rc)) break; pe.Getter = pe.PropertyInfo.Get; } else { if (!pe.PropertyInfo.HasSet || !pe.PropertyInfo.Set.IsAccessible (rc)) break; pe.Setter = pe.PropertyInfo.Set; } } } // TODO: It's used by EventExpr -> FieldExpr transformation only // TODO: Should go to MemberAccess me = me.ResolveMemberAccess (rc, null, null); if (Arity > 0) { targs.Resolve (rc); me.SetTypeArguments (rc, targs); } return me; } // // Stage 3: Lookup nested types, namespaces and type parameters in the context // if ((restrictions & MemberLookupRestrictions.InvocableOnly) == 0 && !variable_found) { if (IsPossibleTypeOrNamespace (rc)) { if (variable != null) { rc.Report.SymbolRelatedToPreviousError (variable.Location, Name); rc.Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", Name); } return ResolveAsTypeOrNamespace (rc, false); } } var mg = NamespaceContainer.LookupStaticUsings (rc, Name, Arity, loc); if (mg != null) { if (Arity > 0) { targs.Resolve (rc); mg.SetTypeArguments (rc, targs); } return mg; } if (Name == "nameof") return new NameOf (this); if (errorMode) { if (variable_found) { rc.Report.Error (841, loc, "A local variable `{0}' cannot be used before it is declared", Name); } else { if (Arity > 0) { var tparams = rc.CurrentTypeParameters; if (tparams != null) { if (tparams.Find (Name) != null) { Error_TypeArgumentsCannotBeUsed (rc, "type parameter", Name, loc); return null; } } var ct = rc.CurrentType; do { if (ct.MemberDefinition.TypeParametersCount > 0) { foreach (var ctp in ct.MemberDefinition.TypeParameters) { if (ctp.Name == Name) { Error_TypeArgumentsCannotBeUsed (rc, "type parameter", Name, loc); return null; } } } ct = ct.DeclaringType; } while (ct != null); } if ((restrictions & MemberLookupRestrictions.InvocableOnly) == 0) { e = rc.LookupNamespaceOrType (Name, Arity, LookupMode.IgnoreAccessibility, loc); if (e != null) { rc.Report.SymbolRelatedToPreviousError (e.Type); ErrorIsInaccesible (rc, e.GetSignatureForError (), loc); return e; } } else { var me = MemberLookup (rc, false, rc.CurrentType, Name, Arity, restrictions & ~MemberLookupRestrictions.InvocableOnly, loc) as MemberExpr; if (me != null) { Error_UnexpectedKind (rc, me, "method group", me.KindName, loc); return ErrorExpression.Instance; } } e = rc.LookupNamespaceOrType (Name, -System.Math.Max (1, Arity), LookupMode.Probing, loc); if (e != null) { if (e.Type.Arity != Arity && (restrictions & MemberLookupRestrictions.IgnoreArity) == 0) { Error_TypeArgumentsCannotBeUsed (rc, e.Type, loc); return e; } if (e is TypeExpr) { // TypeExpression does not have correct location if (e is TypeExpression) e = new TypeExpression (e.Type, loc); return e; } } Error_NameDoesNotExist (rc); } return ErrorExpression.Instance; } if (rc.Module.Evaluator != null) { var fi = rc.Module.Evaluator.LookupField (Name); if (fi != null) return new FieldExpr (fi.Item1, loc); } lookup_arity = 0; errorMode = true; } } Expression SimpleNameResolve (ResolveContext ec, Expression right_side) { Expression e = LookupNameExpression (ec, right_side == null ? MemberLookupRestrictions.ReadAccess : MemberLookupRestrictions.None); if (e == null) return null; if (e is FullNamedExpression && e.eclass != ExprClass.Unresolved) { Error_UnexpectedKind (ec, e, "variable", e.ExprClassName, loc); return e; } if (right_side != null) { e = e.ResolveLValue (ec, right_side); } else { e = e.Resolve (ec); } return e; } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } /// <summary> /// Represents a namespace or a type. The name of the class was inspired by /// section 10.8.1 (Fully Qualified Names). /// </summary> public abstract class FullNamedExpression : Expression { protected override void CloneTo (CloneContext clonectx, Expression target) { // Do nothing, most unresolved type expressions cannot be // resolved to different type } public override bool ContainsEmitWithAwait () { return false; } public override Expression CreateExpressionTree (ResolveContext ec) { throw new NotSupportedException ("ET"); } public abstract FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc, bool allowUnboundTypeArguments); // // This is used to resolve the expression as a type, a null // value will be returned if the expression is not a type // reference // public override TypeSpec ResolveAsType (IMemberContext mc, bool allowUnboundTypeArguments = false) { FullNamedExpression fne = ResolveAsTypeOrNamespace (mc, allowUnboundTypeArguments); if (fne == null) return null; TypeExpr te = fne as TypeExpr; if (te == null) { Error_UnexpectedKind (mc, fne, "type", fne.ExprClassName, loc); return null; } te.loc = loc; type = te.Type; var dep = type.GetMissingDependencies (); if (dep != null) { ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc); } if (type.Kind == MemberKind.Void) { mc.Module.Compiler.Report.Error (673, loc, "System.Void cannot be used from C#. Consider using `void'"); } // // Obsolete checks cannot be done when resolving base context as they // require type dependencies to be set but we are in process of resolving them // if (!(mc is TypeDefinition.BaseContext) && !(mc is UsingAliasNamespace.AliasContext)) { ObsoleteAttribute obsolete_attr = type.GetAttributeObsolete (); if (obsolete_attr != null && !mc.IsObsolete) { AttributeTester.Report_ObsoleteMessage (obsolete_attr, te.GetSignatureForError (), Location, mc.Module.Compiler.Report); } } return type; } public override void Emit (EmitContext ec) { throw new InternalErrorException ("FullNamedExpression `{0}' found in resolved tree", GetSignatureForError ()); } } /// <summary> /// Expression that evaluates to a type /// </summary> public abstract class TypeExpr : FullNamedExpression { public sealed override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc, bool allowUnboundTypeArguments) { ResolveAsType (mc); return this; } protected sealed override Expression DoResolve (ResolveContext ec) { ResolveAsType (ec); return this; } public override bool Equals (object obj) { TypeExpr tobj = obj as TypeExpr; if (tobj == null) return false; return Type == tobj.Type; } public override int GetHashCode () { return Type.GetHashCode (); } } /// <summary> /// Fully resolved Expression that already evaluated to a type /// </summary> public class TypeExpression : TypeExpr { public TypeExpression (TypeSpec t, Location l) { Type = t; eclass = ExprClass.Type; loc = l; } public sealed override TypeSpec ResolveAsType (IMemberContext mc, bool allowUnboundTypeArguments = false) { return type; } } public class NamespaceExpression : FullNamedExpression { readonly Namespace ns; public NamespaceExpression (Namespace ns, Location loc) { this.ns = ns; this.Type = InternalType.Namespace; this.eclass = ExprClass.Namespace; this.loc = loc; } public Namespace Namespace { get { return ns; } } protected override Expression DoResolve (ResolveContext rc) { throw new NotImplementedException (); } public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc, bool allowUnboundTypeArguments) { return this; } public void Error_NamespaceDoesNotExist (IMemberContext ctx, string name, int arity) { var retval = Namespace.LookupType (ctx, name, arity, LookupMode.IgnoreAccessibility, loc); if (retval != null) { // ctx.Module.Compiler.Report.SymbolRelatedToPreviousError (retval.MemberDefinition); ErrorIsInaccesible (ctx, retval.GetSignatureForError (), loc); return; } retval = Namespace.LookupType (ctx, name, -System.Math.Max (1, arity), LookupMode.Probing, loc); if (retval != null) { Error_TypeArgumentsCannotBeUsed (ctx, retval, loc); return; } Namespace ns; if (arity > 0 && Namespace.TryGetNamespace (name, out ns)) { Error_TypeArgumentsCannotBeUsed (ctx, ExprClassName, ns.GetSignatureForError (), loc); return; } string assembly = null; string possible_name = Namespace.GetSignatureForError () + "." + name; // Only assembly unique name should be added switch (possible_name) { case "System.Drawing": case "System.Web.Services": case "System.Web": case "System.Data": case "System.Configuration": case "System.Data.Services": case "System.DirectoryServices": case "System.Json": case "System.Net.Http": case "System.Numerics": case "System.Runtime.Caching": case "System.ServiceModel": case "System.Transactions": case "System.Web.Routing": case "System.Xml.Linq": case "System.Xml": assembly = possible_name; break; case "System.Linq": case "System.Linq.Expressions": assembly = "System.Core"; break; case "System.Windows.Forms": case "System.Windows.Forms.Layout": assembly = "System.Windows.Forms"; break; } assembly = assembly == null ? "an" : "`" + assembly + "'"; if (Namespace is GlobalRootNamespace) { ctx.Module.Compiler.Report.Error (400, loc, "The type or namespace name `{0}' could not be found in the global namespace. Are you missing {1} assembly reference?", name, assembly); } else { ctx.Module.Compiler.Report.Error (234, loc, "The type or namespace name `{0}' does not exist in the namespace `{1}'. Are you missing {2} assembly reference?", name, GetSignatureForError (), assembly); } } public override string GetSignatureForError () { return ns.GetSignatureForError (); } public FullNamedExpression LookupTypeOrNamespace (IMemberContext ctx, string name, int arity, LookupMode mode, Location loc) { return ns.LookupTypeOrNamespace (ctx, name, arity, mode, loc); } public override string ToString () { return Namespace.Name; } } /// <summary> /// This class denotes an expression which evaluates to a member /// of a struct or a class. /// </summary> public abstract class MemberExpr : Expression, OverloadResolver.IInstanceQualifier { protected bool conditional_access_receiver; // // An instance expression associated with this member, if it's a // non-static member // public Expression InstanceExpression; /// <summary> /// The name of this member. /// </summary> public abstract string Name { get; } // // When base.member is used // public bool IsBase { get { return InstanceExpression is BaseThis; } } /// <summary> /// Whether this is an instance member. /// </summary> public abstract bool IsInstance { get; } /// <summary> /// Whether this is a static member. /// </summary> public abstract bool IsStatic { get; } public abstract string KindName { get; } public bool ConditionalAccess { get; set; } protected abstract TypeSpec DeclaringType { get; } TypeSpec OverloadResolver.IInstanceQualifier.InstanceType { get { return InstanceExpression.Type; } } // // Converts best base candidate for virtual method starting from QueriedBaseType // protected MethodSpec CandidateToBaseOverride (ResolveContext rc, MethodSpec method) { // // Only when base.member is used and method is virtual // if (!IsBase) return method; // // Overload resulution works on virtual or non-virtual members only (no overrides). That // means for base.member access we have to find the closest match after we found best candidate // if ((method.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) { // // The method could already be what we are looking for // TypeSpec[] targs = null; if (method.DeclaringType != InstanceExpression.Type) { // // Candidate can have inflated MVAR parameters and we need to find // base match for original definition not inflated parameter types // var parameters = method.Parameters; if (method.Arity > 0) { parameters = ((IParametersMember) method.MemberDefinition).Parameters; var inflated = method.DeclaringType as InflatedTypeSpec; if (inflated != null) { parameters = parameters.Inflate (inflated.CreateLocalInflator (rc)); } } var filter = new MemberFilter (method.Name, method.Arity, MemberKind.Method, parameters, null); var base_override = MemberCache.FindMember (InstanceExpression.Type, filter, BindingRestriction.InstanceOnly | BindingRestriction.OverrideOnly) as MethodSpec; if (base_override != null && base_override.DeclaringType != method.DeclaringType) { if (base_override.IsGeneric) targs = method.TypeArguments; method = base_override; } } // // When base access is used inside anonymous method/iterator/etc we need to // get back to the context of original type. We do it by emiting proxy // method in original class and rewriting base call to this compiler // generated method call which does the actual base invocation. This may // introduce redundant storey but with `this' only but it's tricky to avoid // at this stage as we don't know what expressions follow base // if (rc.CurrentAnonymousMethod != null) { if (targs == null && method.IsGeneric) { targs = method.TypeArguments; method = method.GetGenericMethodDefinition (); } if (method.Parameters.HasArglist) throw new NotImplementedException ("__arglist base call proxy"); method = rc.CurrentMemberDefinition.Parent.PartialContainer.CreateHoistedBaseCallProxy (rc, method); // Ideally this should apply to any proxy rewrite but in the case of unary mutators on // get/set member expressions second call would fail to proxy because left expression // would be of 'this' and not 'base' because we share InstanceExpression for get/set // FIXME: The async check is another hack but will probably fail with mutators if (rc.CurrentType.IsStruct || rc.CurrentAnonymousMethod.Storey is AsyncTaskStorey) InstanceExpression = new This (loc).Resolve (rc); } if (targs != null) method = method.MakeGenericMethod (rc, targs); } // // Only base will allow this invocation to happen. // if (method.IsAbstract) { rc.Report.SymbolRelatedToPreviousError (method); Error_CannotCallAbstractBase (rc, method.GetSignatureForError ()); } return method; } protected void CheckProtectedMemberAccess (ResolveContext rc, MemberSpec member) { if (InstanceExpression == null) return; if ((member.Modifiers & Modifiers.PROTECTED) != 0 && !(InstanceExpression is This)) { if (!CheckProtectedMemberAccess (rc, member, InstanceExpression.Type)) { Error_ProtectedMemberAccess (rc, member, InstanceExpression.Type, loc); } } } bool OverloadResolver.IInstanceQualifier.CheckProtectedMemberAccess (ResolveContext rc, MemberSpec member) { if (InstanceExpression == null) return true; return InstanceExpression is This || CheckProtectedMemberAccess (rc, member, InstanceExpression.Type); } public static bool CheckProtectedMemberAccess<T> (ResolveContext rc, T member, TypeSpec qualifier) where T : MemberSpec { var ct = rc.CurrentType; if (ct == qualifier) return true; if ((member.Modifiers & Modifiers.INTERNAL) != 0 && member.DeclaringType.MemberDefinition.IsInternalAsPublic (ct.MemberDefinition.DeclaringAssembly)) return true; qualifier = qualifier.GetDefinition (); if (ct != qualifier && !IsSameOrBaseQualifier (ct, qualifier)) { return false; } return true; } public override bool ContainsEmitWithAwait () { return InstanceExpression != null && InstanceExpression.ContainsEmitWithAwait (); } public override bool HasConditionalAccess () { return ConditionalAccess || (InstanceExpression != null && InstanceExpression.HasConditionalAccess ()); } static bool IsSameOrBaseQualifier (TypeSpec type, TypeSpec qtype) { do { type = type.GetDefinition (); if (type == qtype || TypeManager.IsFamilyAccessible (qtype, type)) return true; type = type.DeclaringType; } while (type != null); return false; } protected void DoBestMemberChecks<T> (ResolveContext rc, T member) where T : MemberSpec, IInterfaceMemberSpec { if (InstanceExpression != null) { InstanceExpression = InstanceExpression.Resolve (rc); CheckProtectedMemberAccess (rc, member); } if (member.MemberType.IsPointer && !rc.IsUnsafe) { UnsafeError (rc, loc); } var dep = member.GetMissingDependencies (); if (dep != null) { ImportedTypeDefinition.Error_MissingDependency (rc, dep, loc); } if (!rc.IsObsolete) { ObsoleteAttribute oa = member.GetAttributeObsolete (); if (oa != null) AttributeTester.Report_ObsoleteMessage (oa, member.GetSignatureForError (), loc, rc.Report); } if (!(member is FieldSpec)) member.MemberDefinition.SetIsUsed (); } protected virtual void Error_CannotCallAbstractBase (ResolveContext rc, string name) { rc.Report.Error (205, loc, "Cannot call an abstract base member `{0}'", name); } public static void Error_ProtectedMemberAccess (ResolveContext rc, MemberSpec member, TypeSpec qualifier, Location loc) { rc.Report.SymbolRelatedToPreviousError (member); rc.Report.Error (1540, loc, "Cannot access protected member `{0}' via a qualifier of type `{1}'. The qualifier must be of type `{2}' or derived from it", member.GetSignatureForError (), qualifier.GetSignatureForError (), rc.CurrentType.GetSignatureForError ()); } public override void FlowAnalysis (FlowAnalysisContext fc) { if (InstanceExpression != null) { InstanceExpression.FlowAnalysis (fc); if (ConditionalAccess) { fc.BranchConditionalAccessDefiniteAssignment (); } } } protected void ResolveConditionalAccessReceiver (ResolveContext rc) { if (!rc.HasSet (ResolveContext.Options.ConditionalAccessReceiver)) { if (HasConditionalAccess ()) { conditional_access_receiver = true; rc.Set (ResolveContext.Options.ConditionalAccessReceiver); } } } public bool ResolveInstanceExpression (ResolveContext rc, Expression rhs) { if (!ResolveInstanceExpressionCore (rc, rhs)) return false; // // Check intermediate value modification which won't have any effect // if (rhs != null && TypeSpec.IsValueType (InstanceExpression.Type)) { var fexpr = InstanceExpression as FieldExpr; if (fexpr != null) { if (!fexpr.Spec.IsReadOnly || rc.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.ConstructorScope)) return true; if (fexpr.IsStatic) { rc.Report.Error (1650, loc, "Fields of static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)", fexpr.GetSignatureForError ()); } else { rc.Report.Error (1648, loc, "Members of readonly field `{0}' cannot be modified (except in a constructor or a variable initializer)", fexpr.GetSignatureForError ()); } return true; } if (InstanceExpression is PropertyExpr || InstanceExpression is IndexerExpr || InstanceExpression is Invocation) { if (rc.CurrentInitializerVariable != null) { rc.Report.Error (1918, loc, "Members of value type `{0}' cannot be assigned using a property `{1}' object initializer", InstanceExpression.Type.GetSignatureForError (), InstanceExpression.GetSignatureForError ()); } else { rc.Report.Error (1612, loc, "Cannot modify a value type return value of `{0}'. Consider storing the value in a temporary variable", InstanceExpression.GetSignatureForError ()); } return true; } var lvr = InstanceExpression as LocalVariableReference; if (lvr != null) { if (!lvr.local_info.IsReadonly) return true; rc.Report.Error (1654, loc, "Cannot assign to members of `{0}' because it is a `{1}'", InstanceExpression.GetSignatureForError (), lvr.local_info.GetReadOnlyContext ()); } } return true; } bool ResolveInstanceExpressionCore (ResolveContext rc, Expression rhs) { if (IsStatic) { if (InstanceExpression != null) { if (InstanceExpression is TypeExpr) { var t = InstanceExpression.Type; do { ObsoleteAttribute oa = t.GetAttributeObsolete (); if (oa != null && !rc.IsObsolete) { AttributeTester.Report_ObsoleteMessage (oa, t.GetSignatureForError (), loc, rc.Report); } t = t.DeclaringType; } while (t != null); } else { var runtime_expr = InstanceExpression as RuntimeValueExpression; if (runtime_expr == null || !runtime_expr.IsSuggestionOnly) { rc.Report.Error (176, loc, "Static member `{0}' cannot be accessed with an instance reference, qualify it with a type name instead", GetSignatureForError ()); } } InstanceExpression = null; } return false; } if (InstanceExpression == null || InstanceExpression is TypeExpr) { if (InstanceExpression != null || !This.IsThisAvailable (rc, true)) { if (rc.HasSet (ResolveContext.Options.FieldInitializerScope)) { rc.Report.Error (236, loc, "A field initializer cannot reference the nonstatic field, method, or property `{0}'", GetSignatureForError ()); } else { var fe = this as FieldExpr; if (fe != null && fe.Spec.MemberDefinition is PrimaryConstructorField) { if (rc.HasSet (ResolveContext.Options.BaseInitializer)) { rc.Report.Error (9005, loc, "Constructor initializer cannot access primary constructor parameters"); } else { rc.Report.Error (9006, loc, "An object reference is required to access primary constructor parameter `{0}'", fe.Name); } } else { rc.Report.Error (120, loc, "An object reference is required to access non-static member `{0}'", GetSignatureForError ()); } } InstanceExpression = new CompilerGeneratedThis (rc.CurrentType, loc).Resolve (rc); return false; } if (!TypeManager.IsFamilyAccessible (rc.CurrentType, DeclaringType)) { rc.Report.Error (38, loc, "Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'", DeclaringType.GetSignatureForError (), rc.CurrentType.GetSignatureForError ()); } InstanceExpression = new This (loc).Resolve (rc); return false; } var me = InstanceExpression as MemberExpr; if (me != null) { me.ResolveInstanceExpressionCore (rc, rhs); var fe = me as FieldExpr; if (fe != null && fe.IsMarshalByRefAccess (rc)) { rc.Report.SymbolRelatedToPreviousError (me.DeclaringType); rc.Report.Warning (1690, 1, loc, "Cannot call methods, properties, or indexers on `{0}' because it is a value type member of a marshal-by-reference class", me.GetSignatureForError ()); } return true; } // // Additional checks for l-value member access // if (rhs != null) { if (InstanceExpression is UnboxCast) { rc.Report.Error (445, InstanceExpression.Location, "Cannot modify the result of an unboxing conversion"); } } return true; } public virtual MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, SimpleName original) { if (left != null && !ConditionalAccess && left.IsNull && TypeSpec.IsReferenceType (left.Type)) { ec.Report.Warning (1720, 1, left.Location, "Expression will always cause a `{0}'", "System.NullReferenceException"); } InstanceExpression = left; return this; } protected void EmitInstance (EmitContext ec, bool prepare_for_load) { var inst = new InstanceEmitter (InstanceExpression, TypeSpec.IsValueType (InstanceExpression.Type)); inst.Emit (ec, ConditionalAccess); if (prepare_for_load) ec.Emit (OpCodes.Dup); } public abstract void SetTypeArguments (ResolveContext ec, TypeArguments ta); } public class ExtensionMethodCandidates { readonly NamespaceContainer container; readonly IList<MethodSpec> methods; readonly int index; readonly IMemberContext context; public ExtensionMethodCandidates (IMemberContext context, IList<MethodSpec> methods, NamespaceContainer nsContainer, int lookupIndex) { this.context = context; this.methods = methods; this.container = nsContainer; this.index = lookupIndex; } public NamespaceContainer Container { get { return container; } } public IMemberContext Context { get { return context; } } public int LookupIndex { get { return index; } } public IList<MethodSpec> Methods { get { return methods; } } } // // Represents a group of extension method candidates for whole namespace // class ExtensionMethodGroupExpr : MethodGroupExpr, OverloadResolver.IErrorHandler { ExtensionMethodCandidates candidates; public Expression ExtensionExpression; public ExtensionMethodGroupExpr (ExtensionMethodCandidates candidates, Expression extensionExpr, Location loc) : base (candidates.Methods.Cast<MemberSpec>().ToList (), extensionExpr.Type, loc) { this.candidates = candidates; this.ExtensionExpression = extensionExpr; } public override bool IsStatic { get { return true; } } public override void FlowAnalysis (FlowAnalysisContext fc) { if (ConditionalAccess) { fc.BranchConditionalAccessDefiniteAssignment (); } } // // For extension methodgroup we are not looking for base members but parent // namespace extension methods // public override IList<MemberSpec> GetBaseMembers (TypeSpec baseType) { // TODO: candidates are null only when doing error reporting, that's // incorrect. We have to discover same extension methods in error mode if (candidates == null) return null; int arity = type_arguments == null ? 0 : type_arguments.Count; candidates = candidates.Container.LookupExtensionMethod (candidates.Context, ExtensionExpression.Type, Name, arity, candidates.LookupIndex); if (candidates == null) return null; return candidates.Methods.Cast<MemberSpec> ().ToList (); } public override MethodGroupExpr LookupExtensionMethod (ResolveContext rc) { // We are already here return null; } public override MethodGroupExpr OverloadResolve (ResolveContext ec, ref Arguments arguments, OverloadResolver.IErrorHandler ehandler, OverloadResolver.Restrictions restr) { if (arguments == null) arguments = new Arguments (1); ExtensionExpression = ExtensionExpression.Resolve (ec); if (ExtensionExpression == null) return null; var cand = candidates; var atype = ConditionalAccess ? Argument.AType.ExtensionTypeConditionalAccess : Argument.AType.ExtensionType; arguments.Insert (0, new Argument (ExtensionExpression, atype)); var res = base.OverloadResolve (ec, ref arguments, ehandler ?? this, restr); // Restore candidates in case we are running in probing mode candidates = cand; // Store resolved argument and restore original arguments if (res == null) { // Clean-up modified arguments for error reporting arguments.RemoveAt (0); return null; } var me = ExtensionExpression as MemberExpr; if (me != null) { me.ResolveInstanceExpression (ec, null); var fe = me as FieldExpr; if (fe != null) fe.Spec.MemberDefinition.SetIsUsed (); } InstanceExpression = null; return this; } #region IErrorHandler Members bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext rc, MemberSpec best, MemberSpec ambiguous) { return false; } bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index) { rc.Report.SymbolRelatedToPreviousError (best); rc.Report.Error (1928, loc, "Type `{0}' does not contain a member `{1}' and the best extension method overload `{2}' has some invalid arguments", queried_type.GetSignatureForError (), Name, best.GetSignatureForError ()); if (index == 0) { rc.Report.Error (1929, loc, "Extension method instance type `{0}' cannot be converted to `{1}'", arg.Type.GetSignatureForError (), ((MethodSpec)best).Parameters.ExtensionMethodType.GetSignatureForError ()); } return true; } bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best) { return false; } bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best) { return false; } #endregion } /// <summary> /// MethodGroupExpr represents a group of method candidates which /// can be resolved to the best method overload /// </summary> public class MethodGroupExpr : MemberExpr, OverloadResolver.IBaseMembersProvider { static readonly MemberSpec[] Excluded = new MemberSpec[0]; protected IList<MemberSpec> Methods; MethodSpec best_candidate; TypeSpec best_candidate_return; protected TypeArguments type_arguments; SimpleName simple_name; protected TypeSpec queried_type; public MethodGroupExpr (IList<MemberSpec> mi, TypeSpec type, Location loc) { Methods = mi; this.loc = loc; this.type = InternalType.MethodGroup; eclass = ExprClass.MethodGroup; queried_type = type; } public MethodGroupExpr (MethodSpec m, TypeSpec type, Location loc) : this (new MemberSpec[] { m }, type, loc) { } #region Properties public MethodSpec BestCandidate { get { return best_candidate; } } public TypeSpec BestCandidateReturnType { get { return best_candidate_return; } } public IList<MemberSpec> Candidates { get { return Methods; } } protected override TypeSpec DeclaringType { get { return queried_type; } } public bool IsConditionallyExcluded { get { return Methods == Excluded; } } public override bool IsInstance { get { if (best_candidate != null) return !best_candidate.IsStatic; return false; } } public override bool IsSideEffectFree { get { return InstanceExpression == null || InstanceExpression.IsSideEffectFree; } } public override bool IsStatic { get { if (best_candidate != null) return best_candidate.IsStatic; return false; } } public override string KindName { get { return "method"; } } public override string Name { get { if (best_candidate != null) return best_candidate.Name; // TODO: throw ? return Methods.First ().Name; } } #endregion // // When best candidate is already know this factory can be used // to avoid expensive overload resolution to be called // // NOTE: InstanceExpression has to be set manually // public static MethodGroupExpr CreatePredefined (MethodSpec best, TypeSpec queriedType, Location loc) { return new MethodGroupExpr (best, queriedType, loc) { best_candidate = best, best_candidate_return = best.ReturnType }; } public override string GetSignatureForError () { if (best_candidate != null) return best_candidate.GetSignatureForError (); return Methods.First ().GetSignatureForError (); } public override Expression CreateExpressionTree (ResolveContext ec) { if (best_candidate == null) { ec.Report.Error (1953, loc, "An expression tree cannot contain an expression with method group"); return null; } if (IsConditionallyExcluded) ec.Report.Error (765, loc, "Partial methods with only a defining declaration or removed conditional methods cannot be used in an expression tree"); if (ConditionalAccess) Error_NullShortCircuitInsideExpressionTree (ec); return new TypeOfMethod (best_candidate, loc); } protected override Expression DoResolve (ResolveContext ec) { this.eclass = ExprClass.MethodGroup; if (InstanceExpression != null) { InstanceExpression = InstanceExpression.Resolve (ec); if (InstanceExpression == null) return null; } return this; } public override void Emit (EmitContext ec) { throw new NotSupportedException (); } public void EmitCall (EmitContext ec, Arguments arguments, bool statement) { var call = new CallEmitter (); call.InstanceExpression = InstanceExpression; call.ConditionalAccess = ConditionalAccess; if (statement) call.EmitStatement (ec, best_candidate, arguments, loc); else call.Emit (ec, best_candidate, arguments, loc); } public void EmitCall (EmitContext ec, Arguments arguments, TypeSpec conditionalAccessReceiver, bool statement) { ec.ConditionalAccess = new ConditionalAccessContext (conditionalAccessReceiver, ec.DefineLabel ()) { Statement = statement }; EmitCall (ec, arguments, statement); ec.CloseConditionalAccess (!statement && best_candidate_return != conditionalAccessReceiver && conditionalAccessReceiver.IsNullableType ? conditionalAccessReceiver : null); } public override void Error_ValueCannotBeConverted (ResolveContext ec, TypeSpec target, bool expl) { ec.Report.Error (428, loc, "Cannot convert method group `{0}' to non-delegate type `{1}'. Consider using parentheses to invoke the method", Name, target.GetSignatureForError ()); } public static bool IsExtensionMethodArgument (Expression expr) { // // LAMESPEC: No details about which expressions are not allowed // return !(expr is TypeExpr) && !(expr is BaseThis); } /// <summary> /// Find the Applicable Function Members (7.4.2.1) /// /// me: Method Group expression with the members to select. /// it might contain constructors or methods (or anything /// that maps to a method). /// /// Arguments: ArrayList containing resolved Argument objects. /// /// loc: The location if we want an error to be reported, or a Null /// location for "probing" purposes. /// /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo) /// that is the best match of me on Arguments. /// /// </summary> public virtual MethodGroupExpr OverloadResolve (ResolveContext ec, ref Arguments args, OverloadResolver.IErrorHandler cerrors, OverloadResolver.Restrictions restr) { // TODO: causes issues with probing mode, remove explicit Kind check if (best_candidate != null && best_candidate.Kind == MemberKind.Destructor) return this; var r = new OverloadResolver (Methods, type_arguments, restr, loc); if ((restr & OverloadResolver.Restrictions.NoBaseMembers) == 0) { r.BaseMembersProvider = this; r.InstanceQualifier = this; } if (cerrors != null) r.CustomErrors = cerrors; // TODO: When in probing mode do IsApplicable only and when called again do VerifyArguments for full error reporting best_candidate = r.ResolveMember<MethodSpec> (ec, ref args); if (best_candidate == null) { if (!r.BestCandidateIsDynamic) return null; if (simple_name != null && ec.IsStatic) InstanceExpression = ProbeIdenticalTypeName (ec, InstanceExpression, simple_name); return this; } // Overload resolver had to create a new method group, all checks bellow have already been executed if (r.BestCandidateNewMethodGroup != null) return r.BestCandidateNewMethodGroup; if (best_candidate.Kind == MemberKind.Method && (restr & OverloadResolver.Restrictions.ProbingOnly) == 0) { if (InstanceExpression != null) { if (best_candidate.IsExtensionMethod && args[0].Expr == InstanceExpression) { InstanceExpression = null; } else { if (simple_name != null && best_candidate.IsStatic) { InstanceExpression = ProbeIdenticalTypeName (ec, InstanceExpression, simple_name); } InstanceExpression.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup | ResolveFlags.Type); } } ResolveInstanceExpression (ec, null); } var base_override = CandidateToBaseOverride (ec, best_candidate); if (base_override == best_candidate) { best_candidate_return = r.BestCandidateReturnType; } else { best_candidate = base_override; best_candidate_return = best_candidate.ReturnType; } if (best_candidate.IsGeneric && (restr & OverloadResolver.Restrictions.ProbingOnly) == 0 && TypeParameterSpec.HasAnyTypeParameterConstrained (best_candidate.GenericDefinition)) { ConstraintChecker cc = new ConstraintChecker (ec); cc.CheckAll (best_candidate.GetGenericMethodDefinition (), best_candidate.TypeArguments, best_candidate.Constraints, loc); } // // Additional check for possible imported base override method which // could not be done during IsOverrideMethodBaseTypeAccessible // if (best_candidate.IsVirtual && (best_candidate.DeclaringType.Modifiers & Modifiers.PROTECTED) != 0 && best_candidate.MemberDefinition.IsImported && !best_candidate.DeclaringType.IsAccessible (ec)) { ec.Report.SymbolRelatedToPreviousError (best_candidate); ErrorIsInaccesible (ec, best_candidate.GetSignatureForError (), loc); } // Speed up the check by not doing it on disallowed targets if (best_candidate_return.Kind == MemberKind.Void && best_candidate.IsConditionallyExcluded (ec)) Methods = Excluded; return this; } public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, SimpleName original) { var fe = left as FieldExpr; if (fe != null) { // // Using method-group on struct fields makes the struct assigned. I am not sure // why but that's what .net does // fe.Spec.MemberDefinition.SetIsAssigned (); } simple_name = original; return base.ResolveMemberAccess (ec, left, original); } public override void SetTypeArguments (ResolveContext ec, TypeArguments ta) { type_arguments = ta; } #region IBaseMembersProvider Members public virtual IList<MemberSpec> GetBaseMembers (TypeSpec baseType) { return baseType == null ? null : MemberCache.FindMembers (baseType, Methods [0].Name, false); } public IParametersMember GetOverrideMemberParameters (MemberSpec member) { if (queried_type == member.DeclaringType) return null; return MemberCache.FindMember (queried_type, new MemberFilter ((MethodSpec) member), BindingRestriction.InstanceOnly | BindingRestriction.OverrideOnly) as IParametersMember; } // // Extension methods lookup after ordinary methods candidates failed to apply // public virtual MethodGroupExpr LookupExtensionMethod (ResolveContext rc) { if (InstanceExpression == null || InstanceExpression.eclass == ExprClass.Type) return null; if (!IsExtensionMethodArgument (InstanceExpression)) return null; int arity = type_arguments == null ? 0 : type_arguments.Count; var methods = rc.LookupExtensionMethod (InstanceExpression.Type, Methods[0].Name, arity); if (methods == null) return null; var emg = new ExtensionMethodGroupExpr (methods, InstanceExpression, loc); emg.SetTypeArguments (rc, type_arguments); return emg; } #endregion } struct ConstructorInstanceQualifier : OverloadResolver.IInstanceQualifier { public ConstructorInstanceQualifier (TypeSpec type) : this () { InstanceType = type; } public TypeSpec InstanceType { get; private set; } public bool CheckProtectedMemberAccess (ResolveContext rc, MemberSpec member) { return MemberExpr.CheckProtectedMemberAccess (rc, member, InstanceType); } } public struct OverloadResolver { [Flags] public enum Restrictions { None = 0, DelegateInvoke = 1, ProbingOnly = 1 << 1, CovariantDelegate = 1 << 2, NoBaseMembers = 1 << 3, BaseMembersIncluded = 1 << 4, GetEnumeratorLookup = 1 << 5 } public interface IBaseMembersProvider { IList<MemberSpec> GetBaseMembers (TypeSpec baseType); IParametersMember GetOverrideMemberParameters (MemberSpec member); MethodGroupExpr LookupExtensionMethod (ResolveContext rc); } public interface IErrorHandler { bool AmbiguousCandidates (ResolveContext rc, MemberSpec best, MemberSpec ambiguous); bool ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument a, int index); bool NoArgumentMatch (ResolveContext rc, MemberSpec best); bool TypeInferenceFailed (ResolveContext rc, MemberSpec best); } public interface IInstanceQualifier { TypeSpec InstanceType { get; } bool CheckProtectedMemberAccess (ResolveContext rc, MemberSpec member); } sealed class NoBaseMembers : IBaseMembersProvider { public static readonly IBaseMembersProvider Instance = new NoBaseMembers (); public IList<MemberSpec> GetBaseMembers (TypeSpec baseType) { return null; } public IParametersMember GetOverrideMemberParameters (MemberSpec member) { return null; } public MethodGroupExpr LookupExtensionMethod (ResolveContext rc) { return null; } } struct AmbiguousCandidate { public readonly MemberSpec Member; public readonly bool Expanded; public readonly AParametersCollection Parameters; public AmbiguousCandidate (MemberSpec member, AParametersCollection parameters, bool expanded) { Member = member; Parameters = parameters; Expanded = expanded; } } Location loc; IList<MemberSpec> members; TypeArguments type_arguments; IBaseMembersProvider base_provider; IErrorHandler custom_errors; IInstanceQualifier instance_qualifier; Restrictions restrictions; MethodGroupExpr best_candidate_extension_group; TypeSpec best_candidate_return_type; SessionReportPrinter lambda_conv_msgs; public OverloadResolver (IList<MemberSpec> members, Restrictions restrictions, Location loc) : this (members, null, restrictions, loc) { } public OverloadResolver (IList<MemberSpec> members, TypeArguments targs, Restrictions restrictions, Location loc) : this () { if (members == null || members.Count == 0) throw new ArgumentException ("empty members set"); this.members = members; this.loc = loc; type_arguments = targs; this.restrictions = restrictions; if (IsDelegateInvoke) this.restrictions |= Restrictions.NoBaseMembers; base_provider = NoBaseMembers.Instance; } #region Properties public IBaseMembersProvider BaseMembersProvider { get { return base_provider; } set { base_provider = value; } } public bool BestCandidateIsDynamic { get; set; } // // Best candidate was found in newly created MethodGroupExpr, used by extension methods // public MethodGroupExpr BestCandidateNewMethodGroup { get { return best_candidate_extension_group; } } // // Return type can be different between best candidate and closest override // public TypeSpec BestCandidateReturnType { get { return best_candidate_return_type; } } public IErrorHandler CustomErrors { get { return custom_errors; } set { custom_errors = value; } } TypeSpec DelegateType { get { if ((restrictions & Restrictions.DelegateInvoke) == 0) throw new InternalErrorException ("Not running in delegate mode", loc); return members [0].DeclaringType; } } public IInstanceQualifier InstanceQualifier { get { return instance_qualifier; } set { instance_qualifier = value; } } bool IsProbingOnly { get { return (restrictions & Restrictions.ProbingOnly) != 0; } } bool IsDelegateInvoke { get { return (restrictions & Restrictions.DelegateInvoke) != 0; } } #endregion // // 7.4.3.3 Better conversion from expression // Returns : 1 if a->p is better, // 2 if a->q is better, // 0 if neither is better // static int BetterExpressionConversion (ResolveContext ec, Argument a, TypeSpec p, TypeSpec q) { TypeSpec argument_type = a.Type; // // If argument is an anonymous function // if (argument_type == InternalType.AnonymousMethod && ec.Module.Compiler.Settings.Version > LanguageVersion.ISO_2) { // // p and q are delegate types or expression tree types // if (p.IsExpressionTreeType || q.IsExpressionTreeType) { if (q.MemberDefinition != p.MemberDefinition) { return 0; } // // Uwrap delegate from Expression<T> // q = TypeManager.GetTypeArguments (q)[0]; p = TypeManager.GetTypeArguments (p)[0]; } var p_m = Delegate.GetInvokeMethod (p); var q_m = Delegate.GetInvokeMethod (q); // // With identical parameter lists // if (!TypeSpecComparer.Equals (p_m.Parameters.Types, q_m.Parameters.Types)) return 0; p = p_m.ReturnType; var orig_q = q; q = q_m.ReturnType; // // if p is void returning, and q has a return type Y, then C2 is the better conversion. // if (p.Kind == MemberKind.Void) { return q.Kind != MemberKind.Void ? 2 : 0; } // // if p has a return type Y, and q is void returning, then C1 is the better conversion. // if (q.Kind == MemberKind.Void) { return p.Kind != MemberKind.Void ? 1: 0; } var am = (AnonymousMethodExpression) a.Expr; // // When anonymous method is an asynchronous, and P has a return type Task<Y1>, and Q has a return type Task<Y2> // better conversion is performed between underlying types Y1 and Y2 // if (p.IsGenericTask || q.IsGenericTask) { if (am.Block.IsAsync && p.IsGenericTask && q.IsGenericTask) { q = q.TypeArguments[0]; p = p.TypeArguments[0]; } } if (q != p) { // // An inferred return type X exists for E in the context of that parameter list, and // the conversion from X to Y1 is better than the conversion from X to Y2 // argument_type = am.InferReturnType (ec, null, orig_q); if (argument_type == null) { // TODO: Can this be hit? return 1; } if (argument_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) argument_type = ec.BuiltinTypes.Object; } } if (argument_type == p) return 1; if (argument_type == q) return 2; // // The parameters are identicial and return type is not void, use better type conversion // on return type to determine better one // return BetterTypeConversion (ec, p, q); } // // 7.4.3.4 Better conversion from type // public static int BetterTypeConversion (ResolveContext ec, TypeSpec p, TypeSpec q) { if (p == null || q == null) throw new InternalErrorException ("BetterTypeConversion got a null conversion"); switch (p.BuiltinType) { case BuiltinTypeSpec.Type.Int: if (q.BuiltinType == BuiltinTypeSpec.Type.UInt || q.BuiltinType == BuiltinTypeSpec.Type.ULong) return 1; break; case BuiltinTypeSpec.Type.Long: if (q.BuiltinType == BuiltinTypeSpec.Type.ULong) return 1; break; case BuiltinTypeSpec.Type.SByte: switch (q.BuiltinType) { case BuiltinTypeSpec.Type.Byte: case BuiltinTypeSpec.Type.UShort: case BuiltinTypeSpec.Type.UInt: case BuiltinTypeSpec.Type.ULong: return 1; } break; case BuiltinTypeSpec.Type.Short: switch (q.BuiltinType) { case BuiltinTypeSpec.Type.UShort: case BuiltinTypeSpec.Type.UInt: case BuiltinTypeSpec.Type.ULong: return 1; } break; case BuiltinTypeSpec.Type.Dynamic: // Dynamic is never better return 2; } switch (q.BuiltinType) { case BuiltinTypeSpec.Type.Int: if (p.BuiltinType == BuiltinTypeSpec.Type.UInt || p.BuiltinType == BuiltinTypeSpec.Type.ULong) return 2; break; case BuiltinTypeSpec.Type.Long: if (p.BuiltinType == BuiltinTypeSpec.Type.ULong) return 2; break; case BuiltinTypeSpec.Type.SByte: switch (p.BuiltinType) { case BuiltinTypeSpec.Type.Byte: case BuiltinTypeSpec.Type.UShort: case BuiltinTypeSpec.Type.UInt: case BuiltinTypeSpec.Type.ULong: return 2; } break; case BuiltinTypeSpec.Type.Short: switch (p.BuiltinType) { case BuiltinTypeSpec.Type.UShort: case BuiltinTypeSpec.Type.UInt: case BuiltinTypeSpec.Type.ULong: return 2; } break; case BuiltinTypeSpec.Type.Dynamic: // Dynamic is never better return 1; } // FIXME: handle lifted operators // TODO: this is expensive Expression p_tmp = new EmptyExpression (p); Expression q_tmp = new EmptyExpression (q); bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q); bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p); if (p_to_q && !q_to_p) return 1; if (q_to_p && !p_to_q) return 2; return 0; } /// <summary> /// Determines "Better function" between candidate /// and the current best match /// </summary> /// <remarks> /// Returns a boolean indicating : /// false if candidate ain't better /// true if candidate is better than the current best match /// </remarks> static bool BetterFunction (ResolveContext ec, Arguments args, MemberSpec candidate, AParametersCollection cparam, bool candidate_params, MemberSpec best, AParametersCollection bparam, bool best_params) { AParametersCollection candidate_pd = ((IParametersMember) candidate).Parameters; AParametersCollection best_pd = ((IParametersMember) best).Parameters; bool better_at_least_one = false; bool are_equivalent = true; int args_count = args == null ? 0 : args.Count; int j = 0; Argument a = null; TypeSpec ct, bt; for (int c_idx = 0, b_idx = 0; j < args_count; ++j, ++c_idx, ++b_idx) { a = args[j]; // Default arguments are ignored for better decision if (a.IsDefaultArgument) break; // // When comparing named argument the parameter type index has to be looked up // in original parameter set (override version for virtual members) // NamedArgument na = a as NamedArgument; if (na != null) { int idx = cparam.GetParameterIndexByName (na.Name); ct = candidate_pd.Types[idx]; if (candidate_params && candidate_pd.FixedParameters[idx].ModFlags == Parameter.Modifier.PARAMS) ct = TypeManager.GetElementType (ct); idx = bparam.GetParameterIndexByName (na.Name); bt = best_pd.Types[idx]; if (best_params && best_pd.FixedParameters[idx].ModFlags == Parameter.Modifier.PARAMS) bt = TypeManager.GetElementType (bt); } else { ct = candidate_pd.Types[c_idx]; bt = best_pd.Types[b_idx]; if (candidate_params && candidate_pd.FixedParameters[c_idx].ModFlags == Parameter.Modifier.PARAMS) { ct = TypeManager.GetElementType (ct); --c_idx; } if (best_params && best_pd.FixedParameters[b_idx].ModFlags == Parameter.Modifier.PARAMS) { bt = TypeManager.GetElementType (bt); --b_idx; } } if (TypeSpecComparer.IsEqual (ct, bt)) continue; are_equivalent = false; int result = BetterExpressionConversion (ec, a, ct, bt); // for each argument, the conversion to 'ct' should be no worse than // the conversion to 'bt'. if (result == 2) return false; // for at least one argument, the conversion to 'ct' should be better than // the conversion to 'bt'. if (result != 0) better_at_least_one = true; } if (better_at_least_one) return true; // // Tie-breaking rules are applied only for equivalent parameter types // if (!are_equivalent) return false; // // If candidate is applicable in its normal form and best has a params array and is applicable // only in its expanded form, then candidate is better // if (candidate_params != best_params) return !candidate_params; // // We have not reached end of parameters list due to params or used default parameters // while (j < candidate_pd.Count && j < best_pd.Count) { var cand_param = candidate_pd.FixedParameters [j]; var best_param = best_pd.FixedParameters [j]; if (candidate_pd.Count == best_pd.Count) { // // LAMESPEC: // // void Foo (int i = 0) is better than void Foo (params int[]) for Foo () // void Foo (string[] s, string value = null) is better than Foo (string s, params string[]) for Foo (null) or Foo () // if (cand_param.HasDefaultValue != best_param.HasDefaultValue) return cand_param.HasDefaultValue; if (cand_param.HasDefaultValue) { ++j; continue; } } else { // // Neither is better when not all arguments are provided // // void Foo (string s, int i = 0) <-> Foo (string s, int i = 0, int i2 = 0) // void Foo (string s, int i = 0) <-> Foo (string s, byte i = 0) // void Foo (string s, params int[]) <-> Foo (string s, params byte[]) // if (cand_param.HasDefaultValue && best_param.HasDefaultValue) return false; } break; } if (candidate_pd.Count != best_pd.Count) return candidate_pd.Count < best_pd.Count; // // One is a non-generic method and second is a generic method, then non-generic is better // if (best.IsGeneric != candidate.IsGeneric) return best.IsGeneric; // // Both methods have the same number of parameters, and the parameters have equal types // Pick the "more specific" signature using rules over original (non-inflated) types // var candidate_def_pd = ((IParametersMember) candidate.MemberDefinition).Parameters; var best_def_pd = ((IParametersMember) best.MemberDefinition).Parameters; bool specific_at_least_once = false; for (j = 0; j < args_count; ++j) { NamedArgument na = args_count == 0 ? null : args [j] as NamedArgument; if (na != null) { ct = candidate_def_pd.Types[cparam.GetParameterIndexByName (na.Name)]; bt = best_def_pd.Types[bparam.GetParameterIndexByName (na.Name)]; } else { ct = candidate_def_pd.Types[j]; bt = best_def_pd.Types[j]; } if (ct == bt) continue; TypeSpec specific = MoreSpecific (ct, bt); if (specific == bt) return false; if (specific == ct) specific_at_least_once = true; } if (specific_at_least_once) return true; return false; } static bool CheckInflatedArguments (MethodSpec ms) { if (!TypeParameterSpec.HasAnyTypeParameterTypeConstrained (ms.GenericDefinition)) return true; // Setup constraint checker for probing only ConstraintChecker cc = new ConstraintChecker (null); var mp = ms.Parameters.Types; for (int i = 0; i < mp.Length; ++i) { var type = mp[i] as InflatedTypeSpec; if (type == null) continue; var targs = type.TypeArguments; if (targs.Length == 0) continue; // TODO: Checking inflated MVAR arguments should be enough if (!cc.CheckAll (type.GetDefinition (), targs, type.Constraints, Location.Null)) return false; } return true; } public static void Error_ConstructorMismatch (ResolveContext rc, TypeSpec type, int argCount, Location loc) { rc.Report.Error (1729, loc, "The type `{0}' does not contain a constructor that takes `{1}' arguments", type.GetSignatureForError (), argCount.ToString ()); } // // Determines if the candidate method is applicable to the given set of arguments // There could be two different set of parameters for same candidate where one // is the closest override for default values and named arguments checks and second // one being the virtual base for the parameter types and modifiers. // // A return value rates candidate method compatibility, // -1 = fatal error // 0 = the best, int.MaxValue = the worst // int IsApplicable (ResolveContext ec, ref Arguments arguments, int arg_count, ref MemberSpec candidate, IParametersMember pm, ref bool params_expanded_form, ref bool dynamicArgument, ref TypeSpec returnType, bool errorMode) { // // Each step has allocated 10 values, it can overflow for // more than 10 arguments but that's ok as it's used for // better error reporting only // const int ArgumentCountMismatch = 1000000000; const int NamedArgumentsMismatch = 100000000; const int DefaultArgumentMismatch = 10000000; const int UnexpectedTypeArguments = 1000000; const int TypeArgumentsMismatch = 100000; const int InflatedTypesMismatch = 10000; // Parameters of most-derived type used mainly for named and optional parameters var pd = pm.Parameters; // Used for params modifier only, that's legacy of C# 1.0 which uses base type for // params modifier instead of most-derived type var cpd = ((IParametersMember) candidate).Parameters; int param_count = pd.Count; int optional_count = 0; int score; Arguments orig_args = arguments; if (arg_count != param_count) { // // No arguments expansion when doing exact match for delegates // if ((restrictions & Restrictions.CovariantDelegate) == 0) { for (int i = 0; i < pd.Count; ++i) { if (pd.FixedParameters[i].HasDefaultValue) { optional_count = pd.Count - i; break; } } } if (optional_count != 0) { // Readjust expected number when params used if (cpd.HasParams) { optional_count--; if (arg_count < param_count) param_count--; } else if (arg_count > param_count) { int args_gap = System.Math.Abs (arg_count - param_count); return ArgumentCountMismatch + args_gap; } else if (arg_count < param_count - optional_count) { int args_gap = System.Math.Abs (param_count - optional_count - arg_count); return ArgumentCountMismatch + args_gap; } } else if (arg_count != param_count) { int args_gap = System.Math.Abs (arg_count - param_count); if (!cpd.HasParams) return ArgumentCountMismatch + args_gap; if (arg_count < param_count - 1) return ArgumentCountMismatch + args_gap; } // Resize to fit optional arguments if (optional_count != 0) { if (arguments == null) { arguments = new Arguments (optional_count); } else { // Have to create a new container, so the next run can do same var resized = new Arguments (param_count); resized.AddRange (arguments); arguments = resized; } for (int i = arg_count; i < param_count; ++i) arguments.Add (null); } } if (arg_count > 0) { // // Shuffle named arguments to the right positions if there are any // if (arguments[arg_count - 1] is NamedArgument) { arg_count = arguments.Count; for (int i = 0; i < arg_count; ++i) { bool arg_moved = false; while (true) { NamedArgument na = arguments[i] as NamedArgument; if (na == null) break; int index = pd.GetParameterIndexByName (na.Name); // Named parameter not found if (index < 0) return NamedArgumentsMismatch - i; // already reordered if (index == i) break; Argument temp; if (index >= param_count) { // When using parameters which should not be available to the user if ((cpd.FixedParameters[index].ModFlags & Parameter.Modifier.PARAMS) == 0) break; arguments.Add (null); ++arg_count; temp = null; } else { if (index == arg_count) return NamedArgumentsMismatch - i - 1; temp = arguments [index]; // The slot has been taken by positional argument if (temp != null && !(temp is NamedArgument)) break; } if (!arg_moved) { arguments = arguments.MarkOrderedArgument (na); arg_moved = true; } if (arguments == orig_args) { arguments = new Arguments (orig_args.Count); arguments.AddRange (orig_args); } arguments[index] = arguments[i]; arguments[i] = temp; if (temp == null) break; } } } else { arg_count = arguments.Count; } } else if (arguments != null) { arg_count = arguments.Count; } // // Don't do any expensive checks when the candidate cannot succeed // if (arg_count != param_count && !cpd.HasParams) return DefaultArgumentMismatch - System.Math.Abs (param_count - arg_count); var dep = candidate.GetMissingDependencies (); if (dep != null) { ImportedTypeDefinition.Error_MissingDependency (ec, dep, loc); return -1; } // // 1. Handle generic method using type arguments when specified or type inference // TypeSpec[] ptypes; var ms = candidate as MethodSpec; if (ms != null && ms.IsGeneric) { if (type_arguments != null) { var g_args_count = ms.Arity; if (g_args_count != type_arguments.Count) return TypeArgumentsMismatch - System.Math.Abs (type_arguments.Count - g_args_count); if (type_arguments.Arguments != null) ms = ms.MakeGenericMethod (ec, type_arguments.Arguments); } else { // // Deploy custom error reporting for infered anonymous expression or lambda methods. When // probing lambda methods keep all errors reported in separate set and once we are done and no best // candidate was found use the set to report more details about what was wrong with lambda body. // The general idea is to distinguish between code errors and errors caused by // trial-and-error type inference // if (lambda_conv_msgs == null) { for (int i = 0; i < arg_count; i++) { Argument a = arguments[i]; if (a == null) continue; var am = a.Expr as AnonymousMethodExpression; if (am != null) { if (lambda_conv_msgs == null) lambda_conv_msgs = new SessionReportPrinter (); am.TypeInferenceReportPrinter = lambda_conv_msgs; } } } var ti = new TypeInference (arguments); TypeSpec[] i_args = ti.InferMethodArguments (ec, ms); if (i_args == null) return TypeArgumentsMismatch - ti.InferenceScore; // // Clear any error messages when the result was success // if (lambda_conv_msgs != null) lambda_conv_msgs.ClearSession (); if (i_args.Length != 0) { if (!errorMode) { for (int i = 0; i < i_args.Length; ++i) { var ta = i_args [i]; if (!ta.IsAccessible (ec)) return TypeArgumentsMismatch - i; } } ms = ms.MakeGenericMethod (ec, i_args); } } // // Type arguments constraints have to match for the method to be applicable // if (!CheckInflatedArguments (ms)) { candidate = ms; return InflatedTypesMismatch; } // // We have a generic return type and at same time the method is override which // means we have to also inflate override return type in case the candidate is // best candidate and override return type is different to base return type. // // virtual Foo<T, object> with override Foo<T, dynamic> // if (candidate != pm) { MethodSpec override_ms = (MethodSpec) pm; var inflator = new TypeParameterInflator (ec, ms.DeclaringType, override_ms.GenericDefinition.TypeParameters, ms.TypeArguments); returnType = inflator.Inflate (returnType); } else { returnType = ms.ReturnType; } candidate = ms; pd = ms.Parameters; ptypes = pd.Types; } else { if (type_arguments != null) return UnexpectedTypeArguments; ptypes = cpd.Types; } // // 2. Each argument has to be implicitly convertible to method parameter // Parameter.Modifier p_mod = 0; TypeSpec pt = null; for (int i = 0; i < arg_count; i++) { Argument a = arguments[i]; if (a == null) { var fp = pd.FixedParameters[i]; if (!fp.HasDefaultValue) { arguments = orig_args; return arg_count * 2 + 2; } // // Get the default value expression, we can use the same expression // if the type matches // Expression e = fp.DefaultValue; if (e != null) { e = ResolveDefaultValueArgument (ec, ptypes[i], e, loc); if (e == null) { // Restore for possible error reporting for (int ii = i; ii < arg_count; ++ii) arguments.RemoveAt (i); return (arg_count - i) * 2 + 1; } } if ((fp.ModFlags & Parameter.Modifier.CallerMask) != 0) { // // LAMESPEC: Attributes can be mixed together with build-in priority // if ((fp.ModFlags & Parameter.Modifier.CallerLineNumber) != 0) { e = new IntLiteral (ec.BuiltinTypes, loc.Row, loc); } else if ((fp.ModFlags & Parameter.Modifier.CallerFilePath) != 0) { e = new StringLiteral (ec.BuiltinTypes, loc.NameFullPath, loc); } else if (ec.MemberContext.CurrentMemberDefinition != null) { e = new StringLiteral (ec.BuiltinTypes, ec.MemberContext.CurrentMemberDefinition.GetCallerMemberName (), loc); } } arguments[i] = new Argument (e, Argument.AType.Default); continue; } if (p_mod != Parameter.Modifier.PARAMS) { p_mod = (pd.FixedParameters[i].ModFlags & ~Parameter.Modifier.PARAMS) | (cpd.FixedParameters[i].ModFlags & Parameter.Modifier.PARAMS); pt = ptypes [i]; } else if (!params_expanded_form) { params_expanded_form = true; pt = ((ElementTypeSpec) pt).Element; i -= 2; continue; } score = 1; if (!params_expanded_form) { if (a.IsExtensionType) { // // Indentity, implicit reference or boxing conversion must exist for the extension parameter // // LAMESPEC: or implicit type parameter conversion // var at = a.Type; if (at == pt || TypeSpecComparer.IsEqual (at, pt) || Convert.ImplicitReferenceConversionExists (at, pt, false) || Convert.ImplicitBoxingConversion (null, at, pt) != null) { score = 0; continue; } } else { score = IsArgumentCompatible (ec, a, p_mod, pt); if (score < 0) dynamicArgument = true; } } // // It can be applicable in expanded form (when not doing exact match like for delegates) // if (score != 0 && (p_mod & Parameter.Modifier.PARAMS) != 0 && (restrictions & Restrictions.CovariantDelegate) == 0) { if (!params_expanded_form) { pt = ((ElementTypeSpec) pt).Element; } if (score > 0) score = IsArgumentCompatible (ec, a, Parameter.Modifier.NONE, pt); if (score < 0) { params_expanded_form = true; dynamicArgument = true; } else if (score == 0 || arg_count > pd.Count) { params_expanded_form = true; } } if (score > 0) { if (params_expanded_form) ++score; return (arg_count - i) * 2 + score; } } // // Restore original arguments for dynamic binder to keep the intention of original source code // if (dynamicArgument) arguments = orig_args; return 0; } public static Expression ResolveDefaultValueArgument (ResolveContext ec, TypeSpec ptype, Expression e, Location loc) { if (e is Constant && e.Type == ptype) return e; // // LAMESPEC: No idea what the exact rules are for System.Reflection.Missing.Value instead of null // if (e == EmptyExpression.MissingValue && ptype.BuiltinType == BuiltinTypeSpec.Type.Object || ptype.BuiltinType == BuiltinTypeSpec.Type.Dynamic) { e = new MemberAccess (new MemberAccess (new MemberAccess ( new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Reflection", loc), "Missing", loc), "Value", loc); } else if (e is Constant) { // // Handles int to int? conversions, DefaultParameterValue check // e = Convert.ImplicitConversionStandard (ec, e, ptype, loc); if (e == null) return null; } else { e = new DefaultValueExpression (new TypeExpression (ptype, loc), loc); } return e.Resolve (ec); } // // Tests argument compatibility with the parameter // The possible return values are // 0 - success // 1 - modifier mismatch // 2 - type mismatch // -1 - dynamic binding required // int IsArgumentCompatible (ResolveContext ec, Argument argument, Parameter.Modifier param_mod, TypeSpec parameter) { // // Types have to be identical when ref or out modifer // is used and argument is not of dynamic type // if (((argument.Modifier | param_mod) & Parameter.Modifier.RefOutMask) != 0) { var arg_type = argument.Type; if ((argument.Modifier & Parameter.Modifier.RefOutMask) != (param_mod & Parameter.Modifier.RefOutMask)) { // // Using dynamic for ref/out parameter can still succeed at runtime // if (arg_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && (argument.Modifier & Parameter.Modifier.RefOutMask) == 0 && (restrictions & Restrictions.CovariantDelegate) == 0) return -1; return 1; } if (arg_type != parameter) { if (arg_type == InternalType.VarOutType) return 0; // // Do full equality check after quick path // if (!TypeSpecComparer.IsEqual (arg_type, parameter)) { // // Using dynamic for ref/out parameter can still succeed at runtime // if (arg_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && (argument.Modifier & Parameter.Modifier.RefOutMask) == 0 && (restrictions & Restrictions.CovariantDelegate) == 0) return -1; return 2; } } } else { if (argument.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && (restrictions & Restrictions.CovariantDelegate) == 0) return -1; // // Use implicit conversion in all modes to return same candidates when the expression // is used as argument or delegate conversion // if (!Convert.ImplicitConversionExists (ec, argument.Expr, parameter)) { return parameter.IsDelegate && argument.Expr is AnonymousMethodExpression ? 2 : 3; } } return 0; } static TypeSpec MoreSpecific (TypeSpec p, TypeSpec q) { if (TypeManager.IsGenericParameter (p) && !TypeManager.IsGenericParameter (q)) return q; if (!TypeManager.IsGenericParameter (p) && TypeManager.IsGenericParameter (q)) return p; var ac_p = p as ArrayContainer; if (ac_p != null) { var ac_q = q as ArrayContainer; if (ac_q == null) return null; TypeSpec specific = MoreSpecific (ac_p.Element, ac_q.Element); if (specific == ac_p.Element) return p; if (specific == ac_q.Element) return q; } else if (p.IsGeneric && q.IsGeneric) { var pargs = TypeManager.GetTypeArguments (p); var qargs = TypeManager.GetTypeArguments (q); bool p_specific_at_least_once = false; bool q_specific_at_least_once = false; for (int i = 0; i < pargs.Length; i++) { TypeSpec specific = MoreSpecific (pargs[i], qargs[i]); if (specific == pargs[i]) p_specific_at_least_once = true; if (specific == qargs[i]) q_specific_at_least_once = true; } if (p_specific_at_least_once && !q_specific_at_least_once) return p; if (!p_specific_at_least_once && q_specific_at_least_once) return q; } return null; } // // Find the best method from candidate list // public T ResolveMember<T> (ResolveContext rc, ref Arguments args) where T : MemberSpec, IParametersMember { List<AmbiguousCandidate> ambiguous_candidates = null; MemberSpec best_candidate; Arguments best_candidate_args = null; bool best_candidate_params = false; bool best_candidate_dynamic = false; int best_candidate_rate; IParametersMember best_parameter_member = null; int args_count = args != null ? args.Count : 0; Arguments candidate_args = args; bool error_mode = false; MemberSpec invocable_member = null; while (true) { best_candidate = null; best_candidate_rate = int.MaxValue; var type_members = members; do { for (int i = 0; i < type_members.Count; ++i) { var member = type_members[i]; // // Methods in a base class are not candidates if any method in a derived // class is applicable // if ((member.Modifiers & Modifiers.OVERRIDE) != 0) continue; if (!error_mode) { if (!member.IsAccessible (rc)) continue; if (rc.IsRuntimeBinder && !member.DeclaringType.IsAccessible (rc)) continue; if ((member.Modifiers & (Modifiers.PROTECTED | Modifiers.STATIC)) == Modifiers.PROTECTED && instance_qualifier != null && !instance_qualifier.CheckProtectedMemberAccess (rc, member)) { continue; } } IParametersMember pm = member as IParametersMember; if (pm == null) { // // Will use it later to report ambiguity between best method and invocable member // if (Invocation.IsMemberInvocable (member)) invocable_member = member; continue; } // // Overload resolution is looking for base member but using parameter names // and default values from the closest member. That means to do expensive lookup // for the closest override for virtual or abstract members // if ((member.Modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) { var override_params = base_provider.GetOverrideMemberParameters (member); if (override_params != null) pm = override_params; } // // Check if the member candidate is applicable // bool params_expanded_form = false; bool dynamic_argument = false; TypeSpec rt = pm.MemberType; int candidate_rate = IsApplicable (rc, ref candidate_args, args_count, ref member, pm, ref params_expanded_form, ref dynamic_argument, ref rt, error_mode); if (lambda_conv_msgs != null) lambda_conv_msgs.EndSession (); // // How does it score compare to others // if (candidate_rate < best_candidate_rate) { // Fatal error (missing dependency), cannot continue if (candidate_rate < 0) return null; if ((restrictions & Restrictions.GetEnumeratorLookup) != 0 && candidate_args.Count != 0) { // Only parameterless methods are considered } else { best_candidate_rate = candidate_rate; best_candidate = member; best_candidate_args = candidate_args; best_candidate_params = params_expanded_form; best_candidate_dynamic = dynamic_argument; best_parameter_member = pm; best_candidate_return_type = rt; } } else if (candidate_rate == 0) { // // The member look is done per type for most operations but sometimes // it's not possible like for binary operators overload because they // are unioned between 2 sides // if ((restrictions & Restrictions.BaseMembersIncluded) != 0) { if (TypeSpec.IsBaseClass (best_candidate.DeclaringType, member.DeclaringType, true)) continue; } bool is_better; if (best_candidate.DeclaringType.IsInterface && member.DeclaringType.ImplementsInterface (best_candidate.DeclaringType, false)) { // // We pack all interface members into top level type which makes the overload resolution // more complicated for interfaces. We compensate it by removing methods with same // signature when building the cache hence this path should not really be hit often // // Example: // interface IA { void Foo (int arg); } // interface IB : IA { void Foo (params int[] args); } // // IB::Foo is the best overload when calling IB.Foo (1) // is_better = true; if (ambiguous_candidates != null) { foreach (var amb_cand in ambiguous_candidates) { if (member.DeclaringType.ImplementsInterface (best_candidate.DeclaringType, false)) { continue; } is_better = false; break; } if (is_better) ambiguous_candidates = null; } } else { // Is the new candidate better is_better = BetterFunction (rc, candidate_args, member, pm.Parameters, params_expanded_form, best_candidate, best_parameter_member.Parameters, best_candidate_params); } if (is_better) { best_candidate = member; best_candidate_args = candidate_args; best_candidate_params = params_expanded_form; best_candidate_dynamic = dynamic_argument; best_parameter_member = pm; best_candidate_return_type = rt; } else { // It's not better but any other found later could be but we are not sure yet if (ambiguous_candidates == null) ambiguous_candidates = new List<AmbiguousCandidate> (); ambiguous_candidates.Add (new AmbiguousCandidate (member, pm.Parameters, params_expanded_form)); } } // Restore expanded arguments candidate_args = args; } } while (best_candidate_rate != 0 && (type_members = base_provider.GetBaseMembers (type_members[0].DeclaringType.BaseType)) != null); // // We've found exact match // if (best_candidate_rate == 0) break; // // Try extension methods lookup when no ordinary method match was found and provider enables it // if (!error_mode) { var emg = base_provider.LookupExtensionMethod (rc); if (emg != null) { emg = emg.OverloadResolve (rc, ref args, null, restrictions); if (emg != null) { best_candidate_extension_group = emg; return (T) (MemberSpec) emg.BestCandidate; } } } // Don't run expensive error reporting mode for probing if (IsProbingOnly) return null; if (error_mode) break; if (lambda_conv_msgs != null && !lambda_conv_msgs.IsEmpty) break; lambda_conv_msgs = null; error_mode = true; } // // No best member match found, report an error // if (best_candidate_rate != 0 || error_mode) { ReportOverloadError (rc, best_candidate, best_parameter_member, best_candidate_args, best_candidate_params); return null; } if (best_candidate_dynamic) { if (args[0].IsExtensionType) { rc.Report.Error (1973, loc, "Type `{0}' does not contain a member `{1}' and the best extension method overload `{2}' cannot be dynamically dispatched. Consider calling the method without the extension method syntax", args [0].Type.GetSignatureForError (), best_candidate.Name, best_candidate.GetSignatureForError ()); } // // Check type constraints only when explicit type arguments are used // if (best_candidate.IsGeneric && type_arguments != null) { MethodSpec bc = best_candidate as MethodSpec; if (bc != null && TypeParameterSpec.HasAnyTypeParameterConstrained (bc.GenericDefinition)) { ConstraintChecker cc = new ConstraintChecker (rc); cc.CheckAll (bc.GetGenericMethodDefinition (), bc.TypeArguments, bc.Constraints, loc); } } BestCandidateIsDynamic = true; return null; } // // These flags indicates we are running delegate probing conversion. No need to // do more expensive checks // if ((restrictions & (Restrictions.ProbingOnly | Restrictions.CovariantDelegate)) == (Restrictions.CovariantDelegate | Restrictions.ProbingOnly)) return (T) best_candidate; if (ambiguous_candidates != null) { // // Now check that there are no ambiguities i.e the selected method // should be better than all the others // for (int ix = 0; ix < ambiguous_candidates.Count; ix++) { var candidate = ambiguous_candidates [ix]; if (!BetterFunction (rc, best_candidate_args, best_candidate, best_parameter_member.Parameters, best_candidate_params, candidate.Member, candidate.Parameters, candidate.Expanded)) { var ambiguous = candidate.Member; if (custom_errors == null || !custom_errors.AmbiguousCandidates (rc, best_candidate, ambiguous)) { rc.Report.SymbolRelatedToPreviousError (best_candidate); rc.Report.SymbolRelatedToPreviousError (ambiguous); rc.Report.Error (121, loc, "The call is ambiguous between the following methods or properties: `{0}' and `{1}'", best_candidate.GetSignatureForError (), ambiguous.GetSignatureForError ()); } return (T) best_candidate; } } } if (invocable_member != null && !IsProbingOnly) { rc.Report.SymbolRelatedToPreviousError (best_candidate); rc.Report.SymbolRelatedToPreviousError (invocable_member); rc.Report.Warning (467, 2, loc, "Ambiguity between method `{0}' and invocable non-method `{1}'. Using method group", best_candidate.GetSignatureForError (), invocable_member.GetSignatureForError ()); } // // And now check if the arguments are all // compatible, perform conversions if // necessary etc. and return if everything is // all right // if (!VerifyArguments (rc, ref best_candidate_args, best_candidate, best_parameter_member, best_candidate_params)) return null; if (best_candidate == null) return null; // // Don't run possibly expensive checks in probing mode // if (!IsProbingOnly && !rc.IsInProbingMode) { // // Check ObsoleteAttribute on the best method // ObsoleteAttribute oa = best_candidate.GetAttributeObsolete (); if (oa != null && !rc.IsObsolete) AttributeTester.Report_ObsoleteMessage (oa, best_candidate.GetSignatureForError (), loc, rc.Report); best_candidate.MemberDefinition.SetIsUsed (); } args = best_candidate_args; return (T) best_candidate; } public MethodSpec ResolveOperator (ResolveContext rc, ref Arguments args) { return ResolveMember<MethodSpec> (rc, ref args); } void ReportArgumentMismatch (ResolveContext ec, int idx, MemberSpec method, Argument a, AParametersCollection expected_par, TypeSpec paramType) { if (custom_errors != null && custom_errors.ArgumentMismatch (ec, method, a, idx)) return; if (a.Type == InternalType.ErrorType) return; if (a is CollectionElementInitializer.ElementInitializerArgument) { ec.Report.SymbolRelatedToPreviousError (method); if ((expected_par.FixedParameters[idx].ModFlags & Parameter.Modifier.RefOutMask) != 0) { ec.Report.Error (1954, loc, "The best overloaded collection initalizer method `{0}' cannot have `ref' or `out' modifier", TypeManager.CSharpSignature (method)); return; } ec.Report.Error (1950, loc, "The best overloaded collection initalizer method `{0}' has some invalid arguments", TypeManager.CSharpSignature (method)); } else if (IsDelegateInvoke) { ec.Report.Error (1594, loc, "Delegate `{0}' has some invalid arguments", DelegateType.GetSignatureForError ()); } else { ec.Report.SymbolRelatedToPreviousError (method); ec.Report.Error (1502, loc, "The best overloaded method match for `{0}' has some invalid arguments", method.GetSignatureForError ()); } Parameter.Modifier mod = idx >= expected_par.Count ? 0 : expected_par.FixedParameters[idx].ModFlags; string index = (idx + 1).ToString (); if (((mod & Parameter.Modifier.RefOutMask) ^ (a.Modifier & Parameter.Modifier.RefOutMask)) != 0) { if ((mod & Parameter.Modifier.RefOutMask) == 0) ec.Report.Error (1615, a.Expr.Location, "Argument `#{0}' does not require `{1}' modifier. Consider removing `{1}' modifier", index, Parameter.GetModifierSignature (a.Modifier)); else ec.Report.Error (1620, a.Expr.Location, "Argument `#{0}' is missing `{1}' modifier", index, Parameter.GetModifierSignature (mod)); } else { string p1 = a.GetSignatureForError (); string p2 = paramType.GetSignatureForError (); if (p1 == p2) { p1 = a.Type.GetSignatureForErrorIncludingAssemblyName (); p2 = paramType.GetSignatureForErrorIncludingAssemblyName (); } if ((mod & Parameter.Modifier.RefOutMask) != 0) { p1 = Parameter.GetModifierSignature (a.Modifier) + " " + p1; p2 = Parameter.GetModifierSignature (a.Modifier) + " " + p2; } ec.Report.Error (1503, a.Expr.Location, "Argument `#{0}' cannot convert `{1}' expression to type `{2}'", index, p1, p2); } } // // We have failed to find exact match so we return error info about the closest match // void ReportOverloadError (ResolveContext rc, MemberSpec best_candidate, IParametersMember pm, Arguments args, bool params_expanded) { int ta_count = type_arguments == null ? 0 : type_arguments.Count; int arg_count = args == null ? 0 : args.Count; if (ta_count != best_candidate.Arity && (ta_count > 0 || ((IParametersMember) best_candidate).Parameters.IsEmpty)) { var mg = new MethodGroupExpr (new [] { best_candidate }, best_candidate.DeclaringType, loc); mg.Error_TypeArgumentsCannotBeUsed (rc, best_candidate, loc); return; } if (lambda_conv_msgs != null && lambda_conv_msgs.Merge (rc.Report.Printer)) { return; } if ((best_candidate.Modifiers & (Modifiers.PROTECTED | Modifiers.STATIC)) == Modifiers.PROTECTED && InstanceQualifier != null && !InstanceQualifier.CheckProtectedMemberAccess (rc, best_candidate)) { MemberExpr.Error_ProtectedMemberAccess (rc, best_candidate, InstanceQualifier.InstanceType, loc); } // // For candidates which match on parameters count report more details about incorrect arguments // if (pm != null) { if (pm.Parameters.Count == arg_count || params_expanded || HasUnfilledParams (best_candidate, pm, args)) { // Reject any inaccessible member if (!best_candidate.IsAccessible (rc) || !best_candidate.DeclaringType.IsAccessible (rc)) { rc.Report.SymbolRelatedToPreviousError (best_candidate); Expression.ErrorIsInaccesible (rc, best_candidate.GetSignatureForError (), loc); return; } var ms = best_candidate as MethodSpec; if (ms != null && ms.IsGeneric) { bool constr_ok = true; if (ms.TypeArguments != null) constr_ok = new ConstraintChecker (rc.MemberContext).CheckAll (ms.GetGenericMethodDefinition (), ms.TypeArguments, ms.Constraints, loc); if (ta_count == 0 && ms.TypeArguments == null) { if (custom_errors != null && custom_errors.TypeInferenceFailed (rc, best_candidate)) return; if (constr_ok) { rc.Report.Error (411, loc, "The type arguments for method `{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly", ms.GetGenericMethodDefinition ().GetSignatureForError ()); } return; } } VerifyArguments (rc, ref args, best_candidate, pm, params_expanded); return; } } // // We failed to find any method with correct argument count, report best candidate // if (custom_errors != null && custom_errors.NoArgumentMatch (rc, best_candidate)) return; if (best_candidate.Kind == MemberKind.Constructor) { rc.Report.SymbolRelatedToPreviousError (best_candidate); Error_ConstructorMismatch (rc, best_candidate.DeclaringType, arg_count, loc); } else if (IsDelegateInvoke) { rc.Report.SymbolRelatedToPreviousError (DelegateType); rc.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments", DelegateType.GetSignatureForError (), arg_count.ToString ()); } else { string name = best_candidate.Kind == MemberKind.Indexer ? "this" : best_candidate.Name; rc.Report.SymbolRelatedToPreviousError (best_candidate); rc.Report.Error (1501, loc, "No overload for method `{0}' takes `{1}' arguments", name, arg_count.ToString ()); } } static bool HasUnfilledParams (MemberSpec best_candidate, IParametersMember pm, Arguments args) { var p = ((IParametersMember)best_candidate).Parameters; if (!p.HasParams) return false; string name = null; for (int i = p.Count - 1; i != 0; --i) { var fp = p.FixedParameters [i]; if ((fp.ModFlags & Parameter.Modifier.PARAMS) == 0) continue; name = fp.Name; break; } if (args == null) return false; foreach (var arg in args) { var na = arg as NamedArgument; if (na == null) continue; if (na.Name == name) { name = null; break; } } if (name == null) return false; return args.Count + 1 == pm.Parameters.Count; } bool VerifyArguments (ResolveContext ec, ref Arguments args, MemberSpec member, IParametersMember pm, bool chose_params_expanded) { var pd = pm.Parameters; var cpd = ((IParametersMember) member).Parameters; var ptypes = cpd.Types; Parameter.Modifier p_mod = 0; TypeSpec pt = null; int a_idx = 0, a_pos = 0; Argument a = null; ArrayInitializer params_initializers = null; bool has_unsafe_arg = pm.MemberType.IsPointer; int arg_count = args == null ? 0 : args.Count; for (; a_idx < arg_count; a_idx++, ++a_pos) { a = args[a_idx]; if (a == null) continue; if (p_mod != Parameter.Modifier.PARAMS) { p_mod = cpd.FixedParameters [a_idx].ModFlags; pt = ptypes[a_idx]; has_unsafe_arg |= pt.IsPointer; if (p_mod == Parameter.Modifier.PARAMS) { if (chose_params_expanded) { params_initializers = new ArrayInitializer (arg_count - a_idx, a.Expr.Location); pt = TypeManager.GetElementType (pt); } } } // // Types have to be identical when ref or out modifer is used // if (((a.Modifier | p_mod) & Parameter.Modifier.RefOutMask) != 0) { if ((a.Modifier & Parameter.Modifier.RefOutMask) != (p_mod & Parameter.Modifier.RefOutMask)) break; var arg_type = a.Type; if (arg_type == pt) continue; if (arg_type == InternalType.VarOutType) { // // Set underlying variable type based on parameter type // ((DeclarationExpression)a.Expr).Variable.Type = pt; continue; } if (!TypeSpecComparer.IsEqual (arg_type, pt)) break; } NamedArgument na = a as NamedArgument; if (na != null) { int name_index = pd.GetParameterIndexByName (na.Name); if (name_index < 0 || name_index >= pd.Count) { if (IsDelegateInvoke) { ec.Report.SymbolRelatedToPreviousError (DelegateType); ec.Report.Error (1746, na.Location, "The delegate `{0}' does not contain a parameter named `{1}'", DelegateType.GetSignatureForError (), na.Name); } else { ec.Report.SymbolRelatedToPreviousError (member); ec.Report.Error (1739, na.Location, "The best overloaded method match for `{0}' does not contain a parameter named `{1}'", TypeManager.CSharpSignature (member), na.Name); } } else if (args[name_index] != a && args[name_index] != null) { if (IsDelegateInvoke) ec.Report.SymbolRelatedToPreviousError (DelegateType); else ec.Report.SymbolRelatedToPreviousError (member); ec.Report.Error (1744, na.Location, "Named argument `{0}' cannot be used for a parameter which has positional argument specified", na.Name); } } if (a.Expr.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) continue; if ((restrictions & Restrictions.CovariantDelegate) != 0 && !Delegate.IsTypeCovariant (ec, a.Expr.Type, pt)) { custom_errors.NoArgumentMatch (ec, member); return false; } Expression conv; if (a.IsExtensionType) { if (a.Expr.Type == pt || TypeSpecComparer.IsEqual (a.Expr.Type, pt)) { conv = a.Expr; } else { conv = Convert.ImplicitReferenceConversion (a.Expr, pt, false); if (conv == null) conv = Convert.ImplicitBoxingConversion (a.Expr, a.Expr.Type, pt); } } else { conv = Convert.ImplicitConversion (ec, a.Expr, pt, loc); } if (conv == null) break; // // Convert params arguments to an array initializer // if (params_initializers != null) { // we choose to use 'a.Expr' rather than 'conv' so that // we don't hide the kind of expression we have (esp. CompoundAssign.Helper) params_initializers.Add (a.Expr); args.RemoveAt (a_idx--); --arg_count; a.Expr = conv; continue; } // Update the argument with the implicit conversion a.Expr = conv; } if (a_idx != arg_count) { // // Convert all var out argument to error type for less confusing error reporting // when no matching overload is found // for (; a_idx < arg_count; a_idx++) { var arg = args [a_idx]; if (arg == null) continue; if (arg.Type == InternalType.VarOutType) { ((DeclarationExpression)arg.Expr).Variable.Type = InternalType.ErrorType; } } ReportArgumentMismatch (ec, a_pos, member, a, pd, pt); return false; } // // Fill not provided arguments required by params modifier // if (params_initializers == null && arg_count + 1 == pd.Count) { if (args == null) args = new Arguments (1); pt = ptypes[pd.Count - 1]; pt = TypeManager.GetElementType (pt); has_unsafe_arg |= pt.IsPointer; params_initializers = new ArrayInitializer (0, loc); } // // Append an array argument with all params arguments // if (params_initializers != null) { args.Add (new Argument ( new ArrayCreation (new TypeExpression (pt, loc), params_initializers, loc).Resolve (ec))); arg_count++; } if (has_unsafe_arg && !ec.IsUnsafe) { Expression.UnsafeError (ec, loc); } // // We could infer inaccesible type arguments // if (type_arguments == null && member.IsGeneric) { var ms = (MethodSpec) member; foreach (var ta in ms.TypeArguments) { if (!ta.IsAccessible (ec)) { ec.Report.SymbolRelatedToPreviousError (ta); Expression.ErrorIsInaccesible (ec, member.GetSignatureForError (), loc); break; } } } return true; } } public class ConstantExpr : MemberExpr { readonly ConstSpec constant; public ConstantExpr (ConstSpec constant, Location loc) { this.constant = constant; this.loc = loc; } public override string Name { get { throw new NotImplementedException (); } } public override string KindName { get { return "constant"; } } public override bool IsInstance { get { return !IsStatic; } } public override bool IsStatic { get { return true; } } protected override TypeSpec DeclaringType { get { return constant.DeclaringType; } } public override Expression CreateExpressionTree (ResolveContext ec) { throw new NotSupportedException ("ET"); } protected override Expression DoResolve (ResolveContext rc) { ResolveInstanceExpression (rc, null); DoBestMemberChecks (rc, constant); var c = constant.GetConstant (rc); // Creates reference expression to the constant value return Constant.CreateConstantFromValue (constant.MemberType, c.GetValue (), loc); } public override void Emit (EmitContext ec) { throw new NotSupportedException (); } public override string GetSignatureForError () { return constant.GetSignatureForError (); } public override void SetTypeArguments (ResolveContext ec, TypeArguments ta) { Error_TypeArgumentsCannotBeUsed (ec, "constant", GetSignatureForError (), loc); } } // // Fully resolved expression that references a Field // public class FieldExpr : MemberExpr, IDynamicAssign, IMemoryLocation, IVariableReference { protected FieldSpec spec; VariableInfo variable_info; LocalTemporary temp; bool prepared; protected FieldExpr (Location l) { loc = l; } public FieldExpr (FieldSpec spec, Location loc) { this.spec = spec; this.loc = loc; type = spec.MemberType; } public FieldExpr (FieldBase fi, Location l) : this (fi.Spec, l) { } #region Properties public override string Name { get { return spec.Name; } } public bool IsHoisted { get { IVariableReference hv = InstanceExpression as IVariableReference; return hv != null && hv.IsHoisted; } } public override bool IsInstance { get { return !spec.IsStatic; } } public override bool IsStatic { get { return spec.IsStatic; } } public override string KindName { get { return "field"; } } public FieldSpec Spec { get { return spec; } } protected override TypeSpec DeclaringType { get { return spec.DeclaringType; } } public VariableInfo VariableInfo { get { return variable_info; } } #endregion public override string GetSignatureForError () { return spec.GetSignatureForError (); } public bool IsMarshalByRefAccess (ResolveContext rc) { // Checks possible ldflda of field access expression return !spec.IsStatic && TypeSpec.IsValueType (spec.MemberType) && !(InstanceExpression is This) && rc.Module.PredefinedTypes.MarshalByRefObject.Define () && TypeSpec.IsBaseClass (spec.DeclaringType, rc.Module.PredefinedTypes.MarshalByRefObject.TypeSpec, false); } public void SetHasAddressTaken () { IVariableReference vr = InstanceExpression as IVariableReference; if (vr != null) { vr.SetHasAddressTaken (); } } protected override void CloneTo (CloneContext clonectx, Expression target) { var t = (FieldExpr) target; if (InstanceExpression != null) t.InstanceExpression = InstanceExpression.Clone (clonectx); } public override Expression CreateExpressionTree (ResolveContext ec) { if (ConditionalAccess) { Error_NullShortCircuitInsideExpressionTree (ec); } return CreateExpressionTree (ec, true); } public Expression CreateExpressionTree (ResolveContext ec, bool convertInstance) { Arguments args; Expression instance; if (InstanceExpression == null) { instance = new NullLiteral (loc); } else if (convertInstance) { instance = InstanceExpression.CreateExpressionTree (ec); } else { args = new Arguments (1); args.Add (new Argument (InstanceExpression)); instance = CreateExpressionFactoryCall (ec, "Constant", args); } args = Arguments.CreateForExpressionTree (ec, null, instance, CreateTypeOfExpression ()); return CreateExpressionFactoryCall (ec, "Field", args); } public Expression CreateTypeOfExpression () { return new TypeOfField (spec, loc); } protected override Expression DoResolve (ResolveContext ec) { spec.MemberDefinition.SetIsUsed (); return DoResolve (ec, null); } Expression DoResolve (ResolveContext ec, Expression rhs) { bool lvalue_instance = rhs != null && IsInstance && spec.DeclaringType.IsStruct; if (rhs != this) { ResolveConditionalAccessReceiver (ec); if (ResolveInstanceExpression (ec, rhs)) { // Resolve the field's instance expression while flow analysis is turned // off: when accessing a field "a.b", we must check whether the field // "a.b" is initialized, not whether the whole struct "a" is initialized. if (lvalue_instance) { bool out_access = rhs == EmptyExpression.OutAccess || rhs == EmptyExpression.LValueMemberOutAccess; Expression right_side = out_access ? EmptyExpression.LValueMemberOutAccess : EmptyExpression.LValueMemberAccess; InstanceExpression = InstanceExpression.ResolveLValue (ec, right_side); } else { InstanceExpression = InstanceExpression.Resolve (ec, ResolveFlags.VariableOrValue); } if (InstanceExpression == null) return null; } DoBestMemberChecks (ec, spec); if (conditional_access_receiver) ec.With (ResolveContext.Options.ConditionalAccessReceiver, false); } var fb = spec as FixedFieldSpec; IVariableReference var = InstanceExpression as IVariableReference; if (fb != null) { IFixedExpression fe = InstanceExpression as IFixedExpression; if (!ec.HasSet (ResolveContext.Options.FixedInitializerScope) && (fe == null || !fe.IsFixed)) { ec.Report.Error (1666, loc, "You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement"); } if (InstanceExpression.eclass != ExprClass.Variable) { ec.Report.SymbolRelatedToPreviousError (spec); ec.Report.Error (1708, loc, "`{0}': Fixed size buffers can only be accessed through locals or fields", TypeManager.GetFullNameSignature (spec)); } else if (var != null && var.IsHoisted) { AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, var, loc); } return new FixedBufferPtr (this, fb.ElementType, loc).Resolve (ec); } // // Set flow-analysis variable info for struct member access. It will be check later // for precise error reporting // if (var != null && var.VariableInfo != null && InstanceExpression.Type.IsStruct) { variable_info = var.VariableInfo.GetStructFieldInfo (Name); } if (ConditionalAccess) { if (conditional_access_receiver) type = LiftMemberType (ec, type); if (InstanceExpression.IsNull) return Constant.CreateConstantFromValue (type, null, loc); } eclass = ExprClass.Variable; return this; } public void SetFieldAssigned (FlowAnalysisContext fc) { if (!IsInstance) return; bool lvalue_instance = spec.DeclaringType.IsStruct; if (lvalue_instance) { var var = InstanceExpression as IVariableReference; if (var != null && var.VariableInfo != null) { fc.SetStructFieldAssigned (var.VariableInfo, Name); } } var fe = InstanceExpression as FieldExpr; if (fe != null) { Expression instance; do { instance = fe.InstanceExpression; var fe_instance = instance as FieldExpr; if ((fe_instance != null && !fe_instance.IsStatic) || instance is LocalVariableReference) { if (TypeSpec.IsReferenceType (fe.Type) && instance.Type.IsStruct) { var var = InstanceExpression as IVariableReference; if (var != null && var.VariableInfo == null) { var var_inst = instance as IVariableReference; if (var_inst == null || (var_inst.VariableInfo != null && !fc.IsDefinitelyAssigned (var_inst.VariableInfo))) fc.Report.Warning (1060, 1, fe.loc, "Use of possibly unassigned field `{0}'", fe.Name); } } if (fe_instance != null) { fe = fe_instance; continue; } } break; } while (true); if (instance != null && TypeSpec.IsReferenceType (instance.Type)) instance.FlowAnalysis (fc); } else { if (TypeSpec.IsReferenceType (InstanceExpression.Type)) InstanceExpression.FlowAnalysis (fc); } } Expression Error_AssignToReadonly (ResolveContext rc, Expression right_side) { // The return value is always null. Returning a value simplifies calling code. if (right_side == EmptyExpression.OutAccess) { if (IsStatic) { rc.Report.Error (199, loc, "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)", GetSignatureForError ()); } else { rc.Report.Error (192, loc, "A readonly field `{0}' cannot be passed ref or out (except in a constructor)", GetSignatureForError ()); } return null; } if (right_side == EmptyExpression.LValueMemberAccess) { // Already reported as CS1648/CS1650 return null; } if (right_side == EmptyExpression.LValueMemberOutAccess) { if (IsStatic) { rc.Report.Error (1651, loc, "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)", GetSignatureForError ()); } else { rc.Report.Error (1649, loc, "Members of readonly field `{0}' cannot be passed ref or out (except in a constructor)", GetSignatureForError ()); } return null; } if (IsStatic) { rc.Report.Error (198, loc, "A static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)", GetSignatureForError ()); } else { rc.Report.Error (191, loc, "A readonly field `{0}' cannot be assigned to (except in a constructor or a variable initializer)", GetSignatureForError ()); } return null; } public override Expression DoResolveLValue (ResolveContext ec, Expression right_side) { if (ConditionalAccess) throw new NotSupportedException ("null propagating operator assignment"); if (spec is FixedFieldSpec) { // It could be much better error message but we want to be error compatible Error_ValueAssignment (ec, right_side); } Expression e = DoResolve (ec, right_side); if (e == null) return null; spec.MemberDefinition.SetIsAssigned (); if ((right_side == EmptyExpression.UnaryAddress || right_side == EmptyExpression.OutAccess) && (spec.Modifiers & Modifiers.VOLATILE) != 0) { ec.Report.Warning (420, 1, loc, "`{0}': A volatile field references will not be treated as volatile", spec.GetSignatureForError ()); } if (spec.IsReadOnly) { // InitOnly fields can only be assigned in constructors or initializers if (!ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.ConstructorScope)) return Error_AssignToReadonly (ec, right_side); if (ec.HasSet (ResolveContext.Options.ConstructorScope)) { // InitOnly fields cannot be assigned-to in a different constructor from their declaring type if (ec.CurrentMemberDefinition.Parent.PartialContainer.Definition != spec.DeclaringType.GetDefinition ()) return Error_AssignToReadonly (ec, right_side); // static InitOnly fields cannot be assigned-to in an instance constructor if (IsStatic && !ec.IsStatic) return Error_AssignToReadonly (ec, right_side); // instance constructors can't modify InitOnly fields of other instances of the same type if (!IsStatic && !(InstanceExpression is This)) return Error_AssignToReadonly (ec, right_side); } } if (right_side == EmptyExpression.OutAccess && IsMarshalByRefAccess (ec)) { ec.Report.SymbolRelatedToPreviousError (spec.DeclaringType); ec.Report.Warning (197, 1, loc, "Passing `{0}' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class", GetSignatureForError ()); } eclass = ExprClass.Variable; return this; } public override void FlowAnalysis (FlowAnalysisContext fc) { var var = InstanceExpression as IVariableReference; if (var != null) { var vi = var.VariableInfo; if (vi != null && !fc.IsStructFieldDefinitelyAssigned (vi, Name)) { fc.Report.Error (170, loc, "Use of possibly unassigned field `{0}'", Name); return; } if (TypeSpec.IsValueType (InstanceExpression.Type) && InstanceExpression is VariableReference) return; } base.FlowAnalysis (fc); if (conditional_access_receiver) fc.ConditionalAccessEnd (); } public override int GetHashCode () { return spec.GetHashCode (); } public bool IsFixed { get { // // A variable of the form V.I is fixed when V is a fixed variable of a struct type // IVariableReference variable = InstanceExpression as IVariableReference; if (variable != null) return InstanceExpression.Type.IsStruct && variable.IsFixed; IFixedExpression fe = InstanceExpression as IFixedExpression; return fe != null && fe.IsFixed; } } public override bool Equals (object obj) { FieldExpr fe = obj as FieldExpr; if (fe == null) return false; if (spec != fe.spec) return false; if (InstanceExpression == null || fe.InstanceExpression == null) return true; return InstanceExpression.Equals (fe.InstanceExpression); } public void Emit (EmitContext ec, bool leave_copy) { bool is_volatile = (spec.Modifiers & Modifiers.VOLATILE) != 0; if (IsStatic){ if (is_volatile) ec.Emit (OpCodes.Volatile); ec.Emit (OpCodes.Ldsfld, spec); } else { if (!prepared) { if (conditional_access_receiver) ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ()); EmitInstance (ec, false); } // Optimization for build-in types if (type.IsStruct && type == ec.CurrentType && InstanceExpression.Type == type) { ec.EmitLoadFromPtr (type); } else { var ff = spec as FixedFieldSpec; if (ff != null) { ec.Emit (OpCodes.Ldflda, spec); ec.Emit (OpCodes.Ldflda, ff.Element); } else { if (is_volatile) ec.Emit (OpCodes.Volatile); ec.Emit (OpCodes.Ldfld, spec); } } if (conditional_access_receiver) { ec.CloseConditionalAccess (type.IsNullableType && type != spec.MemberType ? type : null); } } if (leave_copy) { ec.Emit (OpCodes.Dup); if (!IsStatic) { temp = new LocalTemporary (this.Type); temp.Store (ec); } } } public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound) { bool has_await_source = ec.HasSet (BuilderContext.Options.AsyncBody) && source.ContainsEmitWithAwait (); if (isCompound && !(source is DynamicExpressionStatement) && !has_await_source) { prepared = true; } if (IsInstance) { if (ConditionalAccess) throw new NotImplementedException ("null operator assignment"); if (has_await_source) source = source.EmitToField (ec); EmitInstance (ec, prepared); } source.Emit (ec); if (leave_copy || ec.NotifyEvaluatorOnStore) { ec.Emit (OpCodes.Dup); if (!IsStatic) { temp = new LocalTemporary (this.Type); temp.Store (ec); } } if ((spec.Modifiers & Modifiers.VOLATILE) != 0) ec.Emit (OpCodes.Volatile); spec.MemberDefinition.SetIsAssigned (); if (IsStatic) ec.Emit (OpCodes.Stsfld, spec); else ec.Emit (OpCodes.Stfld, spec); if (ec.NotifyEvaluatorOnStore) { if (!IsStatic) throw new NotImplementedException ("instance field write"); if (leave_copy) ec.Emit (OpCodes.Dup); ec.Module.Evaluator.EmitValueChangedCallback (ec, Name, type, loc); } if (temp != null) { temp.Emit (ec); temp.Release (ec); temp = null; } } // // Emits store to field with prepared values on stack // public void EmitAssignFromStack (EmitContext ec) { if (IsStatic) { ec.Emit (OpCodes.Stsfld, spec); } else { ec.Emit (OpCodes.Stfld, spec); } } public override void Emit (EmitContext ec) { Emit (ec, false); } public override void EmitSideEffect (EmitContext ec) { bool is_volatile = (spec.Modifiers & Modifiers.VOLATILE) != 0; if (is_volatile) // || is_marshal_by_ref ()) base.EmitSideEffect (ec); } public virtual void AddressOf (EmitContext ec, AddressOp mode) { if ((mode & AddressOp.Store) != 0) spec.MemberDefinition.SetIsAssigned (); if ((mode & AddressOp.Load) != 0) spec.MemberDefinition.SetIsUsed (); // // Handle initonly fields specially: make a copy and then // get the address of the copy. // bool need_copy; if (spec.IsReadOnly){ need_copy = true; if (ec.HasSet (EmitContext.Options.ConstructorScope) && spec.DeclaringType == ec.CurrentType) { if (IsStatic){ if (ec.IsStatic) need_copy = false; } else need_copy = false; } } else need_copy = false; if (need_copy) { Emit (ec); var temp = ec.GetTemporaryLocal (type); ec.Emit (OpCodes.Stloc, temp); ec.Emit (OpCodes.Ldloca, temp); return; } if (IsStatic){ ec.Emit (OpCodes.Ldsflda, spec); } else { if (!prepared) EmitInstance (ec, false); ec.Emit (OpCodes.Ldflda, spec); } } public SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source) { return MakeExpression (ctx); } public override SLE.Expression MakeExpression (BuilderContext ctx) { #if STATIC return base.MakeExpression (ctx); #else return SLE.Expression.Field ( IsStatic ? null : InstanceExpression.MakeExpression (ctx), spec.GetMetaInfo ()); #endif } public override void SetTypeArguments (ResolveContext ec, TypeArguments ta) { Error_TypeArgumentsCannotBeUsed (ec, "field", GetSignatureForError (), loc); } } // // Expression that evaluates to a Property. // // This is not an LValue because we need to re-write the expression. We // can not take data from the stack and store it. // sealed class PropertyExpr : PropertyOrIndexerExpr<PropertySpec> { Arguments arguments; public PropertyExpr (PropertySpec spec, Location l) : base (l) { best_candidate = spec; type = spec.MemberType; } #region Properties protected override Arguments Arguments { get { return arguments; } set { arguments = value; } } protected override TypeSpec DeclaringType { get { return best_candidate.DeclaringType; } } public override string Name { get { return best_candidate.Name; } } public override bool IsInstance { get { return !IsStatic; } } public override bool IsStatic { get { return best_candidate.IsStatic; } } public override string KindName { get { return "property"; } } public PropertySpec PropertyInfo { get { return best_candidate; } } #endregion public override MethodGroupExpr CanReduceLambda (AnonymousMethodBody body) { if (best_candidate == null || !(best_candidate.IsStatic || InstanceExpression is This)) return null; var args_count = arguments == null ? 0 : arguments.Count; if (args_count != body.Parameters.Count && args_count == 0) return null; var mg = MethodGroupExpr.CreatePredefined (best_candidate.Get, DeclaringType, loc); mg.InstanceExpression = InstanceExpression; return mg; } public static PropertyExpr CreatePredefined (PropertySpec spec, Location loc) { return new PropertyExpr (spec, loc) { Getter = spec.Get, Setter = spec.Set }; } public override Expression CreateExpressionTree (ResolveContext ec) { if (ConditionalAccess) { Error_NullShortCircuitInsideExpressionTree (ec); } Arguments args; if (IsSingleDimensionalArrayLength ()) { args = new Arguments (1); args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec))); return CreateExpressionFactoryCall (ec, "ArrayLength", args); } args = new Arguments (2); if (InstanceExpression == null) args.Add (new Argument (new NullLiteral (loc))); else args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec))); args.Add (new Argument (new TypeOfMethod (Getter, loc))); return CreateExpressionFactoryCall (ec, "Property", args); } public Expression CreateSetterTypeOfExpression (ResolveContext rc) { DoResolveLValue (rc, null); return new TypeOfMethod (Setter, loc); } public override string GetSignatureForError () { return best_candidate.GetSignatureForError (); } public override SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source) { #if STATIC return base.MakeExpression (ctx); #else return SLE.Expression.Property (InstanceExpression.MakeExpression (ctx), (MethodInfo) Setter.GetMetaInfo ()); #endif } public override SLE.Expression MakeExpression (BuilderContext ctx) { #if STATIC return base.MakeExpression (ctx); #else return SLE.Expression.Property (InstanceExpression.MakeExpression (ctx), (MethodInfo) Getter.GetMetaInfo ()); #endif } void Error_PropertyNotValid (ResolveContext ec) { ec.Report.SymbolRelatedToPreviousError (best_candidate); ec.Report.Error (1546, loc, "Property or event `{0}' is not supported by the C# language", GetSignatureForError ()); } bool IsSingleDimensionalArrayLength () { if (best_candidate.DeclaringType.BuiltinType != BuiltinTypeSpec.Type.Array || !best_candidate.HasGet || Name != "Length") return false; ArrayContainer ac = InstanceExpression.Type as ArrayContainer; return ac != null && ac.Rank == 1; } public override void Emit (EmitContext ec, bool leave_copy) { // // Special case: length of single dimension array property is turned into ldlen // if (IsSingleDimensionalArrayLength ()) { if (conditional_access_receiver) { ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ()); } EmitInstance (ec, false); ec.Emit (OpCodes.Ldlen); ec.Emit (OpCodes.Conv_I4); if (conditional_access_receiver) { ec.CloseConditionalAccess (type); } return; } base.Emit (ec, leave_copy); } public override void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound) { Arguments args; LocalTemporary await_source_arg = null; if (isCompound && !(source is DynamicExpressionStatement)) { emitting_compound_assignment = true; source.Emit (ec); if (has_await_arguments) { await_source_arg = new LocalTemporary (Type); await_source_arg.Store (ec); args = new Arguments (1); args.Add (new Argument (await_source_arg)); if (leave_copy) { temp = await_source_arg; } has_await_arguments = false; } else { args = null; if (leave_copy) { ec.Emit (OpCodes.Dup); temp = new LocalTemporary (this.Type); temp.Store (ec); } } } else { args = arguments ?? new Arguments (1); if (leave_copy) { source.Emit (ec); temp = new LocalTemporary (this.Type); temp.Store (ec); args.Add (new Argument (temp)); } else { args.Add (new Argument (source)); } } emitting_compound_assignment = false; var call = new CallEmitter (); call.InstanceExpression = InstanceExpression; if (args == null) call.InstanceExpressionOnStack = true; if (ConditionalAccess) { call.ConditionalAccess = true; } if (leave_copy) call.Emit (ec, Setter, args, loc); else call.EmitStatement (ec, Setter, args, loc); if (temp != null) { temp.Emit (ec); temp.Release (ec); } if (await_source_arg != null) { await_source_arg.Release (ec); } } public override void FlowAnalysis (FlowAnalysisContext fc) { base.FlowAnalysis (fc); if (conditional_access_receiver) fc.ConditionalAccessEnd (); } protected override Expression OverloadResolve (ResolveContext rc, Expression right_side) { eclass = ExprClass.PropertyAccess; if (best_candidate.IsNotCSharpCompatible) { Error_PropertyNotValid (rc); } ResolveInstanceExpression (rc, right_side); if ((best_candidate.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0 && best_candidate.DeclaringType != InstanceExpression.Type) { var filter = new MemberFilter (best_candidate.Name, 0, MemberKind.Property, null, null); var p = MemberCache.FindMember (InstanceExpression.Type, filter, BindingRestriction.InstanceOnly | BindingRestriction.OverrideOnly) as PropertySpec; if (p != null) { type = p.MemberType; } } DoBestMemberChecks (rc, best_candidate); // Handling of com-imported properties with any number of default property parameters if (best_candidate.HasGet && !best_candidate.Get.Parameters.IsEmpty) { var p = best_candidate.Get.Parameters; arguments = new Arguments (p.Count); for (int i = 0; i < p.Count; ++i) { arguments.Add (new Argument (OverloadResolver.ResolveDefaultValueArgument (rc, p.Types [i], p.FixedParameters [i].DefaultValue, loc))); } } else if (best_candidate.HasSet && best_candidate.Set.Parameters.Count > 1) { var p = best_candidate.Set.Parameters; arguments = new Arguments (p.Count - 1); for (int i = 0; i < p.Count - 1; ++i) { arguments.Add (new Argument (OverloadResolver.ResolveDefaultValueArgument (rc, p.Types [i], p.FixedParameters [i].DefaultValue, loc))); } } return this; } public override void SetTypeArguments (ResolveContext ec, TypeArguments ta) { Error_TypeArgumentsCannotBeUsed (ec, "property", GetSignatureForError (), loc); } } abstract class PropertyOrIndexerExpr<T> : MemberExpr, IDynamicAssign where T : PropertySpec { // getter and setter can be different for base calls MethodSpec getter, setter; protected T best_candidate; protected LocalTemporary temp; protected bool emitting_compound_assignment; protected bool has_await_arguments; protected PropertyOrIndexerExpr (Location l) { loc = l; } #region Properties protected abstract Arguments Arguments { get; set; } public MethodSpec Getter { get { return getter; } set { getter = value; } } public MethodSpec Setter { get { return setter; } set { setter = value; } } #endregion protected override Expression DoResolve (ResolveContext ec) { if (eclass == ExprClass.Unresolved) { ResolveConditionalAccessReceiver (ec); var expr = OverloadResolve (ec, null); if (expr == null) return null; if (expr != this) return expr.Resolve (ec); if (conditional_access_receiver) { type = LiftMemberType (ec, type); ec.With (ResolveContext.Options.ConditionalAccessReceiver, false); } } if (!ResolveGetter (ec)) return null; return this; } public override Expression DoResolveLValue (ResolveContext ec, Expression right_side) { if (ConditionalAccess) throw new NotSupportedException ("null propagating operator assignment"); if (right_side == EmptyExpression.OutAccess) { // TODO: best_candidate can be null at this point INamedBlockVariable variable = null; if (best_candidate != null && ec.CurrentBlock.ParametersBlock.TopBlock.GetLocalName (best_candidate.Name, ec.CurrentBlock, ref variable) && variable is Linq.RangeVariable) { ec.Report.Error (1939, loc, "A range variable `{0}' may not be passes as `ref' or `out' parameter", best_candidate.Name); } else { right_side.DoResolveLValue (ec, this); } return null; } if (eclass == ExprClass.Unresolved) { var expr = OverloadResolve (ec, right_side); if (expr == null) return null; if (expr != this) return expr.ResolveLValue (ec, right_side); } else { ResolveInstanceExpression (ec, right_side); } if (!ResolveSetter (ec)) return null; return this; } void EmitConditionalAccess (EmitContext ec, ref CallEmitter call, MethodSpec method, Arguments arguments) { ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ()); call.Emit (ec, method, arguments, loc); ec.CloseConditionalAccess (method.ReturnType != type && type.IsNullableType ? type : null); } // // Implements the IAssignMethod interface for assignments // public virtual void Emit (EmitContext ec, bool leave_copy) { var call = new CallEmitter (); call.ConditionalAccess = ConditionalAccess; call.InstanceExpression = InstanceExpression; if (has_await_arguments) call.HasAwaitArguments = true; else call.DuplicateArguments = emitting_compound_assignment; if (conditional_access_receiver) EmitConditionalAccess (ec, ref call, Getter, Arguments); else call.Emit (ec, Getter, Arguments, loc); if (call.HasAwaitArguments) { InstanceExpression = call.InstanceExpression; Arguments = call.EmittedArguments; has_await_arguments = true; } if (leave_copy) { ec.Emit (OpCodes.Dup); temp = new LocalTemporary (Type); temp.Store (ec); } } public abstract void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound); public override void Emit (EmitContext ec) { Emit (ec, false); } protected override FieldExpr EmitToFieldSource (EmitContext ec) { has_await_arguments = true; Emit (ec, false); return null; } public abstract SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source); protected abstract Expression OverloadResolve (ResolveContext rc, Expression right_side); bool ResolveGetter (ResolveContext rc) { if (!best_candidate.HasGet) { if (InstanceExpression != EmptyExpression.Null) { rc.Report.SymbolRelatedToPreviousError (best_candidate); rc.Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor", best_candidate.GetSignatureForError ()); return false; } } else if (!best_candidate.Get.IsAccessible (rc) || !best_candidate.Get.DeclaringType.IsAccessible (rc)) { if (best_candidate.HasDifferentAccessibility) { rc.Report.SymbolRelatedToPreviousError (best_candidate.Get); rc.Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible", TypeManager.CSharpSignature (best_candidate)); } else { rc.Report.SymbolRelatedToPreviousError (best_candidate.Get); ErrorIsInaccesible (rc, best_candidate.Get.GetSignatureForError (), loc); } } if (best_candidate.HasDifferentAccessibility) { CheckProtectedMemberAccess (rc, best_candidate.Get); } getter = CandidateToBaseOverride (rc, best_candidate.Get); return true; } bool ResolveSetter (ResolveContext rc) { if (!best_candidate.HasSet) { rc.Report.Error (200, loc, "Property or indexer `{0}' cannot be assigned to (it is read-only)", GetSignatureForError ()); return false; } if (!best_candidate.Set.IsAccessible (rc) || !best_candidate.Set.DeclaringType.IsAccessible (rc)) { if (best_candidate.HasDifferentAccessibility) { rc.Report.SymbolRelatedToPreviousError (best_candidate.Set); rc.Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible", GetSignatureForError ()); } else { rc.Report.SymbolRelatedToPreviousError (best_candidate.Set); ErrorIsInaccesible (rc, best_candidate.GetSignatureForError (), loc); } } if (best_candidate.HasDifferentAccessibility) CheckProtectedMemberAccess (rc, best_candidate.Set); setter = CandidateToBaseOverride (rc, best_candidate.Set); return true; } } /// <summary> /// Fully resolved expression that evaluates to an Event /// </summary> public class EventExpr : MemberExpr, IAssignMethod { readonly EventSpec spec; MethodSpec op; public EventExpr (EventSpec spec, Location loc) { this.spec = spec; this.loc = loc; } #region Properties protected override TypeSpec DeclaringType { get { return spec.DeclaringType; } } public override string Name { get { return spec.Name; } } public override bool IsInstance { get { return !spec.IsStatic; } } public override bool IsStatic { get { return spec.IsStatic; } } public override string KindName { get { return "event"; } } public MethodSpec Operator { get { return op; } } #endregion public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, SimpleName original) { // // If the event is local to this class and we are not lhs of +=/-= we transform ourselves into a FieldExpr // if (!ec.HasSet (ResolveContext.Options.CompoundAssignmentScope)) { if (spec.BackingField != null && (spec.DeclaringType == ec.CurrentType || TypeManager.IsNestedChildOf (ec.CurrentType, spec.DeclaringType.MemberDefinition))) { spec.MemberDefinition.SetIsUsed (); if (!ec.IsObsolete) { ObsoleteAttribute oa = spec.GetAttributeObsolete (); if (oa != null) AttributeTester.Report_ObsoleteMessage (oa, spec.GetSignatureForError (), loc, ec.Report); } if ((spec.Modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0) Error_AssignmentEventOnly (ec); FieldExpr ml = new FieldExpr (spec.BackingField, loc); InstanceExpression = null; return ml.ResolveMemberAccess (ec, left, original); } } return base.ResolveMemberAccess (ec, left, original); } public override Expression CreateExpressionTree (ResolveContext ec) { throw new NotSupportedException ("ET"); } public override Expression DoResolveLValue (ResolveContext ec, Expression right_side) { if (right_side == EmptyExpression.EventAddition) { op = spec.AccessorAdd; } else if (right_side == EmptyExpression.EventSubtraction) { op = spec.AccessorRemove; } if (op == null) { Error_AssignmentEventOnly (ec); return null; } op = CandidateToBaseOverride (ec, op); return this; } protected override Expression DoResolve (ResolveContext ec) { eclass = ExprClass.EventAccess; type = spec.MemberType; ResolveInstanceExpression (ec, null); if (!ec.HasSet (ResolveContext.Options.CompoundAssignmentScope)) { Error_AssignmentEventOnly (ec); } DoBestMemberChecks (ec, spec); return this; } public override void Emit (EmitContext ec) { throw new NotSupportedException (); //Error_CannotAssign (); } #region IAssignMethod Members public void Emit (EmitContext ec, bool leave_copy) { throw new NotImplementedException (); } public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound) { if (leave_copy || !isCompound) throw new NotImplementedException ("EventExpr::EmitAssign"); Arguments args = new Arguments (1); args.Add (new Argument (source)); // TODO: Wrong, needs receiver // if (NullShortCircuit) { // ec.ConditionalAccess = new ConditionalAccessContext (type, ec.DefineLabel ()); // } var call = new CallEmitter (); call.InstanceExpression = InstanceExpression; call.ConditionalAccess = ConditionalAccess; call.EmitStatement (ec, op, args, loc); // if (NullShortCircuit) // ec.CloseConditionalAccess (null); } #endregion void Error_AssignmentEventOnly (ResolveContext ec) { if (spec.DeclaringType == ec.CurrentType || TypeManager.IsNestedChildOf (ec.CurrentType, spec.DeclaringType.MemberDefinition)) { ec.Report.Error (79, loc, "The event `{0}' can only appear on the left hand side of `+=' or `-=' operator", GetSignatureForError ()); } else { ec.Report.Error (70, loc, "The event `{0}' can only appear on the left hand side of += or -= when used outside of the type `{1}'", GetSignatureForError (), spec.DeclaringType.GetSignatureForError ()); } } protected override void Error_CannotCallAbstractBase (ResolveContext rc, string name) { name = name.Substring (0, name.LastIndexOf ('.')); base.Error_CannotCallAbstractBase (rc, name); } public override string GetSignatureForError () { return TypeManager.CSharpSignature (spec); } public override void SetTypeArguments (ResolveContext ec, TypeArguments ta) { Error_TypeArgumentsCannotBeUsed (ec, "event", GetSignatureForError (), loc); } } public class TemporaryVariableReference : VariableReference { public class Declarator : Statement { TemporaryVariableReference variable; public Declarator (TemporaryVariableReference variable) { this.variable = variable; loc = variable.loc; } protected override void DoEmit (EmitContext ec) { variable.li.CreateBuilder (ec); } public override void Emit (EmitContext ec) { // Don't create sequence point DoEmit (ec); } protected override bool DoFlowAnalysis (FlowAnalysisContext fc) { return false; } protected override void CloneTo (CloneContext clonectx, Statement target) { // Nothing } } LocalVariable li; public TemporaryVariableReference (LocalVariable li, Location loc) { this.li = li; this.type = li.Type; this.loc = loc; } public override bool IsLockedByStatement { get { return false; } set { } } public LocalVariable LocalInfo { get { return li; } } public static TemporaryVariableReference Create (TypeSpec type, Block block, Location loc) { var li = LocalVariable.CreateCompilerGenerated (type, block, loc); return new TemporaryVariableReference (li, loc); } protected override Expression DoResolve (ResolveContext ec) { eclass = ExprClass.Variable; // // Don't capture temporary variables except when using // state machine redirection and block yields // if (ec.CurrentAnonymousMethod is StateMachineInitializer && (ec.CurrentBlock.Explicit.HasYield || ec.CurrentBlock.Explicit.HasAwait) && ec.IsVariableCapturingRequired) { AnonymousMethodStorey storey = li.Block.Explicit.CreateAnonymousMethodStorey (ec); storey.CaptureLocalVariable (ec, li); } return this; } public override Expression DoResolveLValue (ResolveContext ec, Expression right_side) { return Resolve (ec); } public override void Emit (EmitContext ec) { li.CreateBuilder (ec); Emit (ec, false); } public void EmitAssign (EmitContext ec, Expression source) { li.CreateBuilder (ec); EmitAssign (ec, source, false, false); } public override HoistedVariable GetHoistedVariable (AnonymousExpression ae) { return li.HoistedVariant; } public override bool IsFixed { get { return true; } } public override bool IsRef { get { return false; } } public override string Name { get { throw new NotImplementedException (); } } public override void SetHasAddressTaken () { throw new NotImplementedException (); } protected override ILocalVariable Variable { get { return li; } } public override VariableInfo VariableInfo { get { return null; } } } /// /// Handles `var' contextual keyword; var becomes a keyword only /// if no type called var exists in a variable scope /// class VarExpr : SimpleName { public VarExpr (Location loc) : base ("var", loc) { } public bool InferType (ResolveContext ec, Expression right_side) { if (type != null) throw new InternalErrorException ("An implicitly typed local variable could not be redefined"); type = right_side.Type; if (type == InternalType.NullLiteral || type.Kind == MemberKind.Void || type == InternalType.AnonymousMethod || type == InternalType.MethodGroup) { ec.Report.Error (815, loc, "An implicitly typed local variable declaration cannot be initialized with `{0}'", type.GetSignatureForError ()); return false; } eclass = ExprClass.Variable; return true; } protected override void Error_TypeOrNamespaceNotFound (IMemberContext ec) { if (ec.Module.Compiler.Settings.Version < LanguageVersion.V_3) base.Error_TypeOrNamespaceNotFound (ec); else ec.Module.Compiler.Report.Error (825, loc, "The contextual keyword `var' may only appear within a local variable declaration"); } } }
29.05478
224
0.677371
[ "Apache-2.0" ]
RiJo/mono
mcs/mcs/ecore.cs
216,400
C#
#if !NETSTANDARD13 /* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the transcribe-2017-10-26.normal.json service model. */ using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.Threading; using System.Threading.Tasks; using Amazon.Runtime; namespace Amazon.TranscribeService.Model { /// <summary> /// Base class for ListMedicalTranscriptionJobs paginators. /// </summary> internal sealed partial class ListMedicalTranscriptionJobsPaginator : IPaginator<ListMedicalTranscriptionJobsResponse>, IListMedicalTranscriptionJobsPaginator { private readonly IAmazonTranscribeService _client; private readonly ListMedicalTranscriptionJobsRequest _request; private int _isPaginatorInUse = 0; /// <summary> /// Enumerable containing all full responses for the operation /// </summary> public IPaginatedEnumerable<ListMedicalTranscriptionJobsResponse> Responses => new PaginatedResponse<ListMedicalTranscriptionJobsResponse>(this); internal ListMedicalTranscriptionJobsPaginator(IAmazonTranscribeService client, ListMedicalTranscriptionJobsRequest request) { this._client = client; this._request = request; } #if BCL IEnumerable<ListMedicalTranscriptionJobsResponse> IPaginator<ListMedicalTranscriptionJobsResponse>.Paginate() { if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0) { throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance."); } var nextToken = _request.NextToken; ListMedicalTranscriptionJobsResponse response; do { _request.NextToken = nextToken; response = _client.ListMedicalTranscriptionJobs(_request); nextToken = response.NextToken; yield return response; } while (nextToken != null); } #endif #if AWS_ASYNC_ENUMERABLES_API async IAsyncEnumerable<ListMedicalTranscriptionJobsResponse> IPaginator<ListMedicalTranscriptionJobsResponse>.PaginateAsync(CancellationToken cancellationToken = default) { if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0) { throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance."); } var nextToken = _request.NextToken; ListMedicalTranscriptionJobsResponse response; do { _request.NextToken = nextToken; response = await _client.ListMedicalTranscriptionJobsAsync(_request, cancellationToken).ConfigureAwait(false); nextToken = response.NextToken; cancellationToken.ThrowIfCancellationRequested(); yield return response; } while (nextToken != null); } #endif } } #endif
40.681319
178
0.683955
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/TranscribeService/Generated/Model/_bcl45+netstandard/ListMedicalTranscriptionJobsPaginator.cs
3,702
C#
using System; using System.IO; namespace demojson { public static class FileReader { public static string ReadTextFromDataFile(string fullPathToFile) { using (var fi = File.OpenText(fullPathToFile)) { return fi.ReadToEnd(); } } public static void WriteTextToDataFile(string fullPathToFile, string text) { File.WriteAllText(fullPathToFile, text); } } }
23.1
84
0.601732
[ "MIT" ]
kritsadadechawantana/code-basic
src/demojson/FileReader.cs
462
C#
namespace Primeiro_Projeto_Winforms { partial class FrmPrincipal { /// <summary> /// Variável de designer necessária. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Limpar os recursos que estão sendo usados. /// </summary> /// <param name="disposing">true se for necessário descartar os recursos gerenciados; caso contrário, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Código gerado pelo Windows Form Designer /// <summary> /// Método necessário para suporte ao Designer - não modifique /// o conteúdo deste método com o editor de código. /// </summary> private void InitializeComponent() { this.lbNome = new System.Windows.Forms.Label(); this.txtNome = new System.Windows.Forms.TextBox(); this.btConfirma = new System.Windows.Forms.Button(); this.btLimpar = new System.Windows.Forms.Button(); this.lbResultado = new System.Windows.Forms.Label(); this.SuspendLayout(); // // lbNome // this.lbNome.AutoSize = true; this.lbNome.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lbNome.Location = new System.Drawing.Point(12, 79); this.lbNome.Name = "lbNome"; this.lbNome.Size = new System.Drawing.Size(281, 36); this.lbNome.TabIndex = 0; this.lbNome.Text = "Informe seu nome:"; // // txtNome // this.txtNome.Location = new System.Drawing.Point(299, 84); this.txtNome.Name = "txtNome"; this.txtNome.Size = new System.Drawing.Size(366, 31); this.txtNome.TabIndex = 1; // // btConfirma // this.btConfirma.Location = new System.Drawing.Point(18, 150); this.btConfirma.Name = "btConfirma"; this.btConfirma.Size = new System.Drawing.Size(647, 56); this.btConfirma.TabIndex = 2; this.btConfirma.Text = "Confirmar"; this.btConfirma.UseVisualStyleBackColor = true; this.btConfirma.Click += new System.EventHandler(this.btConfirma_Click); // // btLimpar // this.btLimpar.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.btLimpar.Location = new System.Drawing.Point(18, 334); this.btLimpar.Name = "btLimpar"; this.btLimpar.Size = new System.Drawing.Size(649, 41); this.btLimpar.TabIndex = 3; this.btLimpar.Text = "Limpar"; this.btLimpar.UseVisualStyleBackColor = false; this.btLimpar.Click += new System.EventHandler(this.btLimpar_Click); // // lbResultado // this.lbResultado.AutoSize = true; this.lbResultado.Location = new System.Drawing.Point(13, 232); this.lbResultado.Name = "lbResultado"; this.lbResultado.Size = new System.Drawing.Size(47, 25); this.lbResultado.TabIndex = 4; this.lbResultado.Text = "-----"; // // FrmPrincipal // this.AutoScaleDimensions = new System.Drawing.SizeF(12F, 25F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(714, 410); this.Controls.Add(this.lbResultado); this.Controls.Add(this.btLimpar); this.Controls.Add(this.btConfirma); this.Controls.Add(this.txtNome); this.Controls.Add(this.lbNome); this.Name = "FrmPrincipal"; this.Text = "Meu Primeiro Form"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label lbNome; private System.Windows.Forms.TextBox txtNome; private System.Windows.Forms.Button btConfirma; private System.Windows.Forms.Button btLimpar; private System.Windows.Forms.Label lbResultado; } }
41.767857
152
0.553655
[ "MIT" ]
traue/2022-1-quarta_manha
Primeiro Projeto Winforms/Primeiro Projeto Winforms/FrmPrincipal.Designer.cs
4,692
C#
namespace FreeRiders.Models { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using FreeRiders.Data.Common.Models; public class Album : DeletableEntity { private ICollection<Review> reviews; private ICollection<Picture> pictures; public Album() { this.reviews = new HashSet<Review>(); this.pictures = new HashSet<Picture>(); } [Key] public int ID { get; set; } [Required] [StringLength(150, MinimumLength = 3)] public string Title { get; set; } [Required] [StringLength(10000, MinimumLength = 10)] public string Description { get; set; } [Range(0, 10)] public double Rating { get; set; } [Required] public int LocationID { get; set; } public virtual Location Location { get; set; } [Required] public string CreatorID { get; set; } public virtual User Creator { get; set; } [Required] public int CategoryID { get; set; } public virtual AlbumCategory Category { get; set; } public int PictureID { get; set; } public virtual Picture Picture { get; set; } public virtual ICollection<Review> Reviews { get { return this.reviews; } set { this.reviews = value; } } public virtual ICollection<Picture> Pictures { get { return this.pictures; } set { this.pictures = value; } } } }
24.2
59
0.563891
[ "MIT" ]
yasenm/Freeriders
FreeRiders.Models/Album.cs
1,575
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\IMethodRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The interface IWorkbookTableDataBodyRangeRequestBuilder. /// </summary> public partial interface IWorkbookTableDataBodyRangeRequestBuilder { /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> IWorkbookTableDataBodyRangeRequest Request(IEnumerable<Option> options = null); } }
37.758621
153
0.591781
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/IWorkbookTableDataBodyRangeRequestBuilder.cs
1,095
C#
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System.Threading.Tasks; using Elastic.Xunit.XunitPlumbing; using Nest; using Tests.Framework.EndpointTests; using static Tests.Framework.EndpointTests.UrlTester; namespace Tests.XPack.MachineLearning.PutJob { public class PutJobUrlTests : UrlTestsBase { [U] public override async Task Urls() => await PUT("/_ml/anomaly_detectors/job_id") .Fluent(c => c.MachineLearning.PutJob<object>("job_id", p => p)) .Request(c => c.MachineLearning.PutJob(new PutJobRequest("job_id"))) .FluentAsync(c => c.MachineLearning.PutJobAsync<object>("job_id", p => p)) .RequestAsync(c => c.MachineLearning.PutJobAsync(new PutJobRequest("job_id"))); } }
39.181818
85
0.75522
[ "Apache-2.0" ]
magaum/elasticsearch-net
tests/Tests/XPack/MachineLearning/PutJob/PutJobUrlTests.cs
864
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using SpecialPlugin.AspNetCore; using SpecialPlugin.Project.NewDapperDemo.Dtos; using SpecialPlugin.Project.NewDapperDemo.Models; using System; using System.IO; namespace SpecialPlugin.Project.NewDapperDemo { [DependsOn(typeof(JobModule))] public class Module : PluginModule { public override void ConfigureServices(ServiceConfigurationContext context) { var services = context.Services; var configuration = services.GetConfiguration(); services.Configure<NewDapperDemoOptions>(configuration.GetSection("NewDapperDemoOptions")); services.AddScoped<IJobService, JobService>(); services.AddAutoMapper(cfg => { cfg.CreateMap<BookTag, BookTagDto>(); }); } public override void OnApplicationInitialization(ApplicationInitializationContext context) { var app = context.GetApplicationBuilder(); string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UnitPackages", GetType().Namespace, $"wwwroot"); app.UseFileServer(new FileServerOptions() { FileProvider = new PhysicalFileProvider(path), //实际目录地址 RequestPath = new PathString($"/Resource1"), EnableDirectoryBrowsing = true //开启目录浏览 }); using (var scope = app.ApplicationServices.CreateScope()) { scope.ServiceProvider.GetRequiredService<IJobService>().Execute(null).GetAwaiter().GetResult(); } } } }
33.692308
127
0.66153
[ "MIT" ]
xybii/SpecialPlugin
test/net5.0/SpecialPlugin.Project.NewDapperDemo/Module.cs
1,778
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BookSpade.Revamped.Models { public class Textbook { public int TextBookId { get; set; } public string BookTitle { get; set; } public string ISBN { get; set; } public string Author { get; set; } public int CourseId { get; set; } public string CourseName { get; set; } public string BookImageUrl { get; set; } public decimal? StorePrice { get; set; } public int IsActive { get; set; } public int IsDeleted { get; set; } public DateTime CreatedDate { get; set; } public DateTime ModifiedDate { get; set; } public Textbook( int textbookId, string bookTitle, string isbn, string author, int courseId, string courseName, string bookImageUrl, decimal? storePrice, int isActive, int isDeleted, DateTime createdDate, DateTime modifiedDate ) { TextBookId = textbookId; BookTitle = bookTitle; ISBN = isbn; Author = author; CourseId = courseId; CourseName = courseName; BookImageUrl = bookImageUrl; StorePrice = storePrice; IsActive = isActive; IsDeleted = isDeleted; CreatedDate = createdDate; ModifiedDate = modifiedDate; } } }
30.75
51
0.52783
[ "MIT" ]
hw3jung/Chanel
BookSpade/BookSpade.Revamped/Models/Textbook.cs
1,601
C#
namespace FakeItEasy.IntegrationTests { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Net; using FakeItEasy.SelfInitializedFakes; using NUnit.Framework; [TestFixture] public class RecordingManagerTests { [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "No exception is thrown.")] [Test] [Explicit] public void Second_pass_should_use_recorded_values_from_previous_pass() { var storage = new Storage(); using (var recorder = new RecordingManager(storage)) { var memoryStream = new MemoryStream(); using (var stream = A.Fake<Stream>(x => x.Wrapping(memoryStream).RecordedBy(recorder))) using (var writer = new StreamWriter(stream)) { writer.Write("Hello world!"); } Assert.That(memoryStream.GetBuffer().Length, Is.Not.LessThanOrEqualTo(0)); } using (var recorder = new RecordingManager(storage)) { var memoryStream = new MemoryStream(); using (var stream = A.Fake<Stream>(x => x.Wrapping(memoryStream).RecordedBy(recorder))) using (var writer = new StreamWriter(stream)) { writer.Write("Hello world!"); } Assert.That(memoryStream.Length, Is.EqualTo(0)); } foreach (var call in storage.RecordedCalls) { Console.WriteLine(call.Method.ToString() + " returns: " + call.ReturnValue); } } [Test, Explicit] public void FileRecorder_tests() { using (var recorder = Recorders.FileRecorder(@"C:\Users\Patrik\Documents\recorded_calls.dat")) { var realReader = new WebReader(); var fakeReader = A.Fake<WebReader>(x => x.Wrapping(realReader).RecordedBy(recorder)); for (int i = 0; i < 30; i++) { fakeReader.Download(new Uri("http://www.sembo.se/")); } Console.WriteLine(fakeReader.Download(new Uri("http://www.sembo.se/"))); } } public class WebReader { [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "No exception is thrown.")] public virtual string Download(Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } Console.WriteLine("Downloading " + uri.AbsoluteUri); using (var stream = new WebClient().OpenRead(uri)) using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } private class Storage : ICallStorage { public List<CallData> RecordedCalls { get; set; } public IEnumerable<CallData> Load() { return this.RecordedCalls; } public void Save(IEnumerable<CallData> calls) { this.RecordedCalls = calls.ToList(); } } } }
34.009434
140
0.511512
[ "MIT" ]
bondsbw/FakeItEasy
Source/FakeItEasy.IntegrationTests/RecordingManagerTests.cs
3,605
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Spine.Unity.Examples { public class SpawnFromSkeletonDataExample : MonoBehaviour { public SkeletonDataAsset skeletonDataAsset; [Range(0, 100)] public int count = 20; [SpineAnimation(dataField:"skeletonDataAsset")] public string startingAnimation; IEnumerator Start () { if (skeletonDataAsset == null) yield break; skeletonDataAsset.GetSkeletonData(false); // Preload SkeletonDataAsset. yield return new WaitForSeconds(1f); // Pretend stuff is happening. var spineAnimation = skeletonDataAsset.GetSkeletonData(false).FindAnimation(startingAnimation); for (int i = 0; i < count; i++) { var sa = SkeletonAnimation.NewSkeletonAnimationGameObject(skeletonDataAsset); // Spawn a new SkeletonAnimation GameObject. DoExtraStuff(sa, spineAnimation); // optional stuff for fun. sa.gameObject.name = i.ToString(); yield return new WaitForSeconds(1f/8f); } } void DoExtraStuff (SkeletonAnimation sa, Spine.Animation spineAnimation) { sa.transform.localPosition = Random.insideUnitCircle * 6f; sa.transform.SetParent(this.transform, false); if (spineAnimation != null) { sa.Initialize(false); sa.AnimationState.SetAnimation(0, spineAnimation, true); } } } }
30.674419
126
0.74602
[ "Apache-2.0" ]
Code-Ponys/MixedUpTales-0.2.0
Assets/Resources/Animations/spine-unity/Assets/Examples/Scripts/SpawnFromSkeletonDataExample.cs
1,321
C#
using Godot; using System; using MakeFs; public class MainUi : MainUiFs { }
11.142857
34
0.730769
[ "Unlicense" ]
sgillespie/knight-maker
scripts/MainUi.cs
78
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Sql.V20190601Preview.Outputs { /// <summary> /// Properties of a private endpoint connection. /// </summary> [OutputType] public sealed class PrivateEndpointConnectionPropertiesResponse { /// <summary> /// Private endpoint which the connection belongs to. /// </summary> public readonly Outputs.PrivateEndpointPropertyResponse? PrivateEndpoint; /// <summary> /// Connection state of the private endpoint connection. /// </summary> public readonly Outputs.PrivateLinkServiceConnectionStatePropertyResponse? PrivateLinkServiceConnectionState; /// <summary> /// State of the private endpoint connection. /// </summary> public readonly string ProvisioningState; [OutputConstructor] private PrivateEndpointConnectionPropertiesResponse( Outputs.PrivateEndpointPropertyResponse? privateEndpoint, Outputs.PrivateLinkServiceConnectionStatePropertyResponse? privateLinkServiceConnectionState, string provisioningState) { PrivateEndpoint = privateEndpoint; PrivateLinkServiceConnectionState = privateLinkServiceConnectionState; ProvisioningState = provisioningState; } } }
35.26087
117
0.697904
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Sql/V20190601Preview/Outputs/PrivateEndpointConnectionPropertiesResponse.cs
1,622
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace DeBroglie.Wfc { /** * Wave is a fancy array that tracks various per-cell information. * Most importantly, it tracks possibilities - which patterns are possible to put * into which cells. * It has no notion of cell adjacency, cells are just referred to by integer index. */ internal class Wave { public static int AllCellsDecided = -1; private readonly int patternCount; private readonly double[] frequencies; // possibilities[index*patternCount + pattern] is true if we haven't eliminated putting // that pattern at that index. private readonly BitArray possibilities; // Track some useful per-cell values private readonly EntropyValues[] entropyValues; // See the definition in EntropyValues private readonly double[] plogp; private readonly bool[] mask; private readonly int indices; private Wave(int patternCount, double[] frequencies, BitArray possibilites, EntropyValues[] entropyValues, double[] plogp, int indices, bool[] mask) { this.patternCount = patternCount; this.frequencies = frequencies; this.possibilities = possibilites; this.entropyValues = entropyValues; this.plogp = plogp; this.indices = indices; } public Wave(double[] frequencies, int indices, bool[] mask) { this.patternCount = frequencies.Length; this.frequencies = frequencies; this.indices = indices; this.mask = mask; // Initialize possibilities possibilities = new BitArray(indices * patternCount, true); // Initialize plogp and entropyValues plogp = new double[patternCount]; EntropyValues initial; initial.PlogpSum = 0; initial.Sum = 0; initial.PatternCount = 0; initial.Entropy = 0; for (int pattern = 0; pattern < patternCount; pattern++) { var f = frequencies[pattern]; var v = f > 0 ? f * Math.Log(f) : 0.0; plogp[pattern] = v; initial.PlogpSum += v; initial.Sum += f; initial.PatternCount += 1; } initial.RecomputeEntropy(); entropyValues = new EntropyValues[indices]; for (int index = 0; index < indices; index++) { entropyValues[index] = initial; } } public Wave Clone() { return new Wave( patternCount, frequencies, (BitArray)possibilities.Clone(), (EntropyValues[])entropyValues.Clone(), plogp, indices, mask); } public bool Get(int index, int pattern) { return possibilities[index * patternCount + pattern]; } // Returns true if there is a contradiction public bool RemovePossibility(int index, int pattern) { Debug.Assert(possibilities[index * patternCount + pattern] == true); possibilities[index * patternCount + pattern] = false; int c = entropyValues[index].Decrement(frequencies[pattern], plogp[pattern]); return c == 0; } public void AddPossibility(int index, int pattern) { Debug.Assert(possibilities[index * patternCount + pattern] == false); possibilities[index * patternCount + pattern] = true; entropyValues[index].Increment(frequencies[pattern], plogp[pattern]); } // Finds the cells with minimal entropy (excluding 0, decided cells) // and picks one randomly. // Returns AllCellsDecided if every cell is decided. public int GetRandomMinEntropyIndex(Random r) { int selectedIndex = AllCellsDecided; double minEntropy = double.PositiveInfinity; double randomizer = 0; for (int i = 0; i < indices; i++) { if (mask != null && !mask[i]) continue; var c = entropyValues[i].PatternCount; var e = entropyValues[i].Entropy; if (c <= 1) { continue; } else if (e < minEntropy) { selectedIndex = i; minEntropy = e; randomizer = r.NextDouble(); } else if (e == minEntropy) { var randomizer2 = r.NextDouble(); if (randomizer2 < randomizer) { selectedIndex = i; minEntropy = e; randomizer = randomizer2; } } } return selectedIndex; } public double GetProgress() { var c = 0; foreach(bool b in possibilities) { if (!b) c += 1; } // We're basically done when we've banned all but one pattern for each index return ((double)c) / (patternCount-1) / indices; } /** * Struct containing the values needed to compute the entropy of all the cells. * This struct is updated every time the cell is changed. * p'(pattern) is equal to Frequencies[pattern] if the pattern is still possible, otherwise 0. */ private struct EntropyValues { public double PlogpSum; // The sum of p'(pattern) * log(p'(pattern)). public double Sum; // The sum of p'(pattern). public int PatternCount; // The number of patterns present in the wave in the cell. public double Entropy; // The entropy of the cell. public void RecomputeEntropy() { Entropy = Math.Log(Sum) - PlogpSum / Sum; } public int Decrement(double p, double plogp) { PlogpSum -= plogp; Sum -= p; PatternCount--; RecomputeEntropy(); return PatternCount; } public void Increment(double p, double plogp) { PlogpSum += plogp; Sum += p; PatternCount++; RecomputeEntropy(); } } } }
33.086957
103
0.51336
[ "MIT" ]
colrich/DeBroglie
DeBroglie/Wfc/Wave.cs
6,851
C#
using Xunit; using System; public class ProteinTranslationTests { [Fact] public void Methionine_rna_sequence() { Assert.Equal(new[] { "Methionine" }, ProteinTranslation.Proteins("AUG")); } [Fact()] public void Phenylalanine_rna_sequence_1() { Assert.Equal(new[] { "Phenylalanine" }, ProteinTranslation.Proteins("UUU")); } [Fact()] public void Phenylalanine_rna_sequence_2() { Assert.Equal(new[] { "Phenylalanine" }, ProteinTranslation.Proteins("UUC")); } [Fact()] public void Leucine_rna_sequence_1() { Assert.Equal(new[] { "Leucine" }, ProteinTranslation.Proteins("UUA")); } [Fact()] public void Leucine_rna_sequence_2() { Assert.Equal(new[] { "Leucine" }, ProteinTranslation.Proteins("UUG")); } [Fact()] public void Serine_rna_sequence_1() { Assert.Equal(new[] { "Serine" }, ProteinTranslation.Proteins("UCU")); } [Fact()] public void Serine_rna_sequence_2() { Assert.Equal(new[] { "Serine" }, ProteinTranslation.Proteins("UCC")); } [Fact()] public void Serine_rna_sequence_3() { Assert.Equal(new[] { "Serine" }, ProteinTranslation.Proteins("UCA")); } [Fact()] public void Serine_rna_sequence_4() { Assert.Equal(new[] { "Serine" }, ProteinTranslation.Proteins("UCG")); } [Fact()] public void Tyrosine_rna_sequence_1() { Assert.Equal(new[] { "Tyrosine" }, ProteinTranslation.Proteins("UAU")); } [Fact()] public void Tyrosine_rna_sequence_2() { Assert.Equal(new[] { "Tyrosine" }, ProteinTranslation.Proteins("UAC")); } [Fact()] public void Cysteine_rna_sequence_1() { Assert.Equal(new[] { "Cysteine" }, ProteinTranslation.Proteins("UGU")); } [Fact()] public void Cysteine_rna_sequence_2() { Assert.Equal(new[] { "Cysteine" }, ProteinTranslation.Proteins("UGC")); } [Fact()] public void Tryptophan_rna_sequence() { Assert.Equal(new[] { "Tryptophan" }, ProteinTranslation.Proteins("UGG")); } [Fact()] public void Stop_codon_rna_sequence_1() { Assert.Empty(ProteinTranslation.Proteins("UAA")); } [Fact()] public void Stop_codon_rna_sequence_2() { Assert.Empty(ProteinTranslation.Proteins("UAG")); } [Fact()] public void Stop_codon_rna_sequence_3() { Assert.Empty(ProteinTranslation.Proteins("UGA")); } [Fact()] public void Translate_rna_strand_into_correct_protein_list() { Assert.Equal(new[] { "Methionine", "Phenylalanine", "Tryptophan" }, ProteinTranslation.Proteins("AUGUUUUGG")); } [Fact()] public void Translation_stops_if_stop_codon_at_beginning_of_sequence() { Assert.Empty(ProteinTranslation.Proteins("UAGUGG")); } [Fact()] public void Translation_stops_if_stop_codon_at_end_of_two_codon_sequence() { Assert.Equal(new[] { "Tryptophan" }, ProteinTranslation.Proteins("UGGUAG")); } [Fact()] public void Translation_stops_if_stop_codon_at_end_of_three_codon_sequence() { Assert.Equal(new[] { "Methionine", "Phenylalanine" }, ProteinTranslation.Proteins("AUGUUUUAA")); } [Fact()] public void Translation_stops_if_stop_codon_in_middle_of_three_codon_sequence() { Assert.Equal(new[] { "Tryptophan" }, ProteinTranslation.Proteins("UGGUAGUGG")); } [Fact()] public void Translation_stops_if_stop_codon_in_middle_of_six_codon_sequence() { Assert.Equal(new[] { "Tryptophan", "Cysteine", "Tyrosine" }, ProteinTranslation.Proteins("UGGUGUUAUUAAUGGUUU")); } [Fact()] public void Wrong_sequence() { Assert.Throws<ArgumentException>(() => ProteinTranslation.Proteins("UGUU")); } }
25.973154
120
0.6323
[ "MIT" ]
tamireinhorn/Exercism
csharp/protein-translation/ProteinTranslationTests.cs
3,870
C#
using UnityEditor; using UnityEditorInternal; using UnityEngine; namespace WraithavenGames.Bones3.Editor { // TODO Refactor this class public class TextureArrayGenerator : EditorWindow { [MenuItem("Assets/Create/Texture Array from Textures")] protected static void Init() { TextureArrayGenerator window = GetWindow<TextureArrayGenerator>(); window.Show(); } private TextureArrayGeneratorPropertyHolder tempObject; private SerializedProperty textures; private SerializedProperty linearColorSpace; private ReorderableList textureList; private Material texturePreview; private ObjectPicker objectPicker; protected void OnEnable() { tempObject = CreateInstance<TextureArrayGeneratorPropertyHolder>(); SerializedObject propertyHolder = new SerializedObject(tempObject); textures = propertyHolder.FindProperty("textures"); linearColorSpace = propertyHolder.FindProperty("linearColorSpace"); textureList = new ReorderableList(propertyHolder, textures, true, true, true, true) { elementHeight = 68, }; textureList.drawHeaderCallback += DrawTexturesHeader; textureList.onRemoveCallback += RemoveTexture; textureList.onAddCallback += AddTexture; textureList.drawElementCallback += DrawTextures; texturePreview = new Material(Shader.Find("Hidden/Bones3/Texture Preview")); objectPicker = new ObjectPicker(); } protected void OnDisable() { DestroyImmediate(tempObject); } void DrawTexturesHeader(Rect rect) => EditorGUI.LabelField(rect, "Texture List", GUI.skin.GetStyle("BoldLabel")); void AddTexture(ReorderableList list) => objectPicker.ShowPickerWindow<Texture2D>("textures", null, false); void RemoveTexture(ReorderableList list) { if (textures.GetArrayElementAtIndex(list.index).objectReferenceValue != null) textures.DeleteArrayElementAtIndex(list.index); textures.DeleteArrayElementAtIndex(list.index); } void DrawTextures(Rect rect, int index, bool active, bool focused) { var tex = (Texture2D)textures.GetArrayElementAtIndex(index).objectReferenceValue; var r = new Rect(rect.x, rect.y + 2, 64, 64); EditorGUI.DrawPreviewTexture(r, tex, texturePreview); } protected void OnGUI() { var newTexture = objectPicker.PickerObject("textures"); if (newTexture != null) { int index = textures.arraySize; textures.InsertArrayElementAtIndex(index); textures.GetArrayElementAtIndex(index).objectReferenceValue = newTexture; } EditorGUILayout.Space(); ValidateTextureList(); textureList.DoLayoutList(); bool warnings = ShowWarnings(); if (!warnings) { EditorGUILayout.Space(); if (GUILayout.Button("Build Array")) { BuildTexture(); Close(); } } } void BuildTexture() { string path = "Assets"; foreach (Object obj in Selection.GetFiltered(typeof(Object), SelectionMode.Assets)) { path = AssetDatabase.GetAssetPath(obj); if (!string.IsNullOrEmpty(path) && System.IO.File.Exists(path)) { path = System.IO.Path.GetDirectoryName(path); break; } } var firstTex = textures.GetArrayElementAtIndex(0).objectReferenceValue as Texture2D; int width = firstTex.width; int height = firstTex.height; int depth = textures.arraySize; TextureFormat format = TextureFormat.RGBA32; FilterMode filter = firstTex.filterMode; int mipmapCount = firstTex.mipmapCount; bool linearColor = linearColorSpace.boolValue; var texture = new Texture2DArray(width, height, depth, format, mipmapCount, linearColor) { name = "Texture Array", filterMode = filter, anisoLevel = firstTex.anisoLevel, }; AssetDatabase.CreateAsset(texture, path + "/Voxel Texture Atlas.asset"); AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(texture)); for (int i = 0; i < textures.arraySize; i++) { var src = textures.GetArrayElementAtIndex(i).objectReferenceValue as Texture2D; CopyData(src, texture, i); } texture.Apply(); } void CopyData(Texture2D src, Texture2DArray dst, int index) { for (int m = 0; m < src.mipmapCount; m++) { var pixels = src.GetPixels32(m); dst.SetPixels32(pixels, index, m); } } bool ShowWarnings() { if (textures.arraySize == 0) { EditorGUILayout.Space(); EditorGUILayout.HelpBox("Texture list cannot be empty!", MessageType.Warning); return true; } if (!CheckMatching(out string warning)) { EditorGUILayout.Space(); EditorGUILayout.HelpBox(warning, MessageType.Warning); return true; } return false; } bool CheckMatching(out string warning) { warning = ""; Texture2D first = textures.GetArrayElementAtIndex(0).objectReferenceValue as Texture2D; for (int i = 1; i < textures.arraySize; i++) { var next = textures.GetArrayElementAtIndex(i).objectReferenceValue as Texture2D; if (!CheckMatching(first, next, ref warning)) return false; } return true; } private bool IsCompressed(TextureFormat format) { switch (format) { case TextureFormat.RGBA32: case TextureFormat.RGB24: case TextureFormat.RG16: case TextureFormat.R8: return true; default: return false; } } bool CheckMatching(Texture2D a, Texture2D b, ref string warning) { if (a.width != b.width || a.height != b.height) { warning = "Textures must all be the same size!"; return false; } if (!IsCompressed(a.format) || !IsCompressed(b.format)) { warning = "Textures must uncompressed!!"; return false; } if (a.filterMode != b.filterMode) { warning = "Textures must all use the same filter mode!"; return false; } if (a.mipmapCount != b.mipmapCount) { warning = "Textures must all have the same mipmap count!"; return false; } if (a.anisoLevel != b.anisoLevel) { warning = "Textures must all use the same anisotropic level!"; return false; } return true; } void ValidateTextureList() { for (int i = 0; i < textures.arraySize; i++) { if (textures.GetArrayElementAtIndex(i).objectReferenceValue == null) { textureList.index = i; RemoveTexture(textureList); } } } #pragma warning disable 649 internal class TextureArrayGeneratorPropertyHolder : ScriptableObject { [SerializeField] protected Texture2D[] m_Textures; [SerializeField] protected bool m_LinearColorSpace; } } }
32.20155
100
0.543693
[ "MIT" ]
MartinRood/Bones3
Assets/Wraithaven Games/Bones3 Rebuilt/Editor/Scripts/Texturing/TextureArrayGenerator.cs
8,308
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Projeto.Presentation.Mvc.Models; using Projeto.Repository.Entities; using Projeto.Repository.Repositories; namespace Projeto.Presentation.Mvc.Controllers { public class DependenteController : Controller { //Abrir a página public IActionResult Cadastro([FromServices] ClienteRepository clienteRepository) { var result = GetDependenteCadastroModel(clienteRepository); return View(result); } [HttpPost] public IActionResult Cadastro(DependenteCadastroModel model, [FromServices] DependenteRepository dependenteRepository, [FromServices] ClienteRepository clienteRepository) { if (ModelState.IsValid) { try { var dependente = new Dependente(); dependente.Nome = model.Nome; dependente.DataNascimento = DateTime.Parse(model.DataNascimento); dependente.IdCliente = Convert.ToInt32(model.IdCliente); dependenteRepository.Create(dependente); TempData["MensagemSucesso"] = "Dependente cadastrado com sucesso."; ModelState.Clear(); //limpar os campos do formulário } catch (Exception e) { TempData["MensagemErro"] = "Erro: " + e.Message; } } var result = GetDependenteCadastroModel(clienteRepository); return View(result); } //método de ação para consultar dependente public IActionResult Consulta([FromServices] DependenteRepository dependenteRepository) { var dependentes = new List<Dependente>(); try { dependentes = dependenteRepository.GetAll(); } catch (Exception e) { TempData["MensagemErro"] = "Erro: " + e.Message; } return View(dependentes); } //método de ação para excluir dependente public IActionResult Exclusao(int id, [FromServices] DependenteRepository dependenteRepository) { try { var dependente = dependenteRepository.GetById(id); //verificar se o cliente foi obtido no banco de dados if (dependente != null) { //excluindo o cliente dependenteRepository.Delete(dependente); TempData["MensagemSucesso"] = "Dependente excluído com sucesso."; } else { throw new Exception("Dependente não encontrado."); } } catch (Exception e) { TempData["MensagemErro"] = "Erro: " + e.Message; } //redirecionar de volta para a página de consulta. return RedirectToAction("Consulta"); } //método de ação para abrir a página de edição de dependente public IActionResult Edicao(int id, [FromServices] DependenteRepository dependenteRepository, [FromServices] ClienteRepository clienteRepository) { //criando um objeto da classe model var model = GetDependenteEdicaoModel(clienteRepository); try { //buscando o cliente no banco de dados pelo id var dependente = dependenteRepository.GetById(id); //transferir os dados do cliente para a model model.IdDependente = dependente.IdDependente; model.Nome = dependente.Nome; model.DataNascimento = dependente.DataNascimento.ToString("dd/MM/yyyy"); model.IdCliente = dependente.IdCliente; } catch (Exception e) { TempData["MensagemErro"] = e.Message; } return View(model); //abrir uma página } [HttpPost] //método recebe o SUBMIT do formulário public IActionResult Edicao(DependenteEdicaoModel model, [FromServices] DependenteRepository dependenteRepository, [FromServices] ClienteRepository clienteRepository) { if (ModelState.IsValid) { try { var dependente = new Dependente(); dependente.IdDependente = Convert.ToInt32(model.IdDependente); dependente.Nome = model.Nome; dependente.DataNascimento = DateTime.Parse(model.DataNascimento); dependente.IdCliente = Convert.ToInt32(model.IdCliente); //atualizando no banco de dados dependenteRepository.Update(dependente); TempData["MensagemSucesso"] = "Dependente atualizado com sucesso."; } catch (Exception e) { TempData["MensagemErro"] = "Erro: " + e.Message; } } var result = GetDependenteEdicaoModel(clienteRepository); return View(result); } //função que carrega os clientes da página dependente private DependenteCadastroModel GetDependenteCadastroModel(ClienteRepository clienteRepository) { var model = new DependenteCadastroModel(); try { model.ListagemDeClientes = GetClientes(clienteRepository); } catch (Exception e) { TempData["MensagemErro"] = "Erro: " + e.Message; } return model; } //função que carrega os clientes da página Edição de dependente private DependenteEdicaoModel GetDependenteEdicaoModel(ClienteRepository clienteRepository) { var model = new DependenteEdicaoModel(); try { model.ListagemDeClientes = GetClientes(clienteRepository); } catch (Exception e) { TempData["MensagemErro"] = "Erro: " + e.Message; } return model; } private List<SelectListItem> GetClientes(ClienteRepository clienteRepository) { //carregar a lista com os clientes (campo de seleção) var listagemDeClientes = new List<SelectListItem>(); //percorrer todos os clientes obtidos do banco de dados foreach (var item in clienteRepository.GetAll()) { //criando 1 item do campo de seleção var opcao = new SelectListItem(); opcao.Value = item.IdCliente.ToString(); opcao.Text = item.Nome; listagemDeClientes.Add(opcao); //adicionando } return listagemDeClientes; } } }
35.815
178
0.557448
[ "MIT" ]
luizafortes/treinamento-csharp
ProjetoMVC01/Projeto.Presentation.Mvc/Controllers/DependenteController.cs
7,197
C#
namespace AcademyGeometry { public interface IFlat { Vector3D GetNormal(); } }
14
29
0.622449
[ "MIT" ]
NinoSimeonov/Telerik-Academy
Programming with C#/0. Exams/Telerik 2012-2013 - OOP Exam/C# OOP 2013 - Sample Exam/Solutions/02. Academy Geometry API/IFlat.cs
98
C#
// ///////////////////////////////////////////////////////////////////////////// // // File: DiffImplementation.cs // // Copyright (c) 2021 SEA Vision srl // This File is a property of SEA Vision srl // Any use or duplication of this file or part of it, // is strictly prohibited without a written permission // // ///////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; // ReSharper disable CoVariantArrayConversion namespace JsonDiffPatchDotNet.Internals { public static class DiffAlgorithm { public static JToken Diff(JToken left, JToken right, DiffOptions options) { left ??= new JValue(""); right ??= new JValue(""); if (left.Type == JTokenType.Object && right.Type == JTokenType.Object) return ObjectDiff((JObject) left, (JObject) right, options); if (left.Type == JTokenType.Array && right.Type == JTokenType.Array) return ArrayDiff((JArray) left, (JArray) right, options); return JToken.DeepEquals(left, right) ? null : new JArray(left, right); } private static JObject ObjectDiff(JObject left, JObject right, DiffOptions options) { if (left == null) throw new ArgumentNullException(nameof(left)); if (right == null) throw new ArgumentNullException(nameof(right)); var diff = new JObject(); // Find properties modified or deleted foreach (var leftProp in left.Properties()) { //Skip property if in path exclusions if (options.IsPathExcluded(leftProp.Path)) continue; var rightProp = right[leftProp.Name]; // Property was present. Format diff if (rightProp != null) { var propDiff = Diff(leftProp.Value, rightProp, options); if (propDiff != null) diff.Add(new JProperty(leftProp.Name, propDiff)); } // Property deleted else if (!options.IgnoreMissingProperties) diff.Add(new JProperty(leftProp.Name, new JArray(leftProp.Value, 0, (int) DiffOperation.Deleted))); } // Find properties that were added if (!options.IgnoreNewProperties) foreach (var rp in right.Properties().Where(rp => left[rp.Name] == null)) diff.Add(new JProperty(rp.Name, new JArray(rp.Value))); return diff.Properties().Any() ? diff : null; } private static JObject ArrayDiff(JArray left, JArray right, DiffOptions options) { if (JToken.DeepEquals(left, right)) return null; var head = GetCommonHeadLength(left, right); var tail = GetCommonTailLength(left, right, head); // Complex Diff, find the LCS (Longest Common Subsequence) in the arrays stripped of head and tail // trimmedLeft and trimmedRight are the left and right arrays, trimmed of common heads and tails. var trimmedLeft = left.Skip(head).Take(left.Count - tail - head).ToList(); var trimmedRight = right.Skip(head).Take(right.Count - tail - head).ToList(); var arrayDiff = CompareArrays(trimmedLeft, trimmedRight, head); var result = new List<JProperty> {new JProperty("_t", "a")}; result.AddRange((arrayDiff.ToDiff.Concat(arrayDiff.ToMove)) .Select(pair => { var valueDiff = Diff(left[pair.LeftIndex], right[pair.RightIndex], options); return (pair.LeftIndex == pair.RightIndex) ? new JProperty($"{pair.RightIndex}", valueDiff) : new JProperty($"_{pair.LeftIndex}", new JArray(valueDiff, pair.RightIndex, (int) DiffOperation.ArrayMove) ); }) ); result.AddRange(arrayDiff.ToAdd.Select(idx => MakeAddDiff(idx, right))); result.AddRange(arrayDiff.ToRemove.Select(idx => MakeDeletionDiff(idx, left))); //for (var index = head; index < right.Count - tail; index++) //{ // var item = arrayDiff.Lcs.FirstOrDefault(x => x.RightIndex == index); // // Every element in the right array that is not in the LCS gets added // if (item != null) // { // var diff = Diff(left[item.LeftIndex], right[item.RightIndex], options); // if (diff != null) result.Add(new JProperty($"{index}", diff)); // } //} return new JObject(result.ToArray()); } private static JProperty MakeAddDiff(int index, JArray right) => new JProperty($"{index}", new JArray(right[index])); private static JProperty MakeDeletionDiff(int index, JArray left) => new JProperty($"_{index}", new JArray(left[index], 0, 0)); // elements in the head of the 2 arrays that are equal private static int GetCommonHeadLength(JArray left, JArray right) => left.Zip(right, JToken.DeepEquals) .TakeWhile(areEqual => areEqual) .Take(left.Count > right.Count ? right.Count : left.Count) .Count(); // elements in the tail of the 2 arrays that are equal private static int GetCommonTailLength(JArray left, JArray right, int commonHead) => left.Reverse().Zip(right.Reverse(), JToken.DeepEquals) .TakeWhile(areEqual => areEqual) .Take((left.Count > right.Count ? right.Count : left.Count) - commonHead) .Count(); internal static ArrayDiff CompareArrays(List<JToken> left, List<JToken> right, int head) { var leftCount = left.Count; var rightCount = right.Count; if (leftCount == 0) return new ArrayDiff { ToMove = new ItemPair[0], ToDiff = new ItemPair[0], ToAdd = Enumerable.Range(head, rightCount).ToArray(), ToRemove = new int[0], }; if (rightCount == 0) return new ArrayDiff { ToMove = new ItemPair[0], ToDiff = new ItemPair[0], ToAdd = new int[0], ToRemove = Enumerable.Range(head, leftCount).ToArray() }; // each equalityMatrix[i][j] is true if left[i] deep equals right[j] var equalityMatrix = CalculateEqualityMatrix(left, right); var matrix = CalculateLcsMatrix(equalityMatrix, leftCount, rightCount); var lcsLength = matrix[leftCount, rightCount]; var result = new ArrayDiff(lcsLength); // sets containing the indices still to be moved var leftIdxs = new HashSet<int>(); var rightIdxs = new HashSet<int>(); // backtrack int i, j, sequenceIdx = lcsLength - 1; for (i = leftCount - 1, j = rightCount - 1; i >= 0 && j >= 0;) { // Console.WriteLine("{0},{1}", i, j); // If the JSON tokens at the same position are both Objects or both Arrays, we just say they // are the same even if they are not, because we can package smaller deltas than an entire // object or array replacement by doing object to object or array to array diff. // if true, we found an item in the LCS if (equalityMatrix[i, j]) { result.Lcs[sequenceIdx--] = new ItemPair(head + i--, head + j--); continue; } if (matrix[i, j + 1] > matrix[i + 1, j]) leftIdxs.Add(i--); else rightIdxs.Add(j--); } while (i >= 0) leftIdxs.Add(i--); while (j >= 0) rightIdxs.Add(j--); result.ToMove = FindMovements(leftIdxs, rightIdxs, equalityMatrix, head).ToArray(); result.ToDiff = FindEdits(leftIdxs, rightIdxs, head).ToArray(); result.ToRemove = leftIdxs.Select(x => head + x).OrderBy(x => x).ToArray(); result.ToAdd = rightIdxs.Select(x => head + x).OrderBy(x => x).ToArray(); return result; } // leftIdxs and rightIdxs now contains every "i" and "j" value not in the LCS // now we search for move operations private static IEnumerable<ItemPair> FindEdits(HashSet<int> leftIdxs, HashSet<int> rightIdxs, int head) { var leftSorted = leftIdxs.OrderBy(x => x); var rightSorted = rightIdxs.OrderBy(x => x); var pairs = leftSorted.Zip(rightSorted, (i, j) => new {Left = i, Right = j}).ToList(); foreach (var pair in pairs) { leftIdxs.Remove(pair.Left); rightIdxs.Remove(pair.Right); yield return new ItemPair(head + pair.Left, head + pair.Right); } } // leftIdxs and rightIdxs now contains every "i" and "j" value not in the LCS // now we search for move operations private static IEnumerable<ItemPair> FindMovements( HashSet<int> leftIdxs, HashSet<int> rightIdxs, bool[,] equalityMatrix, int head) { foreach (var iToMove in leftIdxs.OrderBy(x => x).ToList()) { var targetJ = rightIdxs.Select(j => (int?) j).FirstOrDefault(j => equalityMatrix[iToMove, j.Value]); if (targetJ != null) { leftIdxs.Remove(iToMove); rightIdxs.Remove(targetJ.Value); yield return new ItemPair(head + iToMove, head + targetJ.Value); } } } // https://en.wikipedia.org/wiki/Longest_common_subsequence_problem#LCS_function_defined private static int[,] CalculateLcsMatrix(bool[,] equalityMatrix, int leftCount, int rightCount) { var matrix = new int[leftCount + 1, rightCount + 1]; for (var i = 0; i < leftCount; i++) for (var j = 0; j < rightCount; j++) { matrix[i + 1, j + 1] = equalityMatrix[i, j] ? matrix[i, j] + 1 : Math.Max(matrix[i, j + 1], matrix[i + 1, j]); } // PrintoutLcsMatrix(leftCount, rightCount, matrix); return matrix; } #if DEBUG private static void PrintoutLcsMatrix(int leftCount, int rightCount, int[,] matrix) { Console.WriteLine("Matrix:"); for (var i = 0; i < leftCount + 1; i++) { for (var j = 0; j < rightCount + 1; j++) Console.Write(matrix[i, j].ToString("D2") + ","); Console.WriteLine(); } Console.WriteLine(); } #endif private static bool[,] CalculateEqualityMatrix(List<JToken> left, List<JToken> right) { int leftCount = left.Count, rightCount = right.Count; // each equalityMatrix[i][j] is true if left[i] deep equals right[j] var equalityMatrix = new bool[leftCount, rightCount]; // evaluate equalities using strings (it's faster) var leftJson = left.Select(x => x.ToString(Formatting.None)).ToList(); var rightJson = right.Select(x => x.ToString(Formatting.None)).ToList(); int i, j; for (i = 0; i < leftCount; i++) for (j = 0; j < rightCount; j++) { equalityMatrix[i, j] = leftJson[i] == rightJson[j]; } return equalityMatrix; } } /// <summary>Describes the difference between two array, /// containing data about array move operations, about the /// LCS, and about items to edit.</summary> public class ArrayDiff { // Pairs in the Longest Common Subsequence will NOT be outputted in the diff public ItemPair[] Lcs { get; set; } public int[] ToRemove { get; set; } public int[] ToAdd { get; set; } public ItemPair[] ToMove { get; set; } public ItemPair[] ToDiff { get; set; } public ArrayDiff(params ItemPair[] items) { if (items == null) throw new ArgumentNullException(nameof(items)); Lcs = items; } public ArrayDiff(int lcsLength) { if (lcsLength < 0) throw new ArgumentOutOfRangeException(nameof(lcsLength)); Lcs = new ItemPair[lcsLength]; } } public class ItemPair { public int LeftIndex { get; } public int RightIndex { get; } public ItemPair(int leftIndex, int rightIndex) { LeftIndex = leftIndex; RightIndex = rightIndex; } } }
42.830671
120
0.533045
[ "MIT" ]
alberto-chiesa/jsondiffpatch.net
Src/JsonDiffPatchDotNet/Internals/DiffAlgorithm.cs
13,406
C#
namespace Decorator { using System; /// <summary> /// The 'ConcreteComponent' class /// </summary> internal class Video : LibraryItem { private readonly string director; private readonly string title; private readonly int playTime; public Video(string director, string title, int copiesCount, int playTime) { this.director = director; this.title = title; this.CopiesCount = copiesCount; this.playTime = playTime; } public override void Display() { Console.WriteLine("\nVideo ----- "); Console.WriteLine(" Director: {0}", this.director); Console.WriteLine(" Title: {0}", this.title); Console.WriteLine(" # Copies: {0}", this.CopiesCount); Console.WriteLine(" Playtime: {0}\n", this.playTime); } } }
28.4375
82
0.56044
[ "MIT" ]
NinoSimeonov/Telerik-Academy
Programming with C#/3. C# Object-Oriented Programming/07. Design Patterns/Structural Patterns/Decorator/Video.cs
912
C#
using System; using System.Configuration; namespace nl.hyperdata.music.core.Collections.Diatonic { public sealed class Config { public static double TwelfthRootOfTwo => Math.Pow(2, 1.00 / 12.00); public static readonly string[] KeyNames = new string[] { "A", "A#,Bb", "B", "C", "C#,Db", "D", "D#,Eb", "E", "F", "F#,Gb", "G", "G#,Ab" }; public static readonly double BaseFrequency = double.Parse(ConfigurationManager.AppSettings["baseFrequency"]); public static readonly int OctaveCount = 8; public static readonly int PitchIndexCorrection = (4 * -12) - 1; public static readonly int ScaleStepCorrection = -28; } }
45
147
0.651852
[ "MIT" ]
casparkleijne/nl.hyperdata.music
nl.hyperdata.music.core/Collections/Diatonic/Config.cs
677
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("Utility")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Utility")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b6cff2c8-eb7e-48a2-88b6-86f2288f17ee")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.486486
84
0.743331
[ "MIT" ]
UltraSabreman/Free_Sharp_Player
Utility/Properties/AssemblyInfo.cs
1,390
C#
namespace RustBotCSharp.Math { public class Geometry { public static bool QuaternionToEuler(double qx, double qy, double qz, double qw, out double heading, out double attitude, out double bank) { double sqw = qw * qw; double sqx = qx * qx; double sqy = qy * qy; double sqz = qz * qz; double unit = sqx + sqy + sqz + sqw; // if normalised is one, otherwise is correction factor double test = qx * qy + qz * qw; if (test > 0.499 * unit) { // singularity at north pole heading = 2 * System.Math.Atan2(qx, qw); attitude = System.Math.PI / 2; bank = 0; return false; } if (test < -0.499 * unit) { // singularity at south pole heading = -2 * System.Math.Atan2(qx, qw); attitude = -System.Math.PI / 2; bank = 0; return false; } heading = System.Math.Atan2(2 * qy * qw - 2 * qx * qz, sqx - sqy - sqz + sqw); attitude = System.Math.Asin(2 * test / unit); bank = System.Math.Atan2(2 * qx * qw - 2 * qy * qz, -sqx + sqy - sqz + sqw); return true; } public static double DegreeToRadian(double angle) { return System.Math.PI * angle / 180.0; } public static double RadianToDegree(double angle) { return angle * (180.0 / System.Math.PI); } } }
35.477273
146
0.485586
[ "BSD-3-Clause" ]
carlosmccosta/RustBotCSharp
RustBotCSharp.Math/Geometry.cs
1,563
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Excercise01_6 { internal class Program { private static void Main(string[] args) { /* this is answer use list is fucking noob here if (input.ToLower() == "ok") break; sum += Convert.ToInt32(input); */ const string okStr = "ok"; var input = new StringBuilder(); var numberOfAll = new List<int>(); Console.WriteLine("Please type number for sum all your type "); while (!input.ToString().Contains(okStr)) { input.Clear(); input.Append(Console.ReadLine().ToLower()); try { numberOfAll.Add(int.Parse(input.ToString())); Console.WriteLine($"List have {numberOfAll.Count} number sumall equal {numberOfAll.Sum()}"); } catch { // ignored } } Console.WriteLine("Exit completed..."); Console.Read(); } } }
27.72093
112
0.479866
[ "MIT" ]
Arnonthawajjana/MoshTrainingCSharp
Excercise01_6/Program.cs
1,194
C#
using System.Collections.Generic; using NUnit.Framework; namespace Json.Path.Tests { public class OtherParsingTests { public static IEnumerable<TestCaseData> SuccessCases => new[] { new TestCaseData("$.baz") }; [TestCaseSource(nameof(SuccessCases))] public void ParseSingleProperty(string path) { JsonPath.Parse(path); } } }
17
57
0.711485
[ "MIT" ]
JMPSequeira/json-everything
JsonPath.Tests/OtherParsingTests.cs
359
C#
using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace PowerApps.Samples.Metadata { [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] public class AttributeRequiredLevelManagedProperty { public AttributeRequiredLevelManagedProperty(AttributeRequiredLevel value) { Value = value; } public AttributeRequiredLevel Value { get; set; } public bool CanBeChanged { get; set; } public string ManagedPropertyLogicalName { get; } = "canmodifyrequirementlevelsettings"; } }
29.842105
96
0.712522
[ "MIT" ]
Antrodfr/PowerApps-Samples
cds/webapi/C#/MetadataOperations/MetadataTypes/AttributeRequiredLevelManagedProperty.cs
569
C#
#pragma checksum "..\..\..\Pushups\PushupsSettingsPage.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "F6473F30CFA5795A09B4B1373F70025592CA093F76A2ABD8457E50D428BF82F5" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; using Workout.Pushups; namespace Workout.Pushups { /// <summary> /// PushupsSettingsPage /// </summary> public partial class PushupsSettingsPage : System.Windows.Controls.Page, System.Windows.Markup.IComponentConnector { #line 43 "..\..\..\Pushups\PushupsSettingsPage.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Label labelExTime1; #line default #line hidden #line 44 "..\..\..\Pushups\PushupsSettingsPage.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Label labelBrTime1; #line default #line hidden #line 45 "..\..\..\Pushups\PushupsSettingsPage.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBox textTestResult; #line default #line hidden #line 46 "..\..\..\Pushups\PushupsSettingsPage.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBox textTrainingDay; #line default #line hidden #line 47 "..\..\..\Pushups\PushupsSettingsPage.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Label labelPushup; #line default #line hidden #line 62 "..\..\..\Pushups\PushupsSettingsPage.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button backButton; #line default #line hidden #line 71 "..\..\..\Pushups\PushupsSettingsPage.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button nextButton; #line default #line hidden private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/Workout;component/pushups/pushupssettingspage.xaml", System.UriKind.Relative); #line 1 "..\..\..\Pushups\PushupsSettingsPage.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: this.labelExTime1 = ((System.Windows.Controls.Label)(target)); return; case 2: this.labelBrTime1 = ((System.Windows.Controls.Label)(target)); return; case 3: this.textTestResult = ((System.Windows.Controls.TextBox)(target)); return; case 4: this.textTrainingDay = ((System.Windows.Controls.TextBox)(target)); return; case 5: this.labelPushup = ((System.Windows.Controls.Label)(target)); return; case 6: this.backButton = ((System.Windows.Controls.Button)(target)); #line 62 "..\..\..\Pushups\PushupsSettingsPage.xaml" this.backButton.Click += new System.Windows.RoutedEventHandler(this.backButton_Click); #line default #line hidden return; case 7: this.nextButton = ((System.Windows.Controls.Button)(target)); #line 71 "..\..\..\Pushups\PushupsSettingsPage.xaml" this.nextButton.Click += new System.Windows.RoutedEventHandler(this.nextButton_Click); #line default #line hidden return; } this._contentLoaded = true; } } }
39.607143
169
0.633303
[ "MIT" ]
dLeczycki/FatBurn-Workout
Workout/obj/Debug/Pushups/PushupsSettingsPage.g.cs
6,656
C#
using SqlServerAnalyzerCommon.Interfaces; using System.Collections.Generic; using System.Threading.Tasks; namespace SqlServerAnalyzerCommon.Implementation { public abstract class SqlServerBase : ISqlServer { public abstract Task<IList<ISqlDatabase>> GetDatabasesAsync(); } }
24.75
70
0.781145
[ "MIT" ]
kennedylabs/sql-server-analyzer
SqlServerAnalyzer/SqlServerAnalyzerCommon/Implementation/SqlServerBase.cs
299
C#
using Newtonsoft.Json; namespace Alipay.AopSdk.Core.Response { /// <summary> /// AlipayDataBillDownloadurlGetResponse. /// </summary> public class AlipayDataBillDownloadurlGetResponse : AopResponse { /// <summary> /// 账单下载地址链接,获取连接后30秒后未下载,链接地址失效。 /// </summary> [JsonProperty("bill_download_url")] public string BillDownloadUrl { get; set; } } }
23.1875
64
0.706199
[ "MIT" ]
ArcherTrister/LeXun.Alipay.AopSdk
src/Alipay.AopSdk.Core/Response/AlipayDataBillDownloadurlGetResponse.cs
425
C#
// $Id$ // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // using System; using Org.Apache.Etch.Bindings.Csharp.Support; using Org.Apache.Etch.Bindings.Csharp.Util; using NUnit.Framework; using org.apache.etch.examples.perf.types.Perf; namespace org.apache.etch.examples.perf { /// <summary> /// Unit Tests to test Perf /// </summary> /// [TestFixture] public class TestPerfServer { private static RemotePerfServer server; private static ServerFactory listener; [TestFixtureSetUp] public void StartListener() { String uri = "tcp://localhost:4010"; MainPerfListener implFactory = new MainPerfListener(); listener = PerfHelper.NewListener(uri, null, implFactory); listener.TransportControl(TransportConsts.START_AND_WAIT_UP, 4000); Console.WriteLine("Listener Started"); } [SetUp] public void MakeConnection() { String uri = "tcp://localhost:4010"; MainPerfClient client = new MainPerfClient(); server = PerfHelper.NewServer(uri, null, client); server._StartAndWaitUp(4000); } [Test] public void CheckConnection() { Assert.IsNotNull(server); } [Test] public void TestAdd() { int? result = server.add(3, 5); Assert.AreEqual(8, result); } [Test] public void TestAdd2() { DateTime? d = DateTime.Now; long? ms = 1000; DateTime? expectedDate = d.Value + new TimeSpan(ms.Value * 10000); DateTime? retDate = server.add2(d, ms); Assert.AreEqual(expectedDate.Value.ToString(), retDate.Value.ToString()); } [Test] public void TestSum() { int[] a = { 1, 2, 3 }; int? result = server.sum(a); Assert.AreEqual(6, result); } [Test] public void TestDistance() { Point a = new Point(2, 3); Point b = new Point(4, 5); Point result = server.dist(a, b); Assert.AreEqual(2, result.x); Assert.AreEqual(2, result.y); } [TearDown] public void CloseConnection() { if (server != null) { server._Stop(); } } [TestFixtureTearDown] public void StopListener() { if (listener != null) { listener.TransportControl(TransportConsts.STOP_AND_WAIT_DOWN, 4000); listener = null; } } } }
27.393701
85
0.576028
[ "ECL-2.0", "Apache-2.0" ]
apache/etch
examples/perf/src/test/csharp/etch.examples.perf/TestPerfServer.cs
3,479
C#
#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class XLuaCSObjectWrapPathfindingRVOMovementPlaneWrapWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(XLua.CSObjectWrap.PathfindingRVOMovementPlaneWrap); Utils.BeginObjectRegister(type, L, translator, 0, 0, 0, 0); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 2, 0, 0); Utils.RegisterFunc(L, Utils.CLS_IDX, "__Register", _m___Register_xlua_st_); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); if(LuaAPI.lua_gettop(L) == 1) { XLua.CSObjectWrap.PathfindingRVOMovementPlaneWrap gen_ret = new XLua.CSObjectWrap.PathfindingRVOMovementPlaneWrap(); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to XLua.CSObjectWrap.PathfindingRVOMovementPlaneWrap constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m___Register_xlua_st_(RealStatePtr L) { try { { System.IntPtr _L = LuaAPI.lua_touserdata(L, 1); XLua.CSObjectWrap.PathfindingRVOMovementPlaneWrap.__Register( _L ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } } }
24.009091
127
0.56418
[ "MIT" ]
zxsean/DCET
Unity/Assets/Model/XLua/Gen/XLuaCSObjectWrapPathfindingRVOMovementPlaneWrapWrap.cs
2,643
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.AppConfiguration.Models; using Azure.ResourceManager.Core; namespace Azure.ResourceManager.AppConfiguration { internal partial class ConfigurationStoresRestOperations { private readonly string _userAgent; private readonly HttpPipeline _pipeline; private readonly Uri _endpoint; private readonly string _apiVersion; /// <summary> The ClientDiagnostics is used to provide tracing support for the client library. </summary> internal ClientDiagnostics ClientDiagnostics { get; } /// <summary> Initializes a new instance of ConfigurationStoresRestOperations. </summary> /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="applicationId"> The application id to use for user agent. </param> /// <param name="endpoint"> server parameter. </param> /// <param name="apiVersion"> Api Version. </param> /// <exception cref="ArgumentNullException"> <paramref name="apiVersion"/> is null. </exception> public ConfigurationStoresRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) { _endpoint = endpoint ?? new Uri("https://management.azure.com"); _apiVersion = apiVersion ?? "2020-06-01"; ClientDiagnostics = clientDiagnostics; _pipeline = pipeline; _userAgent = Core.HttpMessageUtilities.GetUserAgentName(this, applicationId); } internal HttpMessage CreateListRequest(string subscriptionId, string skipToken) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/providers/Microsoft.AppConfiguration/configurationStores", false); uri.AppendQuery("api-version", _apiVersion, true); if (skipToken != null) { uri.AppendQuery("$skipToken", skipToken, true); } request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Lists the configuration stores for a given subscription. </summary> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="skipToken"> A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception> public async Task<Response<ConfigurationStoreListResult>> ListAsync(string subscriptionId, string skipToken = null, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } using var message = CreateListRequest(subscriptionId, skipToken); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ConfigurationStoreListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ConfigurationStoreListResult.DeserializeConfigurationStoreListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Lists the configuration stores for a given subscription. </summary> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="skipToken"> A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception> public Response<ConfigurationStoreListResult> List(string subscriptionId, string skipToken = null, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } using var message = CreateListRequest(subscriptionId, skipToken); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ConfigurationStoreListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ConfigurationStoreListResult.DeserializeConfigurationStoreListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw ClientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListByResourceGroupRequest(string subscriptionId, string resourceGroupName, string skipToken) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.AppConfiguration/configurationStores", false); uri.AppendQuery("api-version", _apiVersion, true); if (skipToken != null) { uri.AppendQuery("$skipToken", skipToken, true); } request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Lists the configuration stores for a given resource group. </summary> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="skipToken"> A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception> public async Task<Response<ConfigurationStoreListResult>> ListByResourceGroupAsync(string subscriptionId, string resourceGroupName, string skipToken = null, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName, skipToken); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ConfigurationStoreListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ConfigurationStoreListResult.DeserializeConfigurationStoreListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Lists the configuration stores for a given resource group. </summary> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="skipToken"> A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception> public Response<ConfigurationStoreListResult> ListByResourceGroup(string subscriptionId, string resourceGroupName, string skipToken = null, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName, skipToken); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ConfigurationStoreListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ConfigurationStoreListResult.DeserializeConfigurationStoreListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw ClientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string configStoreName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.AppConfiguration/configurationStores/", false); uri.AppendPath(configStoreName, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Gets the properties of the specified configuration store. </summary> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="configStoreName"> The name of the configuration store. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="configStoreName"/> is null. </exception> public async Task<Response<ConfigurationStoreData>> GetAsync(string subscriptionId, string resourceGroupName, string configStoreName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (configStoreName == null) { throw new ArgumentNullException(nameof(configStoreName)); } using var message = CreateGetRequest(subscriptionId, resourceGroupName, configStoreName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ConfigurationStoreData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ConfigurationStoreData.DeserializeConfigurationStoreData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((ConfigurationStoreData)null, message.Response); default: throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets the properties of the specified configuration store. </summary> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="configStoreName"> The name of the configuration store. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="configStoreName"/> is null. </exception> public Response<ConfigurationStoreData> Get(string subscriptionId, string resourceGroupName, string configStoreName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (configStoreName == null) { throw new ArgumentNullException(nameof(configStoreName)); } using var message = CreateGetRequest(subscriptionId, resourceGroupName, configStoreName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ConfigurationStoreData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ConfigurationStoreData.DeserializeConfigurationStoreData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((ConfigurationStoreData)null, message.Response); default: throw ClientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateCreateRequest(string subscriptionId, string resourceGroupName, string configStoreName, ConfigurationStoreData configStoreCreationParameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.AppConfiguration/configurationStores/", false); uri.AppendPath(configStoreName, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(configStoreCreationParameters); request.Content = content; message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Creates a configuration store with the specified parameters. </summary> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="configStoreName"> The name of the configuration store. </param> /// <param name="configStoreCreationParameters"> The parameters for creating a configuration store. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="configStoreName"/>, or <paramref name="configStoreCreationParameters"/> is null. </exception> public async Task<Response> CreateAsync(string subscriptionId, string resourceGroupName, string configStoreName, ConfigurationStoreData configStoreCreationParameters, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (configStoreName == null) { throw new ArgumentNullException(nameof(configStoreName)); } if (configStoreCreationParameters == null) { throw new ArgumentNullException(nameof(configStoreCreationParameters)); } using var message = CreateCreateRequest(subscriptionId, resourceGroupName, configStoreName, configStoreCreationParameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 201: return message.Response; default: throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Creates a configuration store with the specified parameters. </summary> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="configStoreName"> The name of the configuration store. </param> /// <param name="configStoreCreationParameters"> The parameters for creating a configuration store. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="configStoreName"/>, or <paramref name="configStoreCreationParameters"/> is null. </exception> public Response Create(string subscriptionId, string resourceGroupName, string configStoreName, ConfigurationStoreData configStoreCreationParameters, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (configStoreName == null) { throw new ArgumentNullException(nameof(configStoreName)); } if (configStoreCreationParameters == null) { throw new ArgumentNullException(nameof(configStoreCreationParameters)); } using var message = CreateCreateRequest(subscriptionId, resourceGroupName, configStoreName, configStoreCreationParameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 201: return message.Response; default: throw ClientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string configStoreName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.AppConfiguration/configurationStores/", false); uri.AppendPath(configStoreName, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Deletes a configuration store. </summary> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="configStoreName"> The name of the configuration store. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="configStoreName"/> is null. </exception> public async Task<Response> DeleteAsync(string subscriptionId, string resourceGroupName, string configStoreName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (configStoreName == null) { throw new ArgumentNullException(nameof(configStoreName)); } using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, configStoreName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: case 204: return message.Response; default: throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Deletes a configuration store. </summary> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="configStoreName"> The name of the configuration store. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="configStoreName"/> is null. </exception> public Response Delete(string subscriptionId, string resourceGroupName, string configStoreName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (configStoreName == null) { throw new ArgumentNullException(nameof(configStoreName)); } using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, configStoreName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: case 204: return message.Response; default: throw ClientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateUpdateRequest(string subscriptionId, string resourceGroupName, string configStoreName, ConfigurationStoreUpdateOptions configurationStoreUpdateOptions) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Patch; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.AppConfiguration/configurationStores/", false); uri.AppendPath(configStoreName, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(configurationStoreUpdateOptions); request.Content = content; message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Updates a configuration store with the specified parameters. </summary> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="configStoreName"> The name of the configuration store. </param> /// <param name="configurationStoreUpdateOptions"> The options for updating a configuration store. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="configStoreName"/>, or <paramref name="configurationStoreUpdateOptions"/> is null. </exception> public async Task<Response> UpdateAsync(string subscriptionId, string resourceGroupName, string configStoreName, ConfigurationStoreUpdateOptions configurationStoreUpdateOptions, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (configStoreName == null) { throw new ArgumentNullException(nameof(configStoreName)); } if (configurationStoreUpdateOptions == null) { throw new ArgumentNullException(nameof(configurationStoreUpdateOptions)); } using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, configStoreName, configurationStoreUpdateOptions); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 201: return message.Response; default: throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Updates a configuration store with the specified parameters. </summary> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="configStoreName"> The name of the configuration store. </param> /// <param name="configurationStoreUpdateOptions"> The options for updating a configuration store. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="configStoreName"/>, or <paramref name="configurationStoreUpdateOptions"/> is null. </exception> public Response Update(string subscriptionId, string resourceGroupName, string configStoreName, ConfigurationStoreUpdateOptions configurationStoreUpdateOptions, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (configStoreName == null) { throw new ArgumentNullException(nameof(configStoreName)); } if (configurationStoreUpdateOptions == null) { throw new ArgumentNullException(nameof(configurationStoreUpdateOptions)); } using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, configStoreName, configurationStoreUpdateOptions); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 201: return message.Response; default: throw ClientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListKeysRequest(string subscriptionId, string resourceGroupName, string configStoreName, string skipToken) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.AppConfiguration/configurationStores/", false); uri.AppendPath(configStoreName, true); uri.AppendPath("/ListKeys", false); uri.AppendQuery("api-version", _apiVersion, true); if (skipToken != null) { uri.AppendQuery("$skipToken", skipToken, true); } request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Lists the access key for the specified configuration store. </summary> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="configStoreName"> The name of the configuration store. </param> /// <param name="skipToken"> A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="configStoreName"/> is null. </exception> public async Task<Response<ApiKeyListResult>> ListKeysAsync(string subscriptionId, string resourceGroupName, string configStoreName, string skipToken = null, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (configStoreName == null) { throw new ArgumentNullException(nameof(configStoreName)); } using var message = CreateListKeysRequest(subscriptionId, resourceGroupName, configStoreName, skipToken); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ApiKeyListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ApiKeyListResult.DeserializeApiKeyListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Lists the access key for the specified configuration store. </summary> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="configStoreName"> The name of the configuration store. </param> /// <param name="skipToken"> A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="configStoreName"/> is null. </exception> public Response<ApiKeyListResult> ListKeys(string subscriptionId, string resourceGroupName, string configStoreName, string skipToken = null, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (configStoreName == null) { throw new ArgumentNullException(nameof(configStoreName)); } using var message = CreateListKeysRequest(subscriptionId, resourceGroupName, configStoreName, skipToken); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ApiKeyListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ApiKeyListResult.DeserializeApiKeyListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw ClientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateRegenerateKeyRequest(string subscriptionId, string resourceGroupName, string configStoreName, RegenerateKeyOptions regenerateKeyOptions) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.AppConfiguration/configurationStores/", false); uri.AppendPath(configStoreName, true); uri.AppendPath("/RegenerateKey", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(regenerateKeyOptions); request.Content = content; message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Regenerates an access key for the specified configuration store. </summary> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="configStoreName"> The name of the configuration store. </param> /// <param name="regenerateKeyOptions"> The options for regenerating an access key. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="configStoreName"/>, or <paramref name="regenerateKeyOptions"/> is null. </exception> public async Task<Response<ApiKey>> RegenerateKeyAsync(string subscriptionId, string resourceGroupName, string configStoreName, RegenerateKeyOptions regenerateKeyOptions, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (configStoreName == null) { throw new ArgumentNullException(nameof(configStoreName)); } if (regenerateKeyOptions == null) { throw new ArgumentNullException(nameof(regenerateKeyOptions)); } using var message = CreateRegenerateKeyRequest(subscriptionId, resourceGroupName, configStoreName, regenerateKeyOptions); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ApiKey value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ApiKey.DeserializeApiKey(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Regenerates an access key for the specified configuration store. </summary> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="configStoreName"> The name of the configuration store. </param> /// <param name="regenerateKeyOptions"> The options for regenerating an access key. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="configStoreName"/>, or <paramref name="regenerateKeyOptions"/> is null. </exception> public Response<ApiKey> RegenerateKey(string subscriptionId, string resourceGroupName, string configStoreName, RegenerateKeyOptions regenerateKeyOptions, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (configStoreName == null) { throw new ArgumentNullException(nameof(configStoreName)); } if (regenerateKeyOptions == null) { throw new ArgumentNullException(nameof(regenerateKeyOptions)); } using var message = CreateRegenerateKeyRequest(subscriptionId, resourceGroupName, configStoreName, regenerateKeyOptions); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ApiKey value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ApiKey.DeserializeApiKey(document.RootElement); return Response.FromValue(value, message.Response); } default: throw ClientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListKeyValueRequest(string subscriptionId, string resourceGroupName, string configStoreName, ListKeyValueOptions listKeyValueOptions) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.AppConfiguration/configurationStores/", false); uri.AppendPath(configStoreName, true); uri.AppendPath("/listKeyValue", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(listKeyValueOptions); request.Content = content; message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Lists a configuration store key-value. </summary> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="configStoreName"> The name of the configuration store. </param> /// <param name="listKeyValueOptions"> The options for retrieving a key-value. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="configStoreName"/>, or <paramref name="listKeyValueOptions"/> is null. </exception> public async Task<Response<KeyValue>> ListKeyValueAsync(string subscriptionId, string resourceGroupName, string configStoreName, ListKeyValueOptions listKeyValueOptions, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (configStoreName == null) { throw new ArgumentNullException(nameof(configStoreName)); } if (listKeyValueOptions == null) { throw new ArgumentNullException(nameof(listKeyValueOptions)); } using var message = CreateListKeyValueRequest(subscriptionId, resourceGroupName, configStoreName, listKeyValueOptions); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { KeyValue value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = KeyValue.DeserializeKeyValue(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Lists a configuration store key-value. </summary> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="configStoreName"> The name of the configuration store. </param> /// <param name="listKeyValueOptions"> The options for retrieving a key-value. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="configStoreName"/>, or <paramref name="listKeyValueOptions"/> is null. </exception> public Response<KeyValue> ListKeyValue(string subscriptionId, string resourceGroupName, string configStoreName, ListKeyValueOptions listKeyValueOptions, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (configStoreName == null) { throw new ArgumentNullException(nameof(configStoreName)); } if (listKeyValueOptions == null) { throw new ArgumentNullException(nameof(listKeyValueOptions)); } using var message = CreateListKeyValueRequest(subscriptionId, resourceGroupName, configStoreName, listKeyValueOptions); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { KeyValue value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = KeyValue.DeserializeKeyValue(document.RootElement); return Response.FromValue(value, message.Response); } default: throw ClientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string skipToken) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Lists the configuration stores for a given subscription. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="skipToken"> A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception> public async Task<Response<ConfigurationStoreListResult>> ListNextPageAsync(string nextLink, string subscriptionId, string skipToken = null, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } using var message = CreateListNextPageRequest(nextLink, subscriptionId, skipToken); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ConfigurationStoreListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ConfigurationStoreListResult.DeserializeConfigurationStoreListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Lists the configuration stores for a given subscription. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="skipToken"> A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception> public Response<ConfigurationStoreListResult> ListNextPage(string nextLink, string subscriptionId, string skipToken = null, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } using var message = CreateListNextPageRequest(nextLink, subscriptionId, skipToken); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ConfigurationStoreListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ConfigurationStoreListResult.DeserializeConfigurationStoreListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw ClientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListByResourceGroupNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string skipToken) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Lists the configuration stores for a given resource group. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="skipToken"> A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, or <paramref name="resourceGroupName"/> is null. </exception> public async Task<Response<ConfigurationStoreListResult>> ListByResourceGroupNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string skipToken = null, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName, skipToken); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ConfigurationStoreListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ConfigurationStoreListResult.DeserializeConfigurationStoreListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Lists the configuration stores for a given resource group. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="skipToken"> A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, or <paramref name="resourceGroupName"/> is null. </exception> public Response<ConfigurationStoreListResult> ListByResourceGroupNextPage(string nextLink, string subscriptionId, string resourceGroupName, string skipToken = null, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName, skipToken); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ConfigurationStoreListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ConfigurationStoreListResult.DeserializeConfigurationStoreListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw ClientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListKeysNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string configStoreName, string skipToken) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("SDKUserAgent", _userAgent); return message; } /// <summary> Lists the access key for the specified configuration store. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="configStoreName"> The name of the configuration store. </param> /// <param name="skipToken"> A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="configStoreName"/> is null. </exception> public async Task<Response<ApiKeyListResult>> ListKeysNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string configStoreName, string skipToken = null, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (configStoreName == null) { throw new ArgumentNullException(nameof(configStoreName)); } using var message = CreateListKeysNextPageRequest(nextLink, subscriptionId, resourceGroupName, configStoreName, skipToken); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ApiKeyListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ApiKeyListResult.DeserializeApiKeyListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Lists the access key for the specified configuration store. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The Microsoft Azure subscription ID. </param> /// <param name="resourceGroupName"> The name of the resource group to which the container registry belongs. </param> /// <param name="configStoreName"> The name of the configuration store. </param> /// <param name="skipToken"> A skip token is used to continue retrieving items after an operation returns a partial result. If a previous response contains a nextLink element, the value of the nextLink element will include a skipToken parameter that specifies a starting point to use for subsequent calls. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="configStoreName"/> is null. </exception> public Response<ApiKeyListResult> ListKeysNextPage(string nextLink, string subscriptionId, string resourceGroupName, string configStoreName, string skipToken = null, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (configStoreName == null) { throw new ArgumentNullException(nameof(configStoreName)); } using var message = CreateListKeysNextPageRequest(nextLink, subscriptionId, resourceGroupName, configStoreName, skipToken); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ApiKeyListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ApiKeyListResult.DeserializeApiKeyListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw ClientDiagnostics.CreateRequestFailedException(message.Response); } } } }
57.781145
322
0.634185
[ "MIT" ]
greck2908/azure-sdk-for-net
sdk/appconfiguration/Azure.ResourceManager.AppConfiguration/src/Generated/RestOperations/ConfigurationStoresRestOperations.cs
68,644
C#
using System.IO; namespace Wikipedia_XML_Generator.Utils.XmlDTDValidator { public interface IValidator { public bool Validate(string s); public bool Validate(Stream s); } }
17.916667
56
0.651163
[ "MIT" ]
PavelSarlov/Wikipedia-XML-Generator
Wikipedia-XML-Generator/Utils/XmlDTDValidator/IValidator.cs
217
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.CosmosDB.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Describes the service response property for MaterializedViewsBuilder. /// </summary> public partial class MaterializedViewsBuilderServiceResource { /// <summary> /// Initializes a new instance of the /// MaterializedViewsBuilderServiceResource class. /// </summary> public MaterializedViewsBuilderServiceResource() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// MaterializedViewsBuilderServiceResource class. /// </summary> public MaterializedViewsBuilderServiceResource(MaterializedViewsBuilderServiceResourceProperties properties = default(MaterializedViewsBuilderServiceResourceProperties)) { Properties = properties; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "properties")] public MaterializedViewsBuilderServiceResourceProperties Properties { get; set; } } }
32.288462
177
0.664681
[ "MIT" ]
AikoBB/azure-sdk-for-net
sdk/cosmosdb/Microsoft.Azure.Management.CosmosDB/src/Generated/Models/MaterializedViewsBuilderServiceResource.cs
1,679
C#
using System.Collections.ObjectModel; namespace AdventureWorks.WebAPI.Areas.HelpPage.ModelDescriptions { public class ComplexTypeModelDescription : ModelDescription { public ComplexTypeModelDescription() { Properties = new Collection<ParameterDescription>(); } public Collection<ParameterDescription> Properties { get; private set; } } }
28.214286
80
0.711392
[ "MIT" ]
amelmusic/REST-Framework-AdventureWorks
AdventureWorks/AdventureWorks.WebAPI/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs
395
C#
using System.Xml; namespace Discovery.Library.Extensions { public static class XMLExtensions { public static XmlElement AppendElement(this XmlDocument xmlDocument, string name, string value = null, XmlElement parent = null) { var element = xmlDocument.CreateElement(name); if (value != null) element.InnerText = value; if (parent == null) xmlDocument.AppendChild(element); else parent.AppendChild(element); return element; } public static XmlElement AppendElement(this XmlElement xmlElement, string name, string value = null, bool raw = false) { var element = xmlElement.OwnerDocument.CreateElement(name); if (value != null) if (raw) element.InnerXml = value; else element.InnerText = value; xmlElement.AppendChild(element); return element; } public static XmlAttribute AppendAttribute(this XmlElement xmlElement, string name, string value = null) { var attribute = xmlElement.OwnerDocument.CreateAttribute(name); if (value != null) attribute.Value = value; xmlElement.Attributes.Append(attribute); return attribute; } } }
28.512821
130
0.725719
[ "MIT" ]
poostwoud/discovery
src/Discovery/Discovery.Library/Extensions/XMLExtensions.cs
1,112
C#
// *** WARNING: this file was generated by crd2pulumi. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Kubernetes.Types.Inputs.Kibana.V1 { /// <summary> /// KibanaStatus defines the observed state of Kibana /// </summary> public class KibanaStatusArgs : Pulumi.ResourceArgs { /// <summary> /// AssociationStatus is the status of an association resource. /// </summary> [Input("associationStatus")] public Input<string>? AssociationStatus { get; set; } /// <summary> /// AvailableNodes is the number of available replicas in the deployment. /// </summary> [Input("availableNodes")] public Input<int>? AvailableNodes { get; set; } /// <summary> /// Health of the deployment. /// </summary> [Input("health")] public Input<string>? Health { get; set; } /// <summary> /// Version of the stack resource currently running. During version upgrades, multiple versions may run in parallel: this value specifies the lowest version currently running. /// </summary> [Input("version")] public Input<string>? Version { get; set; } public KibanaStatusArgs() { } } }
31.12766
183
0.62201
[ "Apache-2.0" ]
pulumi/pulumi-kubernetes-crds
operators/elastic-cloud-eck/dotnet/Kubernetes/Crds/Operators/ElasticCloudEck/Kibana/V1/Inputs/KibanaStatusArgs.cs
1,463
C#
#pragma checksum "..\..\..\MainWindow.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "DD8C17479E58C557C6F3AB36FCB52319" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using FMM2; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace FMM2 { /// <summary> /// MainWindow /// </summary> public partial class MainWindow : System.Windows.Window, System.Windows.Markup.IComponentConnector { #line 24 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Grid everythingGrid; #line default #line hidden #line 27 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TabControl modsTabs; #line default #line hidden #line 28 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TabItem myModsTab; #line default #line hidden #line 29 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Grid myModsOuterGrid; #line default #line hidden #line 35 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Grid myModsAlert; #line default #line hidden #line 36 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock myModsAlertText; #line default #line hidden #line 37 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button myModsAlertHide; #line default #line hidden #line 39 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Grid myModsMenu; #line default #line hidden #line 40 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button myModsRefreshButton; #line default #line hidden #line 41 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Primitives.StatusBarItem myModsStatusNumber; #line default #line hidden #line 42 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBox myModsSearchBox; #line default #line hidden #line 44 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Grid myModsGrid; #line default #line hidden #line 52 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.ListView myModsList; #line default #line hidden #line 75 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.GridViewColumn gv1Name; #line default #line hidden #line 76 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.GridViewColumn gv1Author; #line default #line hidden #line 77 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.GridViewColumn gv1Version; #line default #line hidden #line 78 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.GridViewColumn gv1Description; #line default #line hidden #line 79 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.GridViewColumn gv1Warnings; #line default #line hidden #line 84 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Grid infobar; #line default #line hidden #line 89 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.ScrollViewer infobarScroll; #line default #line hidden #line 90 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.StackPanel infobarPanel; #line default #line hidden #line 92 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.ContentControl infobarCon; #line default #line hidden #line 93 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Grid infobarViewGrid; #line default #line hidden #line 94 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Image infobarImage; #line default #line hidden #line 95 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Shapes.Rectangle infobarRect; #line default #line hidden #line 105 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.StackPanel infobarHeader; #line default #line hidden #line 106 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock infobarName; #line default #line hidden #line 112 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock infobarAuthor; #line default #line hidden #line 113 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock infobarCredits; #line default #line hidden #line 115 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Image infobarIcon; #line default #line hidden #line 119 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.StackPanel infobarOps; #line default #line hidden #line 120 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button infobarUp; #line default #line hidden #line 125 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button infobarDn; #line default #line hidden #line 130 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button infobarDelete; #line default #line hidden #line 136 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock infobarRevisionDate; #line default #line hidden #line 137 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock infobarEDVersion; #line default #line hidden #line 138 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock infobarDescription; #line default #line hidden #line 146 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock infobarWarnings; #line default #line hidden #line 156 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button infobarApply; #line default #line hidden #line 161 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TabItem downloadableModsTab; #line default #line hidden #line 162 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Grid downloadableModsOuterGrid; #line default #line hidden #line 168 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Grid downloadableModsAlert; #line default #line hidden #line 169 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock downloadableModsAlertText; #line default #line hidden #line 170 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button downloadableModsAlertHide; #line default #line hidden #line 172 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Grid downloadableModsMenu; #line default #line hidden #line 173 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button dlModsRefreshButton; #line default #line hidden #line 174 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Primitives.StatusBarItem dlModsStatusNumber; #line default #line hidden #line 175 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBox dlModsSearchBox; #line default #line hidden #line 177 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Grid downloadableModsGrid; #line default #line hidden #line 183 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.ListView downloadableModsList; #line default #line hidden #line 198 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.GridViewColumn gv2Name; #line default #line hidden #line 199 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.GridViewColumn gv2Author; #line default #line hidden #line 200 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.GridViewColumn gv2Version; #line default #line hidden #line 201 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.GridViewColumn gv2Description; #line default #line hidden #line 202 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.GridViewColumn gv2Warnings; #line default #line hidden #line 207 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Grid infobarDL; #line default #line hidden #line 212 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.ScrollViewer infobarDLScroll; #line default #line hidden #line 213 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.StackPanel infobarDLPanel; #line default #line hidden #line 215 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.ContentControl infobarDLCon; #line default #line hidden #line 216 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Grid infobarDLViewGrid; #line default #line hidden #line 217 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Image infobarDLImage; #line default #line hidden #line 218 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Shapes.Rectangle infobarDLRect; #line default #line hidden #line 228 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.StackPanel infobarDLHeader; #line default #line hidden #line 229 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock infobarDLName; #line default #line hidden #line 235 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock infobarDLAuthor; #line default #line hidden #line 236 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock infobarDLCredits; #line default #line hidden #line 238 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Image infobarDLIcon; #line default #line hidden #line 242 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock infobarDLRevisionDate; #line default #line hidden #line 243 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock infobarDLEDVersion; #line default #line hidden #line 244 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock infobarDLDescription; #line default #line hidden #line 252 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock infobarDLWarnings; #line default #line hidden #line 262 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button infobarDLDownload; #line default #line hidden #line 736 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Menu menu; #line default #line hidden #line 737 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.MenuItem file; #line default #line hidden #line 738 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.MenuItem fileAbout; #line default #line hidden #line 740 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.MenuItem fileExit; #line default #line hidden #line 747 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.MenuItem options; #line default #line hidden #line 752 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.MenuItem optionsOrder; #line default #line hidden #line 753 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.MenuItem optionsOrderList; #line default #line hidden #line 754 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.MenuItem optionsOrderPriority; #line default #line hidden #line 757 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.MenuItem optionsOffline; #line default #line hidden #line 758 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.MenuItem optionsDeveloper; #line default #line hidden #line 759 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Separator optionsDeveloperSeparator; #line default #line hidden #line 760 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.MenuItem optionsDeveloperOptions; #line default #line hidden #line 761 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.MenuItem optionsDeveloperBackup; #line default #line hidden #line 762 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.MenuItem optionsDeveloperRestore; #line default #line hidden #line 763 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.MenuItem optionsDeveloperTagTool; #line default #line hidden #line 768 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Grid installLogGrid; #line default #line hidden #line 769 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.ScrollViewer installLogScroll; #line default #line hidden #line 770 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.TextBlock installLogBox; #line default #line hidden #line 774 "..\..\..\MainWindow.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button closeLogButton; #line default #line hidden private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/FMM;component/mainwindow.xaml", System.UriKind.Relative); #line 1 "..\..\..\MainWindow.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: #line 8 "..\..\..\MainWindow.xaml" ((FMM2.MainWindow)(target)).Loaded += new System.Windows.RoutedEventHandler(this.Window_Loaded); #line default #line hidden #line 8 "..\..\..\MainWindow.xaml" ((FMM2.MainWindow)(target)).Closing += new System.ComponentModel.CancelEventHandler(this.Window_Closing); #line default #line hidden return; case 2: this.everythingGrid = ((System.Windows.Controls.Grid)(target)); return; case 3: this.modsTabs = ((System.Windows.Controls.TabControl)(target)); #line 27 "..\..\..\MainWindow.xaml" this.modsTabs.SelectionChanged += new System.Windows.Controls.SelectionChangedEventHandler(this.tabsUpdateStatus); #line default #line hidden return; case 4: this.myModsTab = ((System.Windows.Controls.TabItem)(target)); return; case 5: this.myModsOuterGrid = ((System.Windows.Controls.Grid)(target)); return; case 6: this.myModsAlert = ((System.Windows.Controls.Grid)(target)); return; case 7: this.myModsAlertText = ((System.Windows.Controls.TextBlock)(target)); return; case 8: this.myModsAlertHide = ((System.Windows.Controls.Button)(target)); #line 37 "..\..\..\MainWindow.xaml" this.myModsAlertHide.Click += new System.Windows.RoutedEventHandler(this.myModsAlertHide_Click); #line default #line hidden return; case 9: this.myModsMenu = ((System.Windows.Controls.Grid)(target)); return; case 10: this.myModsRefreshButton = ((System.Windows.Controls.Button)(target)); #line 40 "..\..\..\MainWindow.xaml" this.myModsRefreshButton.Click += new System.Windows.RoutedEventHandler(this.refreshButton_Click); #line default #line hidden return; case 11: this.myModsStatusNumber = ((System.Windows.Controls.Primitives.StatusBarItem)(target)); return; case 12: this.myModsSearchBox = ((System.Windows.Controls.TextBox)(target)); #line 42 "..\..\..\MainWindow.xaml" this.myModsSearchBox.TextChanged += new System.Windows.Controls.TextChangedEventHandler(this.searchBox_TextChanged); #line default #line hidden return; case 13: this.myModsGrid = ((System.Windows.Controls.Grid)(target)); return; case 14: this.myModsList = ((System.Windows.Controls.ListView)(target)); #line 52 "..\..\..\MainWindow.xaml" this.myModsList.SelectionChanged += new System.Windows.Controls.SelectionChangedEventHandler(this.myModsList_SelectionChanged); #line default #line hidden #line 52 "..\..\..\MainWindow.xaml" this.myModsList.AddHandler(System.Windows.Controls.Primitives.ButtonBase.ClickEvent, new System.Windows.RoutedEventHandler(this.myModsList_HeaderClicked)); #line default #line hidden #line 52 "..\..\..\MainWindow.xaml" this.myModsList.GotFocus += new System.Windows.RoutedEventHandler(this.modsList_GotFocus); #line default #line hidden return; case 15: #line 55 "..\..\..\MainWindow.xaml" ((System.Windows.Controls.MenuItem)(target)).Click += new System.Windows.RoutedEventHandler(this.itemMark_Click); #line default #line hidden return; case 16: #line 56 "..\..\..\MainWindow.xaml" ((System.Windows.Controls.MenuItem)(target)).Click += new System.Windows.RoutedEventHandler(this.itemLocationOpen_Click); #line default #line hidden return; case 17: #line 57 "..\..\..\MainWindow.xaml" ((System.Windows.Controls.MenuItem)(target)).Click += new System.Windows.RoutedEventHandler(this.infobarDel_Click); #line default #line hidden return; case 18: this.gv1Name = ((System.Windows.Controls.GridViewColumn)(target)); return; case 19: this.gv1Author = ((System.Windows.Controls.GridViewColumn)(target)); return; case 20: this.gv1Version = ((System.Windows.Controls.GridViewColumn)(target)); return; case 21: this.gv1Description = ((System.Windows.Controls.GridViewColumn)(target)); return; case 22: this.gv1Warnings = ((System.Windows.Controls.GridViewColumn)(target)); return; case 23: this.infobar = ((System.Windows.Controls.Grid)(target)); return; case 24: this.infobarScroll = ((System.Windows.Controls.ScrollViewer)(target)); return; case 25: this.infobarPanel = ((System.Windows.Controls.StackPanel)(target)); return; case 26: this.infobarCon = ((System.Windows.Controls.ContentControl)(target)); #line 92 "..\..\..\MainWindow.xaml" this.infobarCon.MouseLeftButtonUp += new System.Windows.Input.MouseButtonEventHandler(this.infobarCon_MouseLeftButtonUp); #line default #line hidden return; case 27: this.infobarViewGrid = ((System.Windows.Controls.Grid)(target)); return; case 28: this.infobarImage = ((System.Windows.Controls.Image)(target)); return; case 29: this.infobarRect = ((System.Windows.Shapes.Rectangle)(target)); return; case 30: this.infobarHeader = ((System.Windows.Controls.StackPanel)(target)); return; case 31: this.infobarName = ((System.Windows.Controls.TextBlock)(target)); return; case 32: this.infobarAuthor = ((System.Windows.Controls.TextBlock)(target)); return; case 33: this.infobarCredits = ((System.Windows.Controls.TextBlock)(target)); return; case 34: this.infobarIcon = ((System.Windows.Controls.Image)(target)); return; case 35: this.infobarOps = ((System.Windows.Controls.StackPanel)(target)); return; case 36: this.infobarUp = ((System.Windows.Controls.Button)(target)); #line 120 "..\..\..\MainWindow.xaml" this.infobarUp.Click += new System.Windows.RoutedEventHandler(this.infobarUp_Click); #line default #line hidden return; case 37: this.infobarDn = ((System.Windows.Controls.Button)(target)); #line 125 "..\..\..\MainWindow.xaml" this.infobarDn.Click += new System.Windows.RoutedEventHandler(this.infobarDn_Click); #line default #line hidden return; case 38: this.infobarDelete = ((System.Windows.Controls.Button)(target)); #line 130 "..\..\..\MainWindow.xaml" this.infobarDelete.Click += new System.Windows.RoutedEventHandler(this.infobarDel_Click); #line default #line hidden return; case 39: this.infobarRevisionDate = ((System.Windows.Controls.TextBlock)(target)); return; case 40: this.infobarEDVersion = ((System.Windows.Controls.TextBlock)(target)); return; case 41: this.infobarDescription = ((System.Windows.Controls.TextBlock)(target)); return; case 42: this.infobarWarnings = ((System.Windows.Controls.TextBlock)(target)); return; case 43: this.infobarApply = ((System.Windows.Controls.Button)(target)); #line 156 "..\..\..\MainWindow.xaml" this.infobarApply.Click += new System.Windows.RoutedEventHandler(this.infobarApply_Click); #line default #line hidden return; case 44: this.downloadableModsTab = ((System.Windows.Controls.TabItem)(target)); return; case 45: this.downloadableModsOuterGrid = ((System.Windows.Controls.Grid)(target)); return; case 46: this.downloadableModsAlert = ((System.Windows.Controls.Grid)(target)); return; case 47: this.downloadableModsAlertText = ((System.Windows.Controls.TextBlock)(target)); return; case 48: this.downloadableModsAlertHide = ((System.Windows.Controls.Button)(target)); #line 170 "..\..\..\MainWindow.xaml" this.downloadableModsAlertHide.Click += new System.Windows.RoutedEventHandler(this.downloadableModsAlertHide_Click); #line default #line hidden return; case 49: this.downloadableModsMenu = ((System.Windows.Controls.Grid)(target)); return; case 50: this.dlModsRefreshButton = ((System.Windows.Controls.Button)(target)); #line 173 "..\..\..\MainWindow.xaml" this.dlModsRefreshButton.Click += new System.Windows.RoutedEventHandler(this.refreshButton_Click); #line default #line hidden return; case 51: this.dlModsStatusNumber = ((System.Windows.Controls.Primitives.StatusBarItem)(target)); return; case 52: this.dlModsSearchBox = ((System.Windows.Controls.TextBox)(target)); #line 175 "..\..\..\MainWindow.xaml" this.dlModsSearchBox.TextChanged += new System.Windows.Controls.TextChangedEventHandler(this.searchBox_TextChanged); #line default #line hidden return; case 53: this.downloadableModsGrid = ((System.Windows.Controls.Grid)(target)); return; case 54: this.downloadableModsList = ((System.Windows.Controls.ListView)(target)); #line 183 "..\..\..\MainWindow.xaml" this.downloadableModsList.SelectionChanged += new System.Windows.Controls.SelectionChangedEventHandler(this.downloadableModsList_SelectionChanged); #line default #line hidden #line 183 "..\..\..\MainWindow.xaml" this.downloadableModsList.AddHandler(System.Windows.Controls.Primitives.ButtonBase.ClickEvent, new System.Windows.RoutedEventHandler(this.downloadableModsList_HeaderClicked)); #line default #line hidden #line 183 "..\..\..\MainWindow.xaml" this.downloadableModsList.GotFocus += new System.Windows.RoutedEventHandler(this.modsList_GotFocus); #line default #line hidden return; case 55: this.gv2Name = ((System.Windows.Controls.GridViewColumn)(target)); return; case 56: this.gv2Author = ((System.Windows.Controls.GridViewColumn)(target)); return; case 57: this.gv2Version = ((System.Windows.Controls.GridViewColumn)(target)); return; case 58: this.gv2Description = ((System.Windows.Controls.GridViewColumn)(target)); return; case 59: this.gv2Warnings = ((System.Windows.Controls.GridViewColumn)(target)); return; case 60: this.infobarDL = ((System.Windows.Controls.Grid)(target)); return; case 61: this.infobarDLScroll = ((System.Windows.Controls.ScrollViewer)(target)); return; case 62: this.infobarDLPanel = ((System.Windows.Controls.StackPanel)(target)); return; case 63: this.infobarDLCon = ((System.Windows.Controls.ContentControl)(target)); #line 215 "..\..\..\MainWindow.xaml" this.infobarDLCon.MouseLeftButtonUp += new System.Windows.Input.MouseButtonEventHandler(this.infobarCon_MouseLeftButtonUp); #line default #line hidden return; case 64: this.infobarDLViewGrid = ((System.Windows.Controls.Grid)(target)); return; case 65: this.infobarDLImage = ((System.Windows.Controls.Image)(target)); return; case 66: this.infobarDLRect = ((System.Windows.Shapes.Rectangle)(target)); return; case 67: this.infobarDLHeader = ((System.Windows.Controls.StackPanel)(target)); return; case 68: this.infobarDLName = ((System.Windows.Controls.TextBlock)(target)); return; case 69: this.infobarDLAuthor = ((System.Windows.Controls.TextBlock)(target)); return; case 70: this.infobarDLCredits = ((System.Windows.Controls.TextBlock)(target)); return; case 71: this.infobarDLIcon = ((System.Windows.Controls.Image)(target)); return; case 72: this.infobarDLRevisionDate = ((System.Windows.Controls.TextBlock)(target)); return; case 73: this.infobarDLEDVersion = ((System.Windows.Controls.TextBlock)(target)); return; case 74: this.infobarDLDescription = ((System.Windows.Controls.TextBlock)(target)); return; case 75: this.infobarDLWarnings = ((System.Windows.Controls.TextBlock)(target)); return; case 76: this.infobarDLDownload = ((System.Windows.Controls.Button)(target)); #line 262 "..\..\..\MainWindow.xaml" this.infobarDLDownload.Click += new System.Windows.RoutedEventHandler(this.infobarDLDownload_Click); #line default #line hidden return; case 77: this.menu = ((System.Windows.Controls.Menu)(target)); return; case 78: this.file = ((System.Windows.Controls.MenuItem)(target)); return; case 79: this.fileAbout = ((System.Windows.Controls.MenuItem)(target)); #line 738 "..\..\..\MainWindow.xaml" this.fileAbout.Click += new System.Windows.RoutedEventHandler(this.fileAbout_Click); #line default #line hidden return; case 80: this.fileExit = ((System.Windows.Controls.MenuItem)(target)); #line 740 "..\..\..\MainWindow.xaml" this.fileExit.Click += new System.Windows.RoutedEventHandler(this.fileExit_Click); #line default #line hidden return; case 81: this.options = ((System.Windows.Controls.MenuItem)(target)); return; case 82: this.optionsOrder = ((System.Windows.Controls.MenuItem)(target)); return; case 83: this.optionsOrderList = ((System.Windows.Controls.MenuItem)(target)); #line 753 "..\..\..\MainWindow.xaml" this.optionsOrderList.Click += new System.Windows.RoutedEventHandler(this.optionsOrderList_Click); #line default #line hidden return; case 84: this.optionsOrderPriority = ((System.Windows.Controls.MenuItem)(target)); #line 754 "..\..\..\MainWindow.xaml" this.optionsOrderPriority.Click += new System.Windows.RoutedEventHandler(this.optionsOrderPriority_Click); #line default #line hidden return; case 85: this.optionsOffline = ((System.Windows.Controls.MenuItem)(target)); #line 757 "..\..\..\MainWindow.xaml" this.optionsOffline.Click += new System.Windows.RoutedEventHandler(this.optionsOffline_Click); #line default #line hidden return; case 86: this.optionsDeveloper = ((System.Windows.Controls.MenuItem)(target)); #line 758 "..\..\..\MainWindow.xaml" this.optionsDeveloper.Click += new System.Windows.RoutedEventHandler(this.optionsDeveloper_Click); #line default #line hidden return; case 87: this.optionsDeveloperSeparator = ((System.Windows.Controls.Separator)(target)); return; case 88: this.optionsDeveloperOptions = ((System.Windows.Controls.MenuItem)(target)); return; case 89: this.optionsDeveloperBackup = ((System.Windows.Controls.MenuItem)(target)); #line 761 "..\..\..\MainWindow.xaml" this.optionsDeveloperBackup.Click += new System.Windows.RoutedEventHandler(this.optionsDeveloperBackup_Click); #line default #line hidden return; case 90: this.optionsDeveloperRestore = ((System.Windows.Controls.MenuItem)(target)); #line 762 "..\..\..\MainWindow.xaml" this.optionsDeveloperRestore.Click += new System.Windows.RoutedEventHandler(this.optionsDeveloperRestore_Click); #line default #line hidden return; case 91: this.optionsDeveloperTagTool = ((System.Windows.Controls.MenuItem)(target)); #line 763 "..\..\..\MainWindow.xaml" this.optionsDeveloperTagTool.Click += new System.Windows.RoutedEventHandler(this.optionsDeveloperTagTool_Click); #line default #line hidden return; case 92: this.installLogGrid = ((System.Windows.Controls.Grid)(target)); return; case 93: this.installLogScroll = ((System.Windows.Controls.ScrollViewer)(target)); #line 769 "..\..\..\MainWindow.xaml" this.installLogScroll.ScrollChanged += new System.Windows.Controls.ScrollChangedEventHandler(this.installLogScroll_ScrollChanged); #line default #line hidden return; case 94: this.installLogBox = ((System.Windows.Controls.TextBlock)(target)); return; case 95: this.closeLogButton = ((System.Windows.Controls.Button)(target)); #line 774 "..\..\..\MainWindow.xaml" this.closeLogButton.Click += new System.Windows.RoutedEventHandler(this.closeLogButton_Click); #line default #line hidden return; } this._contentLoaded = true; } } }
40.269939
188
0.585733
[ "MIT" ]
Thanknandwilson/FMM2
FMM2/obj/x86/Debug/MainWindow.g.i.cs
52,514
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _3EqualNumbers { class Program { static void Main(string[] args) { var num1 = double.Parse(Console.ReadLine()); var num2 = double.Parse(Console.ReadLine()); var num3 = double.Parse(Console.ReadLine()); if (num1 == num2 && num2 == num3) { Console.WriteLine("yes"); } else { Console.WriteLine("no"); } } } }
22.62963
56
0.510638
[ "MIT" ]
Plotso/SoftUni
Programming Basics/SimpleConditionsHomeEdition/3EqualNumbers/3EqualNumbers.cs
613
C#
using System.Collections.Generic; namespace GenericEvolutionaryFramework { interface ISelector { IPopulationMember SelectMembersFromPopulation(List<IPopulationMember> population); List<IPopulationMember> SelectMembersFromPopulation(List<IPopulationMember> population, int number); void Sort(List<IPopulationMember> members); void Sort(); } }
29.846154
108
0.75
[ "MIT" ]
OliverBathurst/GenericEvolutionaryFramework
GenericEvolutionaryFramework/Interfaces/ISelector.cs
390
C#
/* * WebAPI - Area Management * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: management * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = IO.Swagger.Management.Client.SwaggerDateConverter; namespace IO.Swagger.Management.Model { /// <summary> /// Class for additional field of type MultiValue /// </summary> [DataContract] public partial class AdditionalFieldManagementMultivalueDTO : AdditionalFieldManagementBaseDTO, IEquatable<AdditionalFieldManagementMultivalueDTO>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="AdditionalFieldManagementMultivalueDTO" /> class. /// </summary> [JsonConstructorAttribute] protected AdditionalFieldManagementMultivalueDTO() { } /// <summary> /// Initializes a new instance of the <see cref="AdditionalFieldManagementMultivalueDTO" /> class. /// </summary> /// <param name="dataGroup">Data group.</param> /// <param name="numMaxChar">Maximum number of characters.</param> /// <param name="limitToList">Possible values​limited to the list.</param> /// <param name="autoinsert">Automatic insert.</param> /// <param name="autocomplete">Autocomplete.</param> /// <param name="autocompleteCharacter">Autocomplete character.</param> /// <param name="autocompleteAlign">Possible values: 0: Left 1: Right -1: None .</param> /// <param name="locked">Field locked (readonly).</param> public AdditionalFieldManagementMultivalueDTO(DataGroupSimpleDTO dataGroup = default(DataGroupSimpleDTO), int? numMaxChar = default(int?), bool? limitToList = default(bool?), bool? autoinsert = default(bool?), bool? autocomplete = default(bool?), string autocompleteCharacter = default(string), int? autocompleteAlign = default(int?), bool? locked = default(bool?), string className = "AdditionalFieldManagementMultivalueDTO", string key = default(string), string description = default(string), FieldGroupSimpleDTO fieldGroup = default(FieldGroupSimpleDTO), DocumentTypeSimpleDTO documentType = default(DocumentTypeSimpleDTO), string referenceId = default(string), int? order = default(int?), bool? required = default(bool?), bool? visible = default(bool?), string externalId = default(string), string formula = default(string), List<AdditionalFieldManagementTranslationDTO> translations = default(List<AdditionalFieldManagementTranslationDTO>)) : base(className, key, description, fieldGroup, documentType, referenceId, order, required, visible, externalId, formula, translations) { this.DataGroup = dataGroup; this.NumMaxChar = numMaxChar; this.LimitToList = limitToList; this.Autoinsert = autoinsert; this.Autocomplete = autocomplete; this.AutocompleteCharacter = autocompleteCharacter; this.AutocompleteAlign = autocompleteAlign; this.Locked = locked; } /// <summary> /// Data group /// </summary> /// <value>Data group</value> [DataMember(Name="dataGroup", EmitDefaultValue=false)] public DataGroupSimpleDTO DataGroup { get; set; } /// <summary> /// Maximum number of characters /// </summary> /// <value>Maximum number of characters</value> [DataMember(Name="numMaxChar", EmitDefaultValue=false)] public int? NumMaxChar { get; set; } /// <summary> /// Possible values​limited to the list /// </summary> /// <value>Possible values​limited to the list</value> [DataMember(Name="limitToList", EmitDefaultValue=false)] public bool? LimitToList { get; set; } /// <summary> /// Automatic insert /// </summary> /// <value>Automatic insert</value> [DataMember(Name="autoinsert", EmitDefaultValue=false)] public bool? Autoinsert { get; set; } /// <summary> /// Autocomplete /// </summary> /// <value>Autocomplete</value> [DataMember(Name="autocomplete", EmitDefaultValue=false)] public bool? Autocomplete { get; set; } /// <summary> /// Autocomplete character /// </summary> /// <value>Autocomplete character</value> [DataMember(Name="autocompleteCharacter", EmitDefaultValue=false)] public string AutocompleteCharacter { get; set; } /// <summary> /// Possible values: 0: Left 1: Right -1: None /// </summary> /// <value>Possible values: 0: Left 1: Right -1: None </value> [DataMember(Name="autocompleteAlign", EmitDefaultValue=false)] public int? AutocompleteAlign { get; set; } /// <summary> /// Field locked (readonly) /// </summary> /// <value>Field locked (readonly)</value> [DataMember(Name="locked", EmitDefaultValue=false)] public bool? Locked { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class AdditionalFieldManagementMultivalueDTO {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" DataGroup: ").Append(DataGroup).Append("\n"); sb.Append(" NumMaxChar: ").Append(NumMaxChar).Append("\n"); sb.Append(" LimitToList: ").Append(LimitToList).Append("\n"); sb.Append(" Autoinsert: ").Append(Autoinsert).Append("\n"); sb.Append(" Autocomplete: ").Append(Autocomplete).Append("\n"); sb.Append(" AutocompleteCharacter: ").Append(AutocompleteCharacter).Append("\n"); sb.Append(" AutocompleteAlign: ").Append(AutocompleteAlign).Append("\n"); sb.Append(" Locked: ").Append(Locked).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 override string ToJson() { return JsonConvert.SerializeObject(this, 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 AdditionalFieldManagementMultivalueDTO); } /// <summary> /// Returns true if AdditionalFieldManagementMultivalueDTO instances are equal /// </summary> /// <param name="input">Instance of AdditionalFieldManagementMultivalueDTO to be compared</param> /// <returns>Boolean</returns> public bool Equals(AdditionalFieldManagementMultivalueDTO input) { if (input == null) return false; return base.Equals(input) && ( this.DataGroup == input.DataGroup || (this.DataGroup != null && this.DataGroup.Equals(input.DataGroup)) ) && base.Equals(input) && ( this.NumMaxChar == input.NumMaxChar || (this.NumMaxChar != null && this.NumMaxChar.Equals(input.NumMaxChar)) ) && base.Equals(input) && ( this.LimitToList == input.LimitToList || (this.LimitToList != null && this.LimitToList.Equals(input.LimitToList)) ) && base.Equals(input) && ( this.Autoinsert == input.Autoinsert || (this.Autoinsert != null && this.Autoinsert.Equals(input.Autoinsert)) ) && base.Equals(input) && ( this.Autocomplete == input.Autocomplete || (this.Autocomplete != null && this.Autocomplete.Equals(input.Autocomplete)) ) && base.Equals(input) && ( this.AutocompleteCharacter == input.AutocompleteCharacter || (this.AutocompleteCharacter != null && this.AutocompleteCharacter.Equals(input.AutocompleteCharacter)) ) && base.Equals(input) && ( this.AutocompleteAlign == input.AutocompleteAlign || (this.AutocompleteAlign != null && this.AutocompleteAlign.Equals(input.AutocompleteAlign)) ) && base.Equals(input) && ( this.Locked == input.Locked || (this.Locked != null && this.Locked.Equals(input.Locked)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = base.GetHashCode(); if (this.DataGroup != null) hashCode = hashCode * 59 + this.DataGroup.GetHashCode(); if (this.NumMaxChar != null) hashCode = hashCode * 59 + this.NumMaxChar.GetHashCode(); if (this.LimitToList != null) hashCode = hashCode * 59 + this.LimitToList.GetHashCode(); if (this.Autoinsert != null) hashCode = hashCode * 59 + this.Autoinsert.GetHashCode(); if (this.Autocomplete != null) hashCode = hashCode * 59 + this.Autocomplete.GetHashCode(); if (this.AutocompleteCharacter != null) hashCode = hashCode * 59 + this.AutocompleteCharacter.GetHashCode(); if (this.AutocompleteAlign != null) hashCode = hashCode * 59 + this.AutocompleteAlign.GetHashCode(); if (this.Locked != null) hashCode = hashCode * 59 + this.Locked.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { foreach(var x in BaseValidate(validationContext)) yield return x; yield break; } } }
45.607143
1,089
0.589228
[ "Apache-2.0" ]
zanardini/ARXivarNext-WebApi
ARXivarNext-ConsumingWebApi/IO.Swagger.Management/Model/AdditionalFieldManagementMultivalueDTO.cs
11,499
C#
// <auto-generated /> using System; using AngularProject.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace AngularProject.Migrations { [DbContext(typeof(AngularProjectDbContext))] [Migration("20190703062215_Upgraded_To_Abp_4_7_0")] partial class Upgraded_To_Abp_4_7_0 { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.4-servicing-10062") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Abp.Application.Editions.Edition", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32); b.HasKey("Id"); b.ToTable("AbpEditions"); }); modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Discriminator") .IsRequired(); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.Property<string>("Value") .IsRequired() .HasMaxLength(2000); b.HasKey("Id"); b.ToTable("AbpFeatures"); b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting"); }); modelBuilder.Entity("Abp.Auditing.AuditLog", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BrowserInfo") .HasMaxLength(512); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<string>("CustomData") .HasMaxLength(2000); b.Property<string>("Exception") .HasMaxLength(2000); b.Property<int>("ExecutionDuration"); b.Property<DateTime>("ExecutionTime"); b.Property<int?>("ImpersonatorTenantId"); b.Property<long?>("ImpersonatorUserId"); b.Property<string>("MethodName") .HasMaxLength(256); b.Property<string>("Parameters") .HasMaxLength(1024); b.Property<string>("ReturnValue"); b.Property<string>("ServiceName") .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionDuration"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Abp.Authorization.PermissionSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Discriminator") .IsRequired(); b.Property<bool>("IsGranted"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpPermissions"); b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasMaxLength(256); b.Property<string>("ClaimValue"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int>("RoleId"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("EmailAddress") .HasMaxLength(256); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.Property<long?>("UserLinkId"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("EmailAddress"); b.HasIndex("UserName"); b.HasIndex("TenantId", "EmailAddress"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "UserName"); b.ToTable("AbpUserAccounts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasMaxLength(256); b.Property<string>("ClaimValue"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("LoginProvider") .IsRequired() .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BrowserInfo") .HasMaxLength(512); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<byte>("Result"); b.Property<string>("TenancyName") .HasMaxLength(64); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.Property<string>("UserNameOrEmailAddress") .HasMaxLength(255); b.HasKey("Id"); b.HasIndex("UserId", "TenantId"); b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result"); b.ToTable("AbpUserLoginAttempts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<bool>("IsDeleted"); b.Property<long>("OrganizationUnitId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int>("RoleId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "RoleId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime?>("ExpireDate"); b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("Name") .HasMaxLength(128); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.Property<string>("Value") .HasMaxLength(512); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<bool>("IsAbandoned"); b.Property<string>("JobArgs") .IsRequired() .HasMaxLength(1048576); b.Property<string>("JobType") .IsRequired() .HasMaxLength(512); b.Property<DateTime?>("LastTryTime"); b.Property<DateTime>("NextTryTime"); b.Property<byte>("Priority"); b.Property<short>("TryCount"); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.Property<string>("Value") .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "Name", "UserId") .IsUnique(); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChange", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("ChangeTime"); b.Property<byte>("ChangeType"); b.Property<long>("EntityChangeSetId"); b.Property<string>("EntityId") .HasMaxLength(48); b.Property<string>("EntityTypeFullName") .HasMaxLength(192); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("EntityChangeSetId"); b.HasIndex("EntityTypeFullName", "EntityId"); b.ToTable("AbpEntityChanges"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChangeSet", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BrowserInfo") .HasMaxLength(512); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<string>("ExtensionData"); b.Property<int?>("ImpersonatorTenantId"); b.Property<long?>("ImpersonatorUserId"); b.Property<string>("Reason") .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "CreationTime"); b.HasIndex("TenantId", "Reason"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpEntityChangeSets"); }); modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<long>("EntityChangeId"); b.Property<string>("NewValue") .HasMaxLength(512); b.Property<string>("OriginalValue") .HasMaxLength(512); b.Property<string>("PropertyName") .HasMaxLength(96); b.Property<string>("PropertyTypeFullName") .HasMaxLength(192); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("EntityChangeId"); b.ToTable("AbpEntityPropertyChanges"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<string>("Icon") .HasMaxLength(128); b.Property<bool>("IsDeleted"); b.Property<bool>("IsDisabled"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(10); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpLanguages"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Key") .IsRequired() .HasMaxLength(256); b.Property<string>("LanguageName") .IsRequired() .HasMaxLength(10); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Source") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.Property<string>("Value") .IsRequired() .HasMaxLength(67108864); b.HasKey("Id"); b.HasIndex("TenantId", "Source", "LanguageName", "Key"); b.ToTable("AbpLanguageTexts"); }); modelBuilder.Entity("Abp.Notifications.NotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Data") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasMaxLength(512); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("ExcludedUserIds") .HasMaxLength(131072); b.Property<string>("NotificationName") .IsRequired() .HasMaxLength(96); b.Property<byte>("Severity"); b.Property<string>("TenantIds") .HasMaxLength(131072); b.Property<string>("UserIds") .HasMaxLength(131072); b.HasKey("Id"); b.ToTable("AbpNotifications"); }); modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("NotificationName") .HasMaxLength(96); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId"); b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId"); b.ToTable("AbpNotificationSubscriptions"); }); modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Data") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasMaxLength(512); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("NotificationName") .IsRequired() .HasMaxLength(96); b.Property<byte>("Severity"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId"); b.ToTable("AbpTenantNotifications"); }); modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<int>("State"); b.Property<int?>("TenantId"); b.Property<Guid>("TenantNotificationId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId", "State", "CreationTime"); b.ToTable("AbpUserNotifications"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Code") .IsRequired() .HasMaxLength(95); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(128); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<long?>("ParentId"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("ParentId"); b.HasIndex("TenantId", "Code"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnitRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<bool>("IsDeleted"); b.Property<long>("OrganizationUnitId"); b.Property<int>("RoleId"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "RoleId"); b.ToTable("AbpOrganizationUnitRoles"); }); modelBuilder.Entity("AngularProject.Authorization.Roles.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("Description") .HasMaxLength(5000); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<bool>("IsDefault"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsStatic"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32); b.Property<string>("NormalizedName") .IsRequired() .HasMaxLength(32); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("AngularProject.Authorization.Users.User", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("AccessFailedCount"); b.Property<string>("AuthenticationSource") .HasMaxLength(64); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("EmailAddress") .IsRequired() .HasMaxLength(256); b.Property<string>("EmailConfirmationCode") .HasMaxLength(328); b.Property<bool>("IsActive"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsEmailConfirmed"); b.Property<bool>("IsLockoutEnabled"); b.Property<bool>("IsPhoneNumberConfirmed"); b.Property<bool>("IsTwoFactorEnabled"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<DateTime?>("LockoutEndDateUtc"); b.Property<string>("Name") .IsRequired() .HasMaxLength(64); b.Property<string>("NormalizedEmailAddress") .IsRequired() .HasMaxLength(256); b.Property<string>("NormalizedUserName") .IsRequired() .HasMaxLength(256); b.Property<string>("Password") .IsRequired() .HasMaxLength(128); b.Property<string>("PasswordResetCode") .HasMaxLength(328); b.Property<string>("PhoneNumber") .HasMaxLength(32); b.Property<string>("SecurityStamp") .HasMaxLength(128); b.Property<string>("Surname") .IsRequired() .HasMaxLength(64); b.Property<int?>("TenantId"); b.Property<string>("UserName") .IsRequired() .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedEmailAddress"); b.HasIndex("TenantId", "NormalizedUserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("AngularProject.MultiTenancy.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ConnectionString") .HasMaxLength(1024); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int?>("EditionId"); b.Property<bool>("IsActive"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<string>("TenancyName") .IsRequired() .HasMaxLength(64); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("EditionId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenancyName"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("EditionId"); b.HasIndex("EditionId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("EditionFeatureSetting"); }); modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("TenantFeatureSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<int>("RoleId"); b.HasIndex("RoleId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("RolePermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<long>("UserId"); b.HasIndex("UserId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("UserPermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.HasOne("AngularProject.Authorization.Roles.Role") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.HasOne("AngularProject.Authorization.Users.User") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.HasOne("AngularProject.Authorization.Users.User") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.HasOne("AngularProject.Authorization.Users.User") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.HasOne("AngularProject.Authorization.Users.User") .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.HasOne("AngularProject.Authorization.Users.User") .WithMany("Settings") .HasForeignKey("UserId"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChange", b => { b.HasOne("Abp.EntityHistory.EntityChangeSet") .WithMany("EntityChanges") .HasForeignKey("EntityChangeSetId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b => { b.HasOne("Abp.EntityHistory.EntityChange") .WithMany("PropertyChanges") .HasForeignKey("EntityChangeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.HasOne("Abp.Organizations.OrganizationUnit", "Parent") .WithMany("Children") .HasForeignKey("ParentId"); }); modelBuilder.Entity("AngularProject.Authorization.Roles.Role", b => { b.HasOne("AngularProject.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("AngularProject.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("AngularProject.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("AngularProject.Authorization.Users.User", b => { b.HasOne("AngularProject.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("AngularProject.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("AngularProject.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("AngularProject.MultiTenancy.Tenant", b => { b.HasOne("AngularProject.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("AngularProject.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId"); b.HasOne("AngularProject.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasOne("AngularProject.Authorization.Roles.Role") .WithMany("Permissions") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasOne("AngularProject.Authorization.Users.User") .WithMany("Permissions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
33.703502
125
0.462029
[ "MIT" ]
macupryk/AngularTemplate
src/AngularProject.EntityFrameworkCore/Migrations/20190703062215_Upgraded_To_Abp_4_7_0.Designer.cs
43,311
C#
//-------------------------------------------------- // <copyright file="WebServiceUnitTestSteps.cs" company="Magenic"> // Copyright 2021 Magenic, All rights Reserved // </copyright> // <summary>TestSteps class that inherits from BaseWebServiceTestSteps</summary> //-------------------------------------------------- using Magenic.Maqs.BaseWebServiceTest; using Magenic.Maqs.SpecFlow.TestSteps; using NUnit.Framework; using TechTalk.SpecFlow; namespace SpecFlowExtensionNUnitTests.Steps { /// <summary> /// BaseWebService unit test steps /// </summary> [Binding] public class WebServiceUnitTestSteps : BaseWebServiceTestSteps { /// <summary> /// Initializes a new instance of the <see cref="WebServiceUnitTestSteps" /> class /// </summary> /// <param name="context">The context to pass to the base class</param> protected WebServiceUnitTestSteps(ScenarioContext context) : base(context) { } /// <summary> /// Class is instantiated /// </summary> [Given(@"class BaseWebServiceTestSteps")] public void GivenClassBaseWebServiceTestSteps() { Assert.IsNotNull(this); } /// <summary> /// Test object exists /// </summary> [Then(@"BaseWebServiceTestSteps TestObject is not null")] public void ThenBaseWebServiceTestStepsTestObjectIsNotNull() { Assert.IsNotNull(this.TestObject, "TestObject for BaseWebServiceTestSteps class is null."); } /// <summary> /// Test object exists /// </summary> [Then(@"TestObject is type WebServiceTestObject")] public void ThenTestObjectIsTypeWebServiceTestObject() { Assert.IsTrue(this.TestObject.GetType().Equals(typeof(WebServiceTestObject)), $"TestObject for BaseWebServiceTestSteps class is the wrong type : {this.TestObject.GetType()}."); } /// <summary> /// ScenarioContext exists /// </summary> [Then(@"BaseWebServiceTestSteps ScenarioContext is not null")] public void ThenScenarioContextIsNotNull() { Assert.IsNotNull(this.LocalScenarioContext, "LocalScenarioContext for BaseWebServiceTestSteps class is null."); } /// <summary> /// ScenarioContext is valid /// </summary> [Then(@"BaseWebServiceTestSteps ScenarioContext is type ScenarioContext")] public void AndScenarioContextIsTypeScenarioContext() { Assert.IsTrue(this.LocalScenarioContext.GetType().Equals(typeof(ScenarioContext)), $"LocalScenarioContext for BaseWebServiceTestSteps class is the wrong type : {this.LocalScenarioContext.GetType()}."); } /// <summary> /// WebServiceDriver exists /// </summary> [Then(@"BaseWebServiceTestSteps WebServiceDriver is not null")] public void ThenWebDriverIsNotNull() { Assert.IsNotNull(this.TestObject.WebServiceDriver, "WebServiceDriver for BaseWebServiceTestSteps class is null."); } /// <summary> /// WebServiceDriver exists /// </summary> [Then(@"BaseWebServiceTestSteps WebServiceDriver is type EventFiringWebServiceDriver")] public void AndWebDriverIsTypeWebServiceDriver() { Assert.IsTrue(this.TestObject.WebServiceDriver.GetType().Equals(typeof(EventFiringWebServiceDriver)), $"WebServiceDriver for BaseWebServiceTestSteps class is the wrong type : {this.TestObject.WebServiceDriver.GetType()}."); } } }
39.282609
235
0.636967
[ "MIT" ]
CoryJHolland/MAQS
Framework/SpecFlowExtensionNUnitTests/Steps/WebServiceUnitTestSteps.cs
3,616
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; //对象的移动路径信息 class ObjWaysData : IBinaryReader { public int pos_idx; public float[] pos_arr; public int[] trype_arr; //public ObjSpeedData speed; public void ReadBinary() { } } public class ObjSpeedData : IBinaryReader { public float speed; public long su_expire; public float su_speed; //米/毫秒 public float su_stop_x; //如果su_speed = 0, 则表示停止精确的坐标 public float su_stop_y; public void ReadBinary() { } } // 对象移动信息 public class ObjMoveData : IBinaryReader { public int scene_ins_id; public int aoi_id; public byte ssid; // 序列号 // move public int move_type; public float[] pos_arr; public void ReadBinary() { } } /// <summary> /// 对象停止 /// </summary> public class ObjStopData : IBinaryReader { public int scene_ins_id; public int aoi_id; public float x; public float y; public void ReadBinary() { } }
17.1
60
0.662768
[ "MIT" ]
bailang00/UFM
Assets/GamePlugins/core/obj/data/ObjWaysData.cs
1,102
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StudentInfoSystem { public class StudentData { static private List<Student> _testStudent; static public List<Student> TestStudent { get { PopulateTestData(); return _testStudent; } private set { } } static private void PopulateTestData() { _testStudent = new List<Student>(3); for (int i = 0; i < 3; i++) { _testStudent.Add(new Student()); } _testStudent[0].Name = "Georgi"; _testStudent[0].MiddleName = "Georgiev"; _testStudent[0].LastName = "Sergiev"; _testStudent[0].Faculty = "FKST"; _testStudent[0].Course = "KSI"; _testStudent[0].Degree = "Bachelor"; _testStudent[0].Status = "Regular"; _testStudent[0].FacNum = "121217109"; _testStudent[0].Year = 3; _testStudent[0].Flow = 9; _testStudent[0].Group = 36; _testStudent[1].Name = "Pencho"; _testStudent[1].MiddleName = "Hristianov"; _testStudent[1].LastName = "Peshev"; _testStudent[1].Faculty = "FKST"; _testStudent[1].Course = "KSI"; _testStudent[1].Degree = "Bachelor"; _testStudent[1].Status = "Regular"; _testStudent[1].FacNum = "121217888"; _testStudent[1].Year = 2; _testStudent[1].Flow = 4; _testStudent[1].Group = 26; _testStudent[2].Name = "Atanas"; _testStudent[2].MiddleName = "Penchev"; _testStudent[2].LastName = "Penchev"; _testStudent[2].Faculty = "FKST"; _testStudent[2].Course = "KSI"; _testStudent[2].Degree = "Bachelor"; _testStudent[2].Status = "Regular"; _testStudent[2].FacNum = "121217898"; _testStudent[2].Year = 1; _testStudent[2].Flow = 7; _testStudent[2].Group = 16; } } }
33.936508
60
0.538354
[ "MIT" ]
GeorgeSergiev/Kursova-PS
FirstEx_36_GK/StudentInfoSystem/StudentData.cs
2,140
C#