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 |
|---|---|---|---|---|---|---|---|---|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Scaffolding.Internal;
using Xunit;
namespace Microsoft.EntityFrameworkCore
{
public class CSharpNamerTest
{
[Theory]
[InlineData("Name with space", "Name_with_space")]
[InlineData("namespace", "_namespace")]
[InlineData("@namespace", "@namespace")]
[InlineData("8ball", "_8ball")]
public void Sanitizes_name_with_no_singularize_or_pluralize(string input, string output)
{
Assert.Equal(output, new CSharpNamer<string>(s => s, new CSharpUtilities(), null).GetName(input));
}
[Theory]
[InlineData("Name ending with s", "Name_ending_with_")]
[InlineData("Name with no s at end", "Name_with_no_s_at_end")]
public void Sanitizes_name_with_singularizer(string input, string output)
{
var fakePluralizer = new RelationalDatabaseModelFactoryTest.FakePluralizer();
Assert.Equal(output, new CSharpNamer<string>(s => s, new CSharpUtilities(), fakePluralizer.Singularize).GetName(input));
}
[Theory]
[InlineData("Name ending with s", "Name_ending_with_s")]
[InlineData("Name with no s at end", "Name_with_no_s_at_ends")]
public void Sanitizes_name_with_pluralizer(string input, string output)
{
var fakePluralizer = new RelationalDatabaseModelFactoryTest.FakePluralizer();
Assert.Equal(output, new CSharpNamer<string>(s => s, new CSharpUtilities(), fakePluralizer.Pluralize).GetName(input));
}
}
}
| 43.170732 | 132 | 0.684181 | [
"Apache-2.0"
] | Wrank/EntityFrameworkCore | test/EFCore.Design.Tests/Scaffolding/Internal/CSharpNamerTest.cs | 1,770 | C# |
// System.EnterpriseServices.Internal.GenerateMetadata.cs
//
// Author: Mike Kestner (mkestner@ximian.com)
//
// Copyright (C) 2004 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Reflection;
using System.Runtime.InteropServices;
namespace System.EnterpriseServices.Internal
{
#if NET_1_1
[Guid("d8013ff1-730b-45e2-ba24-874b7242c425")]
public class GenerateMetadata : IComSoapMetadata {
[MonoTODO]
public GenerateMetadata ()
{
throw new NotImplementedException ();
}
[MonoTODO]
public string Generate (string strSrcTypeLib, string outPath)
{
throw new NotImplementedException ();
}
[MonoTODO]
public string GenerateMetaData (string strSrcTypeLib, string outPath, byte[] PublicKey, StrongNameKeyPair KeyPair)
{
throw new NotImplementedException ();
}
[MonoTODO]
public string GenerateSigned (string strSrcTypeLib, string outPath, bool InstallGac, out string Error)
{
throw new NotImplementedException ();
}
[MonoTODO]
public static int SearchPath (string path, string fileName, string extension, int numBufferChars, string buffer, int[] filePart)
{
throw new NotImplementedException ();
}
}
#endif
}
| 31.577465 | 130 | 0.752899 | [
"Apache-2.0"
] | CRivlaldo/mono | mcs/class/System.EnterpriseServices/System.EnterpriseServices.Internal/GenerateMetadata.cs | 2,242 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WechatSDK
{
public class WXSDK
{
private API.WXAPI api = new API.WXAPI();
private Action<byte[]> CBLogin;
private Func<UserRequest, bool> CBUserRequest;
private Action<UserMessage> CBUserMessage;
public WXSDK()
{
}
public void DoJob()
{
while (api.IsLogin)
{
var state = api.synccheck();
api.webwxsync();
if (state == "2")
{
foreach (var item in api.webWXSync.AddMsgList)
{
if (item.MsgType == 1)
{
var u = api.webWXGetContact.MemberList.Where(m => m.UserName == item.FromUserName).FirstOrDefault();
if (u != null)
{
if (this.CBUserMessage != null)
{
this.CBUserMessage(new UserMessage() { User = new UserInfo(u), Message = item.Content });
}
}
api.webwxstatusnotify(api.webWXInit.User.UserName, item.FromUserName, 1);
}
else if (item.MsgType == 37)
{
if (CBUserRequest != null)
{
if (CBUserRequest(new UserRequest() { NickName = item.RecommendInfo.NickName, Id = item.RecommendInfo.UserName, City = item.RecommendInfo.City }))
{
api.webwxverifyuser(item.RecommendInfo);
api.webwxgetcontact();
}
}
}
}
}
Thread.Sleep(1000);
}
}
public void OnUserRequest(Func<UserRequest, bool> callback)
{
this.CBUserRequest = callback;
}
public void OnUserMessage(Action<UserMessage> callback)
{
this.CBUserMessage = callback;
}
public void Login(Action<byte[]> login_callback)
{
CBLogin = login_callback;
if (api.IsLogin) return;
api.jslogin();
var buffer = api.qrcode();
if (CBLogin != null) this.CBLogin(buffer);
while (true)
{
string p = api.login();
if (p == "200")
{
// login confirmed
api.webwxnewloginpage();
api.webwxinit();
api.webwxstatusnotify(api.webWXInit.User.UserName, api.webWXInit.User.UserName);
api.webwxgetcontact();
break;
}
else if (p == "201")
{
// qrcode scaned
}
else if (p == "408")
{
this.api.jslogin();
if (CBLogin != null) this.CBLogin(api.qrcode());
}
}
}
public void SendMessage(UserInfo info , string message)
{
if (string.IsNullOrEmpty(message)) return;
api.webwxsendmsg(info.UserName, message);
}
}
}
| 29.25 | 178 | 0.415771 | [
"MIT"
] | 406345/wechat | WechatSDK/WXSDK.cs | 3,629 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.DirectoryServices.Protocols;
using System.Globalization;
using System.IO;
using System.Linq;
using OptigemLdapSync.Models;
namespace OptigemLdapSync
{
internal class SyncEngine
{
private readonly ISyncConfiguration configuration;
private readonly OptigemConnector optigem;
private readonly LdapConnector ldap;
private readonly GroupWorker groups;
private readonly DirectoryInfo logDir;
public SyncEngine(ISyncConfiguration configuration)
{
if (configuration == null)
throw new ArgumentNullException(nameof(configuration));
this.configuration = configuration;
this.optigem = new OptigemConnector(this.configuration.OptigemDatabasePath);
this.logDir = new DirectoryInfo(Path.Combine(this.configuration.OptigemDatabasePath, "syncLogs"));
if (!this.logDir.Exists)
{
this.logDir.Create();
}
string ldapConnection = this.optigem.GetLdapConnectionString();
if (string.IsNullOrEmpty(ldapConnection))
throw new InvalidOperationException("No LDAP connection configured.");
var parser = new LdapConnectionStringParser { ConnectionString = ldapConnection };
this.ldap = new LdapConnector(parser.Server, parser.Port, AuthType.Basic, parser.User, parser.Password, 100, this.configuration.WhatIf);
this.groups = new GroupWorker(this.configuration, this.ldap, this.optigem);
}
public SyncResult Do(ITaskReporter reporter, bool fullSync)
{
string logName = "SyncLog_" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".log";
using (var wrappedReport = new LoggingReporter(Path.Combine(this.logDir.FullName, logName), reporter))
{
return this.InternalDo(wrappedReport, fullSync);
}
}
private SyncResult InternalDo(ITaskReporter reporter, bool fullSync)
{
if (reporter == null)
throw new ArgumentNullException(nameof(reporter));
// 1: Group metadata
// 2: Prepare new users
// 3: Sync users
// 4: Check orphans
// 5: Syng group membership
reporter.Init(fullSync ? 5 : 3);
// Read LDAP groups and sync meta data.
this.groups.SyncMetadata(reporter);
// Clean-up database
this.optigem.SetCustomFieldsToNull();
var result = new SyncResult();
if (fullSync)
{
// Create sync meta data in Optigem for new users.
result.Created = this.CreateNewLdapUsers(reporter);
}
IList<PersonModel> persons = this.optigem.GetAllPersons()
.ToList();
reporter.StartTask("Personen abgleichen", persons.Count + 1);
reporter.Progress("LDAP-Benutzer laden");
List<SearchResultEntry> allPersonUsers = this.ldap.PagedSearch("(&(objectClass=fegperson))", this.configuration.LdapDirectoryBaseDn, LdapBuilder.AllAttributes) //new[] { "cn", "dn", "syncuserid" }
.SelectMany(s => s.OfType<SearchResultEntry>())
.ToList();
foreach (PersonModel person in persons)
{
reporter.Progress(person.Username);
var existingUser = allPersonUsers.FirstOrDefault(u => u.Attributes["syncuserid"][0]?.ToString() == person.SyncUserId.ToString());
this.SyncUser(reporter, person, existingUser, fullSync);
if (person.Aenderung && fullSync)
{
this.optigem.SetChangedFlag(person.Nr, false);
}
if (existingUser != null)
{
allPersonUsers.Remove(existingUser);
}
}
if (fullSync)
{
reporter.StartTask("Offene LDAP-Benutzer abgleichen", allPersonUsers.Count);
foreach (SearchResultEntry entry in allPersonUsers)
{
reporter.Progress(entry.DistinguishedName);
reporter.Log("Manual action required.");
}
}
this.groups.SyncMembership(reporter);
return result;
}
private int CreateNewLdapUsers(ITaskReporter reporter)
{
IList<PersonModel> persons = this.optigem.GetNewPersons().ToList();
reporter.StartTask("Neue Personen in OPTIGEM vorbereiten", persons.Count);
if (persons.Any())
{
int intranetUid = this.optigem.GetNextSyncUserId();
foreach (var person in persons)
{
string username = LdapBuilder.GetCn((person.Vorname?.Trim() + "." + person.Nachname?.Trim()).Trim('.')).ToLower(CultureInfo.CurrentCulture);
reporter.Progress(username);
person.Username = username.Length > 50 ? username.Substring(0, 50) : username;
person.Password = this.CalculatePassword();
person.SyncUserId = intranetUid++;
reporter.Log(person.Username + " mit Id " + person.SyncUserId + " angelegt.");
}
this.optigem.SetIntranetUserIds(persons);
return persons.Count;
}
return 0;
}
private void SyncUser(ITaskReporter reporter, PersonModel model, SearchResultEntry entry, bool fullSync)
{
ICollection<PersonenkategorieModel> kategorien = this.groups.GetKategorien(model.Nr);
// this.optigem.GetPersonenkategorien(model.Nr).ToList();
bool disabled = this.IsDisabled(model, kategorien);
string baseDn;
string requiredBaseDn;
string mitgliederBase = "ou=mitglieder," + this.configuration.LdapBenutzerBaseDn;
string externBase = "ou=extern," + this.configuration.LdapBenutzerBaseDn;
if (disabled)
{
requiredBaseDn = this.configuration.LdapInaktiveBenutzerBaseDn;
baseDn = requiredBaseDn;
}
else
{
requiredBaseDn = this.configuration.LdapBenutzerBaseDn;
baseDn = kategorien.Any(k => k.Name == "Mitglied") ? mitgliederBase : externBase;
}
string cn = LdapBuilder.GetCn(model.Username);
string dn = $"cn={cn},{baseDn}";
if (disabled && model.EndDatum.HasValue && model.EndDatum.Value < DateTime.Today.AddYears(-2))
{
// More than two years inactive => delete in LDAP
// No entry in LDAP => ok, NOP
if (entry != null)
{
try
{
reporter.Log($"Benutzer wird gelöscht (mehr als 2 Jahre inaktiv): {entry.DistinguishedName}");
this.ldap.DeleteEntry(entry.DistinguishedName);
}
catch (Exception exception)
{
reporter.Log($"Beim Versuch den Benutzer {cn} zu löschen ist ein Fehler aufgetreten: {exception.Message}");
}
}
return;
}
if (entry == null)
{
SearchResultEntry[] searchResult = this.ldap
.PagedSearch($"(&(objectClass=inetOrgPerson)(syncUserId={model.SyncUserId}))", this.configuration.LdapDirectoryBaseDn, LdapBuilder.AllAttributes)
.SelectMany(s => s.OfType<SearchResultEntry>())
.ToArray();
if (searchResult.Length == 0)
{
DirectoryAttribute[] attributes = LdapBuilder.GetAllAttributes(model, disabled).ToArray();
this.ldap.AddEntry(dn, attributes);
Log.Source.TraceEvent(TraceEventType.Information, 0, "Added new LDAP user '{0}'.", dn);
reporter.Log($"Neuer Benutzer hinzugefügt: {dn}");
}
else
{
entry = searchResult.First();
}
}
if (entry != null)
{
string oldDn = entry.DistinguishedName;
string oldBaseDn = oldDn.Split(new[] { ',' }, 2).Last();
Log.Source.TraceEvent(TraceEventType.Verbose, 0, "Syncing LDAP user '{0}'.", oldDn);
if (!oldDn.EndsWith(requiredBaseDn)
|| (oldBaseDn == externBase && baseDn == mitgliederBase)
|| (oldBaseDn == mitgliederBase && baseDn == externBase))
{
this.ldap.MoveEntry(oldDn, baseDn, $"cn={cn}");
Log.Source.TraceEvent(TraceEventType.Information, 0, "Moved LDAP user from '{0}' to '{1}'.", oldDn, dn);
reporter.Log($"Benutzer von {oldDn} nach {dn} verschoben.");
}
else
{
// User was not moved. Set baseDn to actual baseDn.
baseDn = oldBaseDn;
dn = $"cn={cn},{baseDn}";
string oldCn = entry.Attributes["cn"][0]?.ToString();
if (oldCn != cn)
{
dn = $"cn={cn},{oldBaseDn}";
this.ldap.MoveEntry(oldDn, oldBaseDn, $"cn={cn}");
Log.Source.TraceEvent(TraceEventType.Information, 0, "Renamed LDAP user from '{0}' to '{1}'.", oldCn, cn);
reporter.Log($"Benutzer von {oldCn} nach {cn} umbenannt.");
}
}
DirectoryAttributeModification[] diffAttributes = null;
if (fullSync)
{
diffAttributes = LdapBuilder.GetDiff(
LdapBuilder.GetUpdateAttributes(model, disabled),
entry,
LdapBuilder.CreateAttributes.Union(new[] { "cn", "dn" }).ToArray())
.ToArray();
}
else
{
// only update disabled attribute
diffAttributes = LdapBuilder.GetDiff(
LdapBuilder.GetUpdateAttributes(model, disabled),
entry,
LdapBuilder.AllAttributes.Except(new[] { "typo3disabled" }).ToArray())
.ToArray();
}
if (diffAttributes?.Any() ?? false)
{
this.ldap.ModifyEntry(dn, diffAttributes);
Log.Source.TraceEvent(TraceEventType.Information, 0, "Updated LDAP user '{0}'.", dn);
foreach (var diff in diffAttributes)
{
var oldAttr = entry.Attributes.Values?.OfType<DirectoryAttribute>().FirstOrDefault(a => string.Equals(a.Name, diff.Name, StringComparison.InvariantCultureIgnoreCase));
string oldValue = oldAttr == null ? string.Empty : string.Join("', '", oldAttr.GetValues<string>());
Debug.Assert(oldValue != string.Join("', '", diff.GetValues<string>()));
reporter.Log($"{diff.Name} auf '{string.Join("', '", diff.GetValues<string>())}' gesetzt (alt: '{oldValue}').");
}
foreach (string attributeChange in diffAttributes.SelectMany(Log.Print))
{
Log.Source.TraceEvent(TraceEventType.Verbose, 0, "Updated LDAP user '{0}': {1}", cn, attributeChange);
}
}
}
if (!disabled)
{
foreach (PersonenkategorieModel kategorie in kategorien)
{
LdapGroup group = this.groups.Get(kategorie);
if (group == null)
{
Log.Source.TraceEvent(TraceEventType.Warning, 0, "LDAP group does not exist: '{0}'", kategorie.Name);
}
else
{
group.MemberList.Add(dn);
}
}
}
}
private bool IsDisabled(PersonModel model, ICollection<PersonenkategorieModel> kategorien)
{
bool mitglied = kategorien.Any(k => k.Name == "Mitglied");
if (mitglied)
{
if (model.StartDatum.HasValue && model.StartDatum.Value > DateTime.Now)
return true;
if (model.EndDatum.HasValue && model.EndDatum.Value < DateTime.Now
&& (!model.StartDatum.HasValue || model.EndDatum.Value >= model.StartDatum.Value))
return true;
}
return !kategorien.Any();
}
private string CalculatePassword()
{
const int pinLaenge = 8;
const string charList1 = "abcdefghijklmnopqrstuvwxyz";
const string charList2 = "1234567890";
char[] result = new char[pinLaenge];
int i;
Random rand = new Random(Environment.TickCount);
for (i = 0; i < pinLaenge; i++)
{
int pos;
string list = i < 4 ? charList1 : charList2;
do
{
pos = (int)(list.Length * rand.NextDouble());
}
while (pos < 0 || pos >= list.Length);
result[i] = list[pos];
}
return new string(result);
}
}
}
| 38.753463 | 208 | 0.5198 | [
"MIT"
] | feg-giessen/OptigemLdapSync | OptigemLdapSync/SyncEngine.cs | 13,995 | C# |
namespace OpenQA.Selenium.DevTools.Page
{
using Newtonsoft.Json;
/// <summary>
/// GetInstallabilityErrors
/// </summary>
public sealed class GetInstallabilityErrorsCommandSettings : ICommand
{
private const string DevToolsRemoteInterface_CommandName = "Page.getInstallabilityErrors";
[JsonIgnore]
public string CommandName
{
get { return DevToolsRemoteInterface_CommandName; }
}
}
public sealed class GetInstallabilityErrorsCommandResponse : ICommandResponse<GetInstallabilityErrorsCommandSettings>
{
/// <summary>
/// Gets or sets the errors
/// </summary>
[JsonProperty("errors")]
public string[] Errors
{
get;
set;
}
}
} | 25.25 | 121 | 0.612624 | [
"Apache-2.0"
] | 418sec/selenium | dotnet/src/webdriver/DevTools/AutoGenerated/Page/GetInstallabilityErrorsCommand.cs | 808 | C# |
using System;
namespace NotFightClub_WebAPI
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
}
| 17.375 | 65 | 0.661871 | [
"MIT"
] | 08162021-dotnet-uta/P2_Group2 | NotFightClub/NotFightClub_WebAPI/WeatherForecast.cs | 278 | C# |
#pragma warning disable 1591
namespace Braintree.Exceptions
{
public class UpgradeRequiredException : BraintreeException
{
}
}
| 15.555556 | 62 | 0.75 | [
"MIT"
] | Ethernodes-org/braintree_dotnet | src/Braintree/Exceptions/UpgradeRequiredException.cs | 140 | C# |
namespace LauncherGUI
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Text = "Form1";
}
#endregion
}
}
| 28.35 | 107 | 0.556437 | [
"CC0-1.0"
] | VDGroup/SURustLauncher | RustLauncher/LauncherGUI/Form1.Designer.cs | 1,136 | 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.AzureNextGen.ServiceFabric.V20190601Preview
{
public static class GetCluster
{
public static Task<GetClusterResult> InvokeAsync(GetClusterArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetClusterResult>("azure-nextgen:servicefabric/v20190601preview:getCluster", args ?? new GetClusterArgs(), options.WithVersion());
}
public sealed class GetClusterArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the cluster resource.
/// </summary>
[Input("clusterName", required: true)]
public string ClusterName { get; set; } = null!;
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
public GetClusterArgs()
{
}
}
[OutputType]
public sealed class GetClusterResult
{
/// <summary>
/// The list of add-on features to enable in the cluster.
/// </summary>
public readonly ImmutableArray<string> AddOnFeatures;
/// <summary>
/// The Service Fabric runtime versions available for this cluster.
/// </summary>
public readonly ImmutableArray<Outputs.ClusterVersionDetailsResponse> AvailableClusterVersions;
/// <summary>
/// The AAD authentication settings of the cluster.
/// </summary>
public readonly Outputs.AzureActiveDirectoryResponse? AzureActiveDirectory;
/// <summary>
/// The certificate to use for securing the cluster. The certificate provided will be used for node to node security within the cluster, SSL certificate for cluster management endpoint and default admin client.
/// </summary>
public readonly Outputs.CertificateDescriptionResponse? Certificate;
/// <summary>
/// Describes a list of server certificates referenced by common name that are used to secure the cluster.
/// </summary>
public readonly Outputs.ServerCertificateCommonNamesResponse? CertificateCommonNames;
/// <summary>
/// The list of client certificates referenced by common name that are allowed to manage the cluster.
/// </summary>
public readonly ImmutableArray<Outputs.ClientCertificateCommonNameResponse> ClientCertificateCommonNames;
/// <summary>
/// The list of client certificates referenced by thumbprint that are allowed to manage the cluster.
/// </summary>
public readonly ImmutableArray<Outputs.ClientCertificateThumbprintResponse> ClientCertificateThumbprints;
/// <summary>
/// The Service Fabric runtime version of the cluster. This property can only by set the user when **upgradeMode** is set to 'Manual'. To get list of available Service Fabric versions for new clusters use [ClusterVersion API](./ClusterVersion.md). To get the list of available version for existing clusters use **availableClusterVersions**.
/// </summary>
public readonly string? ClusterCodeVersion;
/// <summary>
/// The Azure Resource Provider endpoint. A system service in the cluster connects to this endpoint.
/// </summary>
public readonly string ClusterEndpoint;
/// <summary>
/// A service generated unique identifier for the cluster resource.
/// </summary>
public readonly string ClusterId;
/// <summary>
/// The current state of the cluster.
///
/// - WaitingForNodes - Indicates that the cluster resource is created and the resource provider is waiting for Service Fabric VM extension to boot up and report to it.
/// - Deploying - Indicates that the Service Fabric runtime is being installed on the VMs. Cluster resource will be in this state until the cluster boots up and system services are up.
/// - BaselineUpgrade - Indicates that the cluster is upgrading to establishes the cluster version. This upgrade is automatically initiated when the cluster boots up for the first time.
/// - UpdatingUserConfiguration - Indicates that the cluster is being upgraded with the user provided configuration.
/// - UpdatingUserCertificate - Indicates that the cluster is being upgraded with the user provided certificate.
/// - UpdatingInfrastructure - Indicates that the cluster is being upgraded with the latest Service Fabric runtime version. This happens only when the **upgradeMode** is set to 'Automatic'.
/// - EnforcingClusterVersion - Indicates that cluster is on a different version than expected and the cluster is being upgraded to the expected version.
/// - UpgradeServiceUnreachable - Indicates that the system service in the cluster is no longer polling the Resource Provider. Clusters in this state cannot be managed by the Resource Provider.
/// - AutoScale - Indicates that the ReliabilityLevel of the cluster is being adjusted.
/// - Ready - Indicates that the cluster is in a stable state.
/// </summary>
public readonly string ClusterState;
/// <summary>
/// The storage account information for storing Service Fabric diagnostic logs.
/// </summary>
public readonly Outputs.DiagnosticsStorageAccountConfigResponse? DiagnosticsStorageAccountConfig;
/// <summary>
/// Azure resource etag.
/// </summary>
public readonly string Etag;
/// <summary>
/// Indicates if the event store service is enabled.
/// </summary>
public readonly bool? EventStoreServiceEnabled;
/// <summary>
/// The list of custom fabric settings to configure the cluster.
/// </summary>
public readonly ImmutableArray<Outputs.SettingsSectionDescriptionResponse> FabricSettings;
/// <summary>
/// Azure resource location.
/// </summary>
public readonly string Location;
/// <summary>
/// The http management endpoint of the cluster.
/// </summary>
public readonly string ManagementEndpoint;
/// <summary>
/// Azure resource name.
/// </summary>
public readonly string Name;
/// <summary>
/// The list of node types in the cluster.
/// </summary>
public readonly ImmutableArray<Outputs.NodeTypeDescriptionResponse> NodeTypes;
/// <summary>
/// The provisioning state of the cluster resource.
/// </summary>
public readonly string ProvisioningState;
/// <summary>
/// The reliability level sets the replica set size of system services. Learn about [ReliabilityLevel](https://docs.microsoft.com/azure/service-fabric/service-fabric-cluster-capacity).
///
/// - None - Run the System services with a target replica set count of 1. This should only be used for test clusters.
/// - Bronze - Run the System services with a target replica set count of 3. This should only be used for test clusters.
/// - Silver - Run the System services with a target replica set count of 5.
/// - Gold - Run the System services with a target replica set count of 7.
/// - Platinum - Run the System services with a target replica set count of 9.
/// </summary>
public readonly string? ReliabilityLevel;
/// <summary>
/// The server certificate used by reverse proxy.
/// </summary>
public readonly Outputs.CertificateDescriptionResponse? ReverseProxyCertificate;
/// <summary>
/// Describes a list of server certificates referenced by common name that are used to secure the cluster.
/// </summary>
public readonly Outputs.ServerCertificateCommonNamesResponse? ReverseProxyCertificateCommonNames;
/// <summary>
/// Azure resource tags.
/// </summary>
public readonly ImmutableDictionary<string, string>? Tags;
/// <summary>
/// Azure resource type.
/// </summary>
public readonly string Type;
/// <summary>
/// The policy to use when upgrading the cluster.
/// </summary>
public readonly Outputs.ClusterUpgradePolicyResponse? UpgradeDescription;
/// <summary>
/// The upgrade mode of the cluster when new Service Fabric runtime version is available.
///
/// - Automatic - The cluster will be automatically upgraded to the latest Service Fabric runtime version as soon as it is available.
/// - Manual - The cluster will not be automatically upgraded to the latest Service Fabric runtime version. The cluster is upgraded by setting the **clusterCodeVersion** property in the cluster resource.
/// </summary>
public readonly string? UpgradeMode;
/// <summary>
/// The VM image VMSS has been configured with. Generic names such as Windows or Linux can be used.
/// </summary>
public readonly string? VmImage;
[OutputConstructor]
private GetClusterResult(
ImmutableArray<string> addOnFeatures,
ImmutableArray<Outputs.ClusterVersionDetailsResponse> availableClusterVersions,
Outputs.AzureActiveDirectoryResponse? azureActiveDirectory,
Outputs.CertificateDescriptionResponse? certificate,
Outputs.ServerCertificateCommonNamesResponse? certificateCommonNames,
ImmutableArray<Outputs.ClientCertificateCommonNameResponse> clientCertificateCommonNames,
ImmutableArray<Outputs.ClientCertificateThumbprintResponse> clientCertificateThumbprints,
string? clusterCodeVersion,
string clusterEndpoint,
string clusterId,
string clusterState,
Outputs.DiagnosticsStorageAccountConfigResponse? diagnosticsStorageAccountConfig,
string etag,
bool? eventStoreServiceEnabled,
ImmutableArray<Outputs.SettingsSectionDescriptionResponse> fabricSettings,
string location,
string managementEndpoint,
string name,
ImmutableArray<Outputs.NodeTypeDescriptionResponse> nodeTypes,
string provisioningState,
string? reliabilityLevel,
Outputs.CertificateDescriptionResponse? reverseProxyCertificate,
Outputs.ServerCertificateCommonNamesResponse? reverseProxyCertificateCommonNames,
ImmutableDictionary<string, string>? tags,
string type,
Outputs.ClusterUpgradePolicyResponse? upgradeDescription,
string? upgradeMode,
string? vmImage)
{
AddOnFeatures = addOnFeatures;
AvailableClusterVersions = availableClusterVersions;
AzureActiveDirectory = azureActiveDirectory;
Certificate = certificate;
CertificateCommonNames = certificateCommonNames;
ClientCertificateCommonNames = clientCertificateCommonNames;
ClientCertificateThumbprints = clientCertificateThumbprints;
ClusterCodeVersion = clusterCodeVersion;
ClusterEndpoint = clusterEndpoint;
ClusterId = clusterId;
ClusterState = clusterState;
DiagnosticsStorageAccountConfig = diagnosticsStorageAccountConfig;
Etag = etag;
EventStoreServiceEnabled = eventStoreServiceEnabled;
FabricSettings = fabricSettings;
Location = location;
ManagementEndpoint = managementEndpoint;
Name = name;
NodeTypes = nodeTypes;
ProvisioningState = provisioningState;
ReliabilityLevel = reliabilityLevel;
ReverseProxyCertificate = reverseProxyCertificate;
ReverseProxyCertificateCommonNames = reverseProxyCertificateCommonNames;
Tags = tags;
Type = type;
UpgradeDescription = upgradeDescription;
UpgradeMode = upgradeMode;
VmImage = vmImage;
}
}
}
| 47.507576 | 348 | 0.667517 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/ServiceFabric/V20190601Preview/GetCluster.cs | 12,542 | C# |
// -----------------------------------------------------------------------
// <copyright file="ClassifierProvider.cs" company="Equilogic (Pty) Ltd">
// Copyright © Equilogic (Pty) Ltd. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace RegionsAreEvil.Classifications
{
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
internal sealed class ClassifierProvider
{
#region Internal Fields
[Export]
[Name(Constants.ActiveRegionClassificationTypeNames)]
internal static ClassificationTypeDefinition ActiveRegionDefinition;
[Export]
[Name(Constants.InactiveRegionClassificationTypeNames)]
internal static ClassificationTypeDefinition InactiveRegionDefinition;
#endregion
}
} | 32.821429 | 78 | 0.613711 | [
"MIT"
] | VolodymyrBS/regionsareevil | src/RegionsAreEvil/Classifications/ClassifierProvider.cs | 922 | C# |
#region License
// Copyright (c) 2021 Peter Šulek / ScaleHQ Solutions s.r.o.
//
// 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.
#endregion
using System.Globalization;
using System.Linq;
using LHQ.Utils.Extensions;
using LHQ.Utils.Utilities;
namespace LHQ.Data
{
public partial class ModelContext
{
public ResourceValueElement AddResourceValue(CultureInfo cultureInfo, string value, ResourceElement parentResource)
{
return AddResourceValue(cultureInfo.Name, value, parentResource);
}
public ResourceValueElement AddResourceValue(string languageName, string value, ResourceElement parentResource)
{
var resourceValue = CreateResourceValue();
resourceValue.LanguageName = languageName;
resourceValue.Value = value;
AddResourceValue(resourceValue, parentResource);
return resourceValue;
}
internal void AddResourceValue(ResourceValueElement resourceValue, ResourceElement parentResource)
{
ArgumentValidator.EnsureArgumentNotNull(resourceValue, "resourceValue");
ArgumentValidator.EnsureArgumentNotNull(parentResource, "parentResource");
ArgumentValidator.EnsureArgumentNotNullOrEmpty(resourceValue.LanguageName, "resourceValue.LanguageName");
//ArgumentValidator.EnsureArgumentNotNullOrEmpty(resourceValue.Value, "resourceValue.Value");
if (ContainsResourceValue(resourceValue.LanguageName, parentResource))
{
throw new ModelException(Model, resourceValue,
Errors.Model.ResourceAlreadyContainsValueForLanguage(parentResource.Name,
resourceValue.LanguageName));
}
parentResource.Values.Add(resourceValue);
resourceValue.ParentElement = parentResource;
}
internal ResourceValueElement CreateResourceValue()
{
return new ResourceValueElement(GenerateKey()); //.SetRuntimeId(this.Model);
}
internal bool ContainsResourceValue(string resourceParameterLanguageName, ResourceElement parentResource)
{
ArgumentValidator.EnsureArgumentNotNullOrEmpty(resourceParameterLanguageName, "resourceParameterName");
ArgumentValidator.EnsureArgumentNotNull(parentResource, "parentResource");
return parentResource.Values.Any(x => x.LanguageName.EqualsTo(resourceParameterLanguageName));
}
}
} | 44.2125 | 123 | 0.721233 | [
"MIT"
] | psulek/lhqeditor | src/Data/ModelContext.ResourceValue.cs | 3,540 | C# |
using CrossX.Framework.Styles;
using Xx;
namespace CrossX.Framework.ApplicationDefinition
{
[XxSchemaExport]
public class LengthElement: IValueElement
{
public ThemeValueKey Key { get; set; }
[XxSchemaBindable]
public Length Value { get; set; }
object IValueElement.Value => Value;
}
[XxSchemaExport]
public class ThicknessElement : IValueElement
{
public ThemeValueKey Key { get; set; }
[XxSchemaBindable]
public Thickness Value { get; set; }
object IValueElement.Value => Value;
}
}
| 21.964286 | 50 | 0.614634 | [
"MIT"
] | ebatianoSoftware/CrossX | Core/CrossX.Framework/ApplicationDefinition/LengthElement.cs | 617 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Westwind.AspNetCore.LiveReload;
using Westwind.AspNetCore.Markdown;
using Westwind.Utilities;
using Microsoft.Extensions.FileProviders.Physical;
using Microsoft.AspNetCore.Hosting;
namespace LiveReloadServer
{
public class Startup
{
/// <summary>
/// Binary Startup Location irrespective of the environment path
/// </summary>
public static string StartupPath { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
StartupPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
}
public IConfiguration Configuration { get; }
public LiveReloadServerConfiguration ServerConfig { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
ServerConfig = new LiveReloadServerConfiguration();
ServerConfig.LoadFromConfiguration(Configuration);
if (ServerConfig.UseLiveReload)
{
services.AddLiveReload(opt =>
{
opt.FolderToMonitor = ServerConfig.WebRoot;
opt.LiveReloadEnabled = ServerConfig.UseLiveReload;
if (!string.IsNullOrEmpty(ServerConfig.Extensions))
opt.ClientFileExtensions = ServerConfig.Extensions;
});
}
IMvcBuilder mvcBuilder = null;
#if USE_RAZORPAGES
if (ServerConfig.UseRazor)
{
mvcBuilder = services.AddRazorPages(opt => { opt.RootDirectory = "/"; });
}
#endif
if (ServerConfig.UseMarkdown)
{
services.AddMarkdown(config =>
{
var templatePath = ServerConfig.MarkdownTemplate;
templatePath = templatePath.Replace("\\", "/");
var folderConfig = config.AddMarkdownProcessingFolder("/", templatePath);
// Optional configuration settings
folderConfig.ProcessExtensionlessUrls = true; // default
folderConfig.ProcessMdFiles = true; // default
folderConfig.RenderTheme = ServerConfig.MarkdownTheme;
folderConfig.SyntaxTheme = ServerConfig.MarkdownSyntaxTheme;
});
// we have to force MVC in order for the controller routing to work
mvcBuilder = services
.AddMvc()
// have to let MVC know we have a dynamically loaded controller
.AddApplicationPart(typeof(MarkdownPageProcessorMiddleware).Assembly);
// copy Markdown Template and resources if it doesn't exist
if (ServerConfig.CopyMarkdownResources)
CopyMarkdownTemplateResources();
}
if (mvcBuilder != null)
{
mvcBuilder.AddRazorRuntimeCompilation(
opt =>
{
opt.FileProviders.Clear();
opt.FileProviders.Add(new PhysicalFileProvider(ServerConfig.WebRoot));
opt.FileProviders.Add(
new PhysicalFileProvider(Path.Combine(Startup.StartupPath, "templates")));
});
LoadPrivateBinAssemblies(mvcBuilder);
}
}
private static object consoleLock = new object();
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IWebHostEnvironment env)
{
if (ServerConfig.UseLiveReload)
app.UseLiveReload();
if (ServerConfig.DetailedErrors)
app.UseDeveloperExceptionPage();
else
app.UseExceptionHandler("/Error");
if (ServerConfig.ShowUrls)
app.Use(DisplayRequestInfoMiddlewareHandler);
app.UseDefaultFiles(new DefaultFilesOptions
{
FileProvider = new PhysicalFileProvider(ServerConfig.WebRoot),
DefaultFileNames = new List<string>(ServerConfig.DefaultFiles.Split(',', ';'))
});
if (ServerConfig.UseMarkdown)
app.UseMarkdown();
// add static files to WebRoot and our templates folder which provides markdown templates
// and potentially other library resources in the future
var wrProvider = new PhysicalFileProvider(ServerConfig.WebRoot);
var tpProvider = new PhysicalFileProvider(Path.Combine(Startup.StartupPath, "templates"));
var extensionProvider = new FileExtensionContentTypeProvider();
extensionProvider.Mappings.Add(".dll", "application/octet-stream");
if (ServerConfig.AdditionalMimeMappings != null)
{
foreach (var map in ServerConfig.AdditionalMimeMappings)
extensionProvider.Mappings[map.Key] = map.Value;
}
var compositeProvider = new CompositeFileProvider(wrProvider, tpProvider);
var staticFileOptions = new StaticFileOptions
{
//FileProvider = compositeProvider, //new PhysicalFileProvider(WebRoot),
FileProvider = new PhysicalFileProvider(ServerConfig.WebRoot),
RequestPath = new PathString(""),
ContentTypeProvider = extensionProvider,
DefaultContentType = "application/octet-stream"
};
app.UseStaticFiles(staticFileOptions);
if (ServerConfig.UseRazor || ServerConfig.UseMarkdown || !string.IsNullOrEmpty(ServerConfig.FolderNotFoundFallbackPath))
app.UseRouting();
#if USE_RAZORPAGES
if (ServerConfig.UseRazor)
{
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
#endif
if (ServerConfig.UseMarkdown)
{
app.UseEndpoints(endpoints =>
{
// We need MVC Routing for Markdown to work
endpoints.MapDefaultControllerRoute();
});
}
//if (!string.IsNullOrEmpty(ServerConfig.FolderNotFoundFallbackPath))
//{
// app.UseEndpoints(endpoints =>
// {
// endpoints.MapFallbackToFile("/index.html");
// });
//}
//app.Use(FallbackMiddlewareHandler);
DisplayServerSettings(env);
if (ServerConfig.OpenBrowser)
{
var rootUrl = ServerConfig.GetHttpUrl();
if (!string.IsNullOrEmpty(ServerConfig.BrowserUrl))
{
if (ServerConfig.BrowserUrl.StartsWith("http://") || ServerConfig.BrowserUrl.StartsWith("https://"))
rootUrl = ServerConfig.BrowserUrl;
else
{
var url = "/" + ServerConfig.BrowserUrl.TrimStart('/'); // force leading slash
rootUrl = rootUrl.TrimEnd('/') + url
.Replace("~", "")
.Replace("\\", "/")
.Replace("//", "/");
}
}
Helpers.OpenUrl(rootUrl);
}
if (ServerConfig.OpenEditor)
{
string cmdLine = null;
try
{
cmdLine = ServerConfig.EditorLaunchCommand.Replace("%1", ServerConfig.WebRoot);
Westwind.Utilities.ShellUtils.ExecuteCommandLine(cmdLine);
}
catch (Exception ex)
{
ColorConsole.WriteError("Failed to launch editor with: " + cmdLine);
ColorConsole.WriteError("-- " + ex.Message);
}
}
}
private void DisplayServerSettings(IWebHostEnvironment env)
{
string headerLine = new string('-', Helpers.AppHeader.Length);
Console.WriteLine(headerLine);
ColorConsole.WriteLine(Helpers.AppHeader, ConsoleColor.Yellow);
Console.WriteLine(headerLine);
Console.WriteLine($"(c) West Wind Technologies, 2019-{DateTime.Now.Year}\r\n");
string displayUrl = ServerConfig.GetHttpUrl();
string hostUrl = ServerConfig.GetHttpUrl(true);
if (hostUrl == displayUrl || hostUrl.Contains("127.0.0.1"))
hostUrl = null;
else
{
hostUrl = $" [darkgray](binding: {hostUrl})[/darkgray]";
}
ColorConsole.WriteEmbeddedColorLine($"Site Url : [darkcyan]{ServerConfig.GetHttpUrl()}[/darkcyan] {hostUrl}");
//ConsoleHelper.WriteLine(, ConsoleColor.DarkCyan);
Console.WriteLine($"Web Root : {ServerConfig.WebRoot}");
Console.WriteLine($"Executable : {Assembly.GetExecutingAssembly().Location}");
Console.WriteLine($"Live Reload : {ServerConfig.UseLiveReload}");
if (ServerConfig.UseLiveReload)
Console.WriteLine(
$" Extensions : {(string.IsNullOrEmpty(ServerConfig.Extensions) ? $"{(ServerConfig.UseRazor ? ".cshtml," : "")}.css,.js,.htm,.html,.ts" : ServerConfig.Extensions)}");
#if USE_RAZORPAGES
Console.WriteLine($"Use Razor : {ServerConfig.UseRazor}");
#endif
Console.WriteLine($"Use Markdown : {ServerConfig.UseMarkdown}");
if (ServerConfig.UseMarkdown)
{
Console.WriteLine($" Resources : {ServerConfig.CopyMarkdownResources}");
Console.WriteLine($" Template : {ServerConfig.MarkdownTemplate}");
Console.WriteLine($" Theme : {ServerConfig.MarkdownTheme}");
Console.WriteLine($" SyntaxTheme: {ServerConfig.MarkdownSyntaxTheme}");
}
Console.WriteLine($"Show Urls : {ServerConfig.ShowUrls}");
Console.Write($"Open Browser : {ServerConfig.OpenBrowser}");
Console.WriteLine($" Default Pages: {ServerConfig.DefaultFiles}");
Console.WriteLine($"Detail Errors: {ServerConfig.DetailedErrors}");
ColorConsole.WriteEmbeddedColorLine($"Environment : [darkgreen]{env.EnvironmentName}[/darkgreen] {System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription}");
Console.WriteLine();
ColorConsole.Write(Helpers.ExeName + " --help", ConsoleColor.DarkCyan);
Console.WriteLine(" for start options...");
Console.WriteLine();
ColorConsole.WriteLine("Ctrl-C or Ctrl-Break to exit...", ConsoleColor.Yellow);
Console.WriteLine("----------------------------------------------");
var oldColor = Console.ForegroundColor;
foreach (var assmbly in LoadedPrivateAssemblies)
{
var fname = Path.GetFileName(assmbly);
ColorConsole.WriteEmbeddedColorLine("Additional Assembly: [darkgreen]" + fname + "[/darkgreen]");
}
foreach (var assmbly in FailedPrivateAssemblies)
{
var fname = Path.GetFileName(assmbly);
ColorConsole.WriteLine("Failed Additional Assembly: " + fname, ConsoleColor.DarkGreen);
}
Console.ForegroundColor = oldColor;
}
public static Type GetTypeFromName(string TypeName)
{
Type type = Type.GetType(TypeName);
if (type != null)
return type;
// *** try to find manually
foreach (Assembly ass in AssemblyLoadContext.Default.Assemblies)
{
type = ass.GetType(TypeName, false);
if (type != null)
break;
}
return type;
}
private List<string> LoadedPrivateAssemblies = new List<string>();
private List<string> FailedPrivateAssemblies = new List<string>();
private void LoadPrivateBinAssemblies(IMvcBuilder mvcBuilder)
{
var binPath = Path.Combine(ServerConfig.WebRoot, "privatebin");
if (Directory.Exists(binPath))
{
var files = Directory.GetFiles(binPath);
foreach (var file in files)
{
if (!file.EndsWith(".dll", StringComparison.CurrentCultureIgnoreCase) &&
!file.EndsWith(".exe", StringComparison.InvariantCultureIgnoreCase))
continue;
try
{
var asm = AssemblyLoadContext.Default.LoadFromAssemblyPath(file);
mvcBuilder.AddApplicationPart(asm);
LoadedPrivateAssemblies.Add(file);
}
catch (Exception ex)
{
FailedPrivateAssemblies.Add(file + "\n - " + ex.Message);
}
}
}
}
/// <summary>
/// Copies the Markdown Template resources into the WebRoot if it doesn't exist already.
///
/// If you want to get a new set of template, delete the `markdown-themes` folder in hte
/// WebRoot output folder.
/// </summary>
/// <returns>false if already exists and no files were copied. True if path doesn't exist and files were copied</returns>
private bool CopyMarkdownTemplateResources()
{
// explicitly don't want to copy resources
if (!ServerConfig.CopyMarkdownResources)
return false;
var templatePath = Path.Combine(ServerConfig.WebRoot, "markdown-themes");
if (Directory.Exists(templatePath))
return false;
FileUtils.CopyDirectory(Path.Combine(Startup.StartupPath, "templates", "markdown-themes"),
templatePath, recursive: true);
return true;
}
/// <summary>
/// This middle ware handler intercepts every request captures the time
/// and then logs out to the screen (when that feature is enabled) the active
/// request path, the status, processing time.
/// </summary>
/// <param name="context"></param>
/// <param name="next"></param>
/// <returns></returns>
async Task DisplayRequestInfoMiddlewareHandler(HttpContext context, Func<Task> next)
{
var originalPath = context.Request.Path.Value;
Stopwatch sw = new Stopwatch();
sw.Start();
await next();
// ignore Web socket requests
if (context.Request.Path.Value == LiveReloadConfiguration.Current?.WebSocketUrl)
return;
// need to ensure this happens all at once otherwise multiple threads
// write intermixed console output on simultaneous requests
lock (consoleLock)
{
WriteConsoleLogDisplay(context, sw, originalPath);
}
}
/// <summary>
/// Responsible for writing the actual request display out to the console.
/// </summary>
/// <param name="context"></param>
/// <param name="sw"></param>
/// <param name="originalPath"></param>
private void WriteConsoleLogDisplay(HttpContext context, Stopwatch sw, string originalPath)
{
var url =
$"{context.Request.Method} {context.Request.Scheme}://{context.Request.Host} {originalPath}{context.Request.QueryString}";
url = url.PadRight(80, ' ');
var ct = context.Response.ContentType;
bool isPrimary = ct != null &&
(ct.StartsWith("text/html") ||
ct.StartsWith("text/plain") ||
ct.StartsWith("application/json") ||
ct.StartsWith("text/xml"));
var saveColor = Console.ForegroundColor;
var status = context.Response.StatusCode;
if (ct == null) // no response
{
ColorConsole.Write(url + " ", ConsoleColor.Red);
isPrimary = true;
}
else if (isPrimary)
ColorConsole.Write(url + " ", ConsoleColor.Gray);
else
ColorConsole.Write(url + " ", ConsoleColor.DarkGray);
if (status >= 200 && status < 400)
ColorConsole.Write(status.ToString(),
isPrimary ? ConsoleColor.Green : ConsoleColor.DarkGreen);
else if (status == 401)
ColorConsole.Write(status.ToString(),
isPrimary ? ConsoleColor.Yellow : ConsoleColor.DarkYellow);
else if (status >= 400)
ColorConsole.Write(status.ToString(), isPrimary ? ConsoleColor.Red : ConsoleColor.DarkRed);
sw.Stop();
ColorConsole.WriteLine($" {sw.ElapsedMilliseconds:n0}ms".PadLeft(8), ConsoleColor.DarkGray);
Console.ForegroundColor = saveColor;
}
/// <summary>
/// Fallback handler middleware that is fired for any requests that aren't processed.
/// This ends up being either a 404 result or
/// </summary>
/// <param name="context"></param>
/// <param name="next"></param>
/// <returns></returns>
private async Task FallbackMiddlewareHandler(HttpContext context, Func<Task> next)
{
// 404 - no match
if (string.IsNullOrEmpty(ServerConfig.FolderNotFoundFallbackPath))
{
await Status404Page(context);
return;
}
// 404 - SPA fall through middleware - for SPA apps should fallback to index.html
var path = context.Request.Path;
if (string.IsNullOrEmpty(Path.GetExtension(path)))
{
var file = Path.Combine(ServerConfig.WebRoot,
ServerConfig.FolderNotFoundFallbackPath.Trim('/', '\\'));
var fi = new FileInfo(file);
if (fi.Exists)
{
if (!context.Response.HasStarted)
{
context.Response.ContentType = "text/html";
context.Response.StatusCode = 200;
}
await context.Response.SendFileAsync(new PhysicalFileInfo(fi));
await context.Response.CompleteAsync();
}
else
{
await Status404Page(context,isFallback: true);
}
}
}
/// <summary>
/// Writes out a 404 error page with 404 error status
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private async Task Status404Page(HttpContext context, string additionalHtml = null, bool isFallback = false)
{
if (string.IsNullOrEmpty(additionalHtml) && isFallback)
{
additionalHtml = @"
<p>A fallback URL is configured but was not found: <b>{ServerConfig.FolderNotFoundFallbackPath}</b></p>
<p>The fallback URL can be used for SPA application to handle server side redirection to the initial
client side startup URL - typically <code>/index.html</code>. This URL is loaded if
a URL cannot otherwise be handled. This error page is displayed because the specified fallback
page or resource also does not exist.</p>
";
}
if (!context.Response.HasStarted)
{
context.Response.StatusCode = 404;
context.Response.ContentType = "text/html";
}
await context.Response.WriteAsync(@$"
<html>
<body style='font-family: sans-serif; margin:2em 5%; max-width: 978px;'>
<h1>Not Found</h1>
<hr/>
<p>The page or resource you are accessing is not available on this site.<p>
{additionalHtml}
</body></html>");
await context.Response.CompleteAsync();
}
}
}
| 38.563869 | 187 | 0.559788 | [
"MIT"
] | RickStrahl/LiveReloadServer | LiveReloadServer/Startup.cs | 21,135 | C# |
using System;
using BizHawk.Common.NumberExtensions;
namespace BizHawk.Emulation.Common.Components.MC6809
{
public partial class MC6809
{
// this contains the vectors of instrcution operations
// NOTE: This list is NOT confirmed accurate for each individual cycle
private void NOP_()
{
PopulateCURINSTR(IDLE);
IRQS = 1;
}
private void ILLEGAL()
{
//throw new Exception("Encountered illegal instruction");
PopulateCURINSTR(IDLE);
IRQS = 1;
}
private void SYNC_()
{
PopulateCURINSTR(IDLE,
SYNC);
IRQS = -1;
}
private void REG_OP(ushort oper, ushort src)
{
PopulateCURINSTR(oper, src);
IRQS = 1;
}
private void DIRECT_MEM(ushort oper)
{
PopulateCURINSTR(RD_INC, ALU, PC,
SET_ADDR, ADDR, DP, ALU,
RD, ALU, ADDR,
oper, ALU,
WR, ADDR, ALU);
IRQS = 5;
}
private void DIRECT_ST_4(ushort dest)
{
PopulateCURINSTR(RD_INC_OP, ALU, PC, SET_ADDR, ADDR, DP, ALU,
ST_8, dest,
WR, ADDR, dest);
IRQS = 3;
}
private void DIRECT_MEM_4(ushort oper, ushort dest)
{
PopulateCURINSTR(RD_INC_OP, ALU, PC, SET_ADDR, ADDR, DP, ALU,
IDLE,
RD_INC_OP, ALU, ADDR, oper, dest, ALU);
IRQS = 3;
}
private void EXT_MEM(ushort oper)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC, ALU2, PC,
SET_ADDR, ADDR, ALU, ALU2,
RD, ALU, ADDR,
oper, ALU,
WR, ADDR, ALU);
IRQS = 6;
}
private void EXT_REG(ushort oper, ushort dest)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC_OP, ALU2, PC, SET_ADDR, ADDR, ALU, ALU2,
RD, ALU, ADDR,
oper, dest, ALU);
IRQS = 4;
}
private void EXT_ST(ushort dest)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC_OP, ALU2, PC, SET_ADDR, ADDR, ALU, ALU2,
ST_8, dest,
WR, ADDR, dest);
IRQS = 4;
}
private void REG_OP_IMD_CC(ushort oper)
{
Regs[ALU2] = Regs[CC];
PopulateCURINSTR(RD_INC_OP, ALU, PC, oper, ALU2, ALU,
TR, CC, ALU2);
IRQS = 2;
}
private void REG_OP_IMD(ushort oper, ushort dest)
{
PopulateCURINSTR(RD_INC_OP, ALU, PC, oper, dest, ALU);
IRQS = 1;
}
private void IMD_OP_D(ushort oper, ushort dest)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC_OP, ALU2, PC, SET_ADDR, ADDR, ALU, ALU2,
oper, ADDR);
IRQS = 3;
}
private void DIR_OP_D(ushort oper, ushort dest)
{
PopulateCURINSTR(RD_INC_OP, ALU, PC, SET_ADDR, ADDR, DP, ALU,
RD_INC, ALU, ADDR,
RD, ALU2, ADDR,
SET_ADDR, ADDR, ALU, ALU2,
oper, ADDR);
IRQS = 5;
}
private void EXT_OP_D(ushort oper, ushort dest)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC_OP, ALU2, PC, SET_ADDR, ADDR, ALU, ALU2,
RD_INC, ALU, ADDR,
RD, ALU2, ADDR,
SET_ADDR, ADDR, ALU, ALU2,
oper, ADDR);
IRQS = 6;
}
private void REG_OP_LD_16D()
{
PopulateCURINSTR(RD_INC, A, PC,
RD_INC_OP, B, PC, LD_16, ADDR, A, B);
IRQS = 2;
}
private void DIR_OP_LD_16D()
{
PopulateCURINSTR(RD_INC_OP, ALU, PC, SET_ADDR, ADDR, DP, ALU,
IDLE,
RD_INC, A, ADDR,
RD_INC_OP, B, ADDR, LD_16, ADDR, A, B);
IRQS = 4;
}
private void DIR_OP_ST_16D()
{
PopulateCURINSTR(RD_INC_OP, ALU, PC, SET_ADDR, ADDR, DP, ALU,
ST_16, Dr,
WR_LO_INC, ADDR, A,
WR, ADDR, B);
IRQS = 4;
}
private void DIR_CMP_16(ushort oper, ushort dest)
{
PopulateCURINSTR(RD_INC_OP, ALU, PC, SET_ADDR, ADDR, DP, ALU,
RD_INC, ALU, ADDR,
RD, ALU2, ADDR,
SET_ADDR, ADDR, ALU, ALU2,
oper, dest, ADDR);
IRQS = 5;
}
private void IMD_CMP_16(ushort oper, ushort dest)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC_OP, ALU2, PC, SET_ADDR, ADDR, ALU, ALU2,
oper, dest, ADDR);
IRQS = 3;
}
private void REG_OP_LD_16(ushort dest)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC_OP, ALU2, PC, LD_16, dest, ALU, ALU2);
IRQS = 2;
}
private void DIR_OP_LD_16(ushort dest)
{
PopulateCURINSTR(RD_INC_OP, ALU, PC, SET_ADDR, ADDR, DP, ALU,
IDLE,
RD_INC, ALU, ADDR,
RD_INC_OP, ALU2, ADDR, LD_16, dest, ALU, ALU2);
IRQS = 4;
}
private void DIR_OP_ST_16(ushort src)
{
PopulateCURINSTR(RD_INC_OP, ALU, PC, SET_ADDR, ADDR, DP, ALU,
ST_16, src,
WR_HI_INC, ADDR, src,
WR_DEC_LO, ADDR, src);
IRQS = 4;
}
private void EXT_OP_LD_16(ushort dest)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC_OP, ALU2, PC, SET_ADDR, ADDR, ALU, ALU2,
IDLE,
RD_INC, ALU, ADDR,
RD_INC_OP, ALU2, ADDR, LD_16, dest, ALU, ALU2);
IRQS = 5;
}
private void EXT_OP_ST_16(ushort src)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC_OP, ALU2, PC, SET_ADDR, ADDR, ALU, ALU2,
ST_16, src,
WR_HI_INC, ADDR, src,
WR_DEC_LO, ADDR, src);
IRQS = 5;
}
private void EXT_OP_LD_16D()
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC_OP, ALU2, PC, SET_ADDR, ADDR, ALU, ALU2,
IDLE,
RD_INC, A, ADDR,
RD_INC_OP, B, ADDR, LD_16, ADDR, A, B);
IRQS = 5;
}
private void EXT_OP_ST_16D()
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC_OP, ALU2, PC, SET_ADDR, ADDR, ALU, ALU2,
ST_16, Dr,
WR_LO_INC, ADDR, A,
WR, ADDR, B);
IRQS = 5;
}
private void EXT_CMP_16(ushort oper, ushort dest)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC_OP, ALU2, PC, SET_ADDR, ADDR, ALU, ALU2,
RD_INC, ALU, ADDR,
RD, ALU2, ADDR,
SET_ADDR, ADDR, ALU, ALU2,
oper, dest, ADDR);
IRQS = 6;
}
private void EXG_()
{
PopulateCURINSTR(RD_INC, ALU, PC,
EXG, ALU,
IDLE,
IDLE,
IDLE,
IDLE,
IDLE);
IRQS = 7;
}
private void TFR_()
{
PopulateCURINSTR(RD_INC, ALU, PC,
TFR, ALU,
IDLE,
IDLE,
IDLE);
IRQS = 5;
}
private void JMP_DIR_()
{
PopulateCURINSTR(RD_INC, ALU, PC,
SET_ADDR, PC, DP, ALU);
IRQS = 2;
}
private void JMP_EXT_()
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC, ALU2, PC,
SET_ADDR, PC, ALU, ALU2);
IRQS = 3;
}
private void JSR_()
{
PopulateCURINSTR(RD_INC_OP, ALU, PC, SET_ADDR, ADDR, DP, ALU,
TR, ALU, PC,
DEC16, SP,
TR, PC, ADDR,
WR_DEC_LO, SP, ALU,
WR_HI, SP, ALU);
IRQS = 6;
}
private void JSR_EXT()
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC_OP, ALU2, PC, SET_ADDR, ADDR, ALU, ALU2,
TR, ALU, PC,
DEC16, SP,
TR, PC, ADDR,
WR_DEC_LO, SP, ALU,
WR_HI, SP, ALU);
IRQS = 7;
}
private void LBR_(bool cond)
{
if (cond)
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC, ALU2, PC,
SET_ADDR, ADDR, ALU, ALU2,
ADD16BR, PC, ADDR);
IRQS = 4;
}
else
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC, ALU2, PC,
SET_ADDR, ADDR, ALU, ALU2);
IRQS = 3;
}
}
private void BR_(bool cond)
{
if (cond)
{
PopulateCURINSTR(RD_INC, ALU, PC,
ADD8BR, PC, ALU);
IRQS = 2;
}
else
{
PopulateCURINSTR(RD_INC, ALU, PC,
IDLE);
IRQS = 2;
}
}
private void BSR_()
{
PopulateCURINSTR(RD_INC, ALU, PC,
TR, ADDR, PC,
ADD8BR, PC, ALU,
DEC16, SP,
WR_DEC_LO, SP, ADDR,
WR_HI, SP, ADDR);
IRQS = 6;
}
private void LBSR_()
{
PopulateCURINSTR(RD_INC, ALU, PC,
RD_INC, ALU2, PC,
SET_ADDR, ADDR, ALU, ALU2,
TR, ALU, PC,
ADD16BR, PC, ADDR,
DEC16, SP,
WR_DEC_LO, SP, ALU,
WR_HI, SP, ALU);
IRQS = 8;
}
private void PAGE_2()
{
PopulateCURINSTR(OP_PG_2);
IRQS = -1;
}
private void PAGE_3()
{
PopulateCURINSTR(OP_PG_3);
IRQS = -1;
}
private void ABX_()
{
PopulateCURINSTR(ABX,
IDLE);
IRQS = 2;
}
private void MUL_()
{
PopulateCURINSTR(MUL,
IDLE,
IDLE,
IDLE,
IDLE,
IDLE,
IDLE,
IDLE,
IDLE,
IDLE);
IRQS = 10;
}
private void RTS()
{
PopulateCURINSTR(IDLE,
RD_INC, ALU, SP,
RD_INC, ALU2, SP,
SET_ADDR, PC, ALU, ALU2);
IRQS = 4;
}
private void RTI()
{
PopulateCURINSTR(IDLE,
RD_INC_OP, CC, SP, JPE,
RD_INC, A, SP,
RD_INC, B, SP,
RD_INC, DP, SP,
RD_INC, ALU, SP,
RD_INC_OP, ALU2, SP, SET_ADDR, X, ALU, ALU2,
RD_INC, ALU, SP,
RD_INC_OP, ALU2, SP, SET_ADDR, Y, ALU, ALU2,
RD_INC, ALU, SP,
RD_INC_OP, ALU2, SP, SET_ADDR, US, ALU, ALU2,
RD_INC, ALU, SP,
RD_INC_OP, ALU2, SP, SET_ADDR, PC, ALU, ALU2);
IRQS = 14;
}
private void PSH(ushort src)
{
PopulateCURINSTR(RD_INC, ALU, PC,
IDLE,
DEC16, src,
PSH_n, src);
IRQS = -1;
}
// Post byte info is in ALU
// mask out bits until the end
private void PSH_n_BLD(ushort src)
{
if (Regs[ALU].Bit(7))
{
PopulateCURINSTR(WR_DEC_LO, src, PC,
WR_DEC_HI_OP, src, PC, PSH_n, src);
Regs[ALU] &= 0x7F;
}
else if (Regs[ALU].Bit(6))
{
if (src == US)
{
PopulateCURINSTR(WR_DEC_LO, src, SP,
WR_DEC_HI_OP, src, SP, PSH_n, src);
}
else
{
PopulateCURINSTR(WR_DEC_LO, src, US,
WR_DEC_HI_OP, src, US, PSH_n, src);
}
Regs[ALU] &= 0x3F;
}
else if (Regs[ALU].Bit(5))
{
PopulateCURINSTR(WR_DEC_LO, src, Y,
WR_DEC_HI_OP, src, Y, PSH_n, src);
Regs[ALU] &= 0x1F;
}
else if (Regs[ALU].Bit(4))
{
PopulateCURINSTR(WR_DEC_LO, src, X,
WR_DEC_HI_OP, src, X, PSH_n, src);
Regs[ALU] &= 0xF;
}
else if (Regs[ALU].Bit(3))
{
PopulateCURINSTR(WR_DEC_LO_OP, src, DP, PSH_n, src);
Regs[ALU] &= 0x7;
}
else if (Regs[ALU].Bit(2))
{
PopulateCURINSTR(WR_DEC_LO_OP, src, B, PSH_n, src);
Regs[ALU] &= 0x3;
}
else if (Regs[ALU].Bit(1))
{
PopulateCURINSTR(WR_DEC_LO_OP, src, A, PSH_n, src);
Regs[ALU] &= 0x1;
}
else if (Regs[ALU].Bit(0))
{
PopulateCURINSTR(WR_DEC_LO_OP, src, CC, PSH_n, src);
Regs[ALU] = 0;
}
else
{
Regs[src] += 1; // we decremented an extra time overall, regardless of what was run
IRQS = irq_pntr + 1;
}
instr_pntr = 0;
}
private void PUL(ushort src)
{
PopulateCURINSTR(RD_INC, ALU, PC,
IDLE,
PUL_n, src);
IRQS = -1;
}
// Post byte info is in ALU
// mask out bits until the end
private void PUL_n_BLD(ushort src)
{
if (Regs[ALU].Bit(0))
{
PopulateCURINSTR(RD_INC_OP, CC, src, PUL_n, src);
Regs[ALU] &= 0xFE;
}
else if (Regs[ALU].Bit(1))
{
PopulateCURINSTR(RD_INC_OP, A, src, PUL_n, src);
Regs[ALU] &= 0xFC;
}
else if (Regs[ALU].Bit(2))
{
PopulateCURINSTR(RD_INC_OP, B, src, PUL_n, src);
Regs[ALU] &= 0xF8;
}
else if (Regs[ALU].Bit(3))
{
PopulateCURINSTR(RD_INC_OP, DP, src, PUL_n, src);
Regs[ALU] &= 0xF0;
}
else if (Regs[ALU].Bit(4))
{
PopulateCURINSTR(RD_INC, ALU2, src,
RD_INC_OP, ADDR, src, SET_ADDR_PUL, X, src);
Regs[ALU] &= 0xE0;
}
else if (Regs[ALU].Bit(5))
{
PopulateCURINSTR(RD_INC, ALU2, src,
RD_INC_OP, ADDR, src, SET_ADDR_PUL, Y, src);
Regs[ALU] &= 0xC0;
}
else if (Regs[ALU].Bit(6))
{
if (src == US)
{
PopulateCURINSTR(RD_INC, ALU2, src,
RD_INC_OP, ADDR, src, SET_ADDR_PUL, SP, src);
}
else
{
PopulateCURINSTR(RD_INC, ALU2, src,
RD_INC_OP, ADDR, src, SET_ADDR_PUL, US, src);
}
Regs[ALU] &= 0x80;
}
else if (Regs[ALU].Bit(7))
{
PopulateCURINSTR(RD_INC, ALU2, src,
RD_INC_OP, ADDR, src, SET_ADDR_PUL, PC, src);
Regs[ALU] = 0;
}
else
{
// extra end cycle
PopulateCURINSTR(IDLE);
IRQS = irq_pntr + 2;
}
instr_pntr = 0;
}
private void SWI1()
{
Regs[ADDR] = 0xFFFA;
PopulateCURINSTR(SET_E,
DEC16, SP,
WR_DEC_LO, SP, PC,
WR_DEC_HI, SP, PC,
WR_DEC_LO, SP, US,
WR_DEC_HI, SP, US,
WR_DEC_LO, SP, Y,
WR_DEC_HI, SP, Y,
WR_DEC_LO, SP, X,
WR_DEC_HI, SP, X,
WR_DEC_LO, SP, DP,
WR_DEC_LO, SP, B,
WR_DEC_LO, SP, A,
WR, SP, CC,
SET_F_I,
RD_INC, ALU, ADDR,
RD_INC, ALU2, ADDR,
SET_ADDR, PC, ALU, ALU2);
IRQS = 18;
}
private void SWI2_3(ushort pick)
{
Regs[ADDR] = (ushort)((pick == 3) ? 0xFFF2 : 0xFFF4);
PopulateCURINSTR(SET_E,
DEC16, SP,
WR_DEC_LO, SP, PC,
WR_DEC_HI, SP, PC,
WR_DEC_LO, SP, US,
WR_DEC_HI, SP, US,
WR_DEC_LO, SP, Y,
WR_DEC_HI, SP, Y,
WR_DEC_LO, SP, X,
WR_DEC_HI, SP, X,
WR_DEC_LO, SP, DP,
WR_DEC_LO, SP, B,
WR_DEC_LO, SP, A,
WR, SP, CC,
IDLE,
RD_INC, ALU, ADDR,
RD_INC, ALU2, ADDR,
SET_ADDR, PC, ALU, ALU2);
IRQS = 18;
}
private void CWAI_()
{
PopulateCURINSTR(RD_INC_OP, ALU, PC, ANDCC, ALU,
SET_E,
DEC16, SP,
WR_DEC_LO, SP, PC,
WR_DEC_HI, SP, PC,
WR_DEC_LO, SP, US,
WR_DEC_HI, SP, US,
WR_DEC_LO, SP, Y,
WR_DEC_HI, SP, Y,
WR_DEC_LO, SP, X,
WR_DEC_HI, SP, X,
WR_DEC_LO, SP, DP,
WR_DEC_LO, SP, B,
WR_DEC_LO, SP, A,
WR, SP, CC,
CWAI);
IRQS = 16;
}
}
}
| 18.661581 | 87 | 0.554887 | [
"MIT"
] | Diefool/BizHawk | BizHawk.Emulation.Cores/CPUs/MC6809/OP_Tables.cs | 13,455 | C# |
//------------------------------------------------------------------------------
// TDBaseName.cs
// Copyright 2019 2019/2/18
// Created by CYM on 2019/2/18
// Owner: CYM
// 填写类的描述...
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace CYM
{
//Person head icon part enum
public enum PHIPart
{
PBare,
PEye,
PNose,
PHair,
PMouse,
PBrow,
PHelmet,
PBody,
PBeard,
PDecorate,
PBG,
PFrame,
}
[Serializable]
public class GenderInfo
{
BaseGRMgr GRMgr => BaseGlobal.GRMgr;
#region Config
public string Name { get; set; } = "";
public HashList<PartInfo> PBare { get; set; } = new HashList<PartInfo>();
public HashList<PartInfo> PEye { get; set; } = new HashList<PartInfo>();
public HashList<PartInfo> PNose { get; set; } = new HashList<PartInfo>();
public HashList<PartInfo> PHair { get; set; } = new HashList<PartInfo>();
public HashList<PartInfo> PMouse { get; set; } = new HashList<PartInfo>();
public HashList<PartInfo> PBrow { get; set; } = new HashList<PartInfo>();
public HashList<PartInfo> PBeard { get; set; } = new HashList<PartInfo>();
public HashList<PartInfo> PBody { get; set; } = new HashList<PartInfo>();
public HashList<PartInfo> PDecorate { get; set; } = new HashList<PartInfo>();
public HashList<PartInfo> PBG { get; set; } = new HashList<PartInfo>();
public HashList<PartInfo> PHelmet { get; set; } = new HashList<PartInfo>();
public HashList<PartInfo> PFrame { get; set; } = new HashList<PartInfo>();
#endregion
#region parsed
Dictionary<string, HashList<PartInfo>> SBare { get; set; } = new Dictionary<string, HashList<PartInfo>>();
Dictionary<string, HashList<PartInfo>> SEye { get; set; } = new Dictionary<string, HashList<PartInfo>>();
Dictionary<string, HashList<PartInfo>> SNose { get; set; } = new Dictionary<string, HashList<PartInfo>>();
Dictionary<string, HashList<PartInfo>> SHair { get; set; } = new Dictionary<string, HashList<PartInfo>>();
Dictionary<string, HashList<PartInfo>> SMouse { get; set; } = new Dictionary<string, HashList<PartInfo>>();
Dictionary<string, HashList<PartInfo>> SBrow { get; set; } = new Dictionary<string, HashList<PartInfo>>();
Dictionary<string, HashList<PartInfo>> SBeard { get; set; } = new Dictionary<string, HashList<PartInfo>>();
Dictionary<string, HashList<PartInfo>> SBody { get; set; } = new Dictionary<string, HashList<PartInfo>>();
Dictionary<string, HashList<PartInfo>> SDecorate { get; set; } = new Dictionary<string, HashList<PartInfo>>();
Dictionary<string, HashList<PartInfo>> SBG { get; set; } = new Dictionary<string, HashList<PartInfo>>();
Dictionary<string, HashList<PartInfo>> SHelmet { get; set; } = new Dictionary<string, HashList<PartInfo>>();
Dictionary<string, HashList<PartInfo>> SFrame { get; set; } = new Dictionary<string, HashList<PartInfo>>();
HashList<string> Rope = new HashList<string>();
public List<string> NameKeys { get; private set; } = new List<string>();
#endregion
#region get
public HashList<PartInfo> GetSBare(string tag) => GetPartInfo(tag, PBare, SBare);
public HashList<PartInfo> GetSEye(string tag) => GetPartInfo(tag, PEye, SEye);
public HashList<PartInfo> GetSNose(string tag) => GetPartInfo(tag, PNose, SNose);
public HashList<PartInfo> GetSHair(string tag) => GetPartInfo(tag, PHair, SHair);
public HashList<PartInfo> GetSMouse(string tag) => GetPartInfo(tag, PMouse, SMouse);
public HashList<PartInfo> GetSBrow(string tag) => GetPartInfo(tag, PBrow, SBrow);
public HashList<PartInfo> GetSBeard(string tag) => GetPartInfo(tag, PBeard, SBeard);
public HashList<PartInfo> GetSBody(string tag) => GetPartInfo(tag, PBody, SBody);
public HashList<PartInfo> GetSDecorate(string tag) => GetPartInfo(tag, PDecorate, SDecorate);
public HashList<PartInfo> GetSBG(string tag) => GetPartInfo(tag, PBG, SBG);
public HashList<PartInfo> GetSHelmet(string tag) => GetPartInfo(tag, PHelmet, SHelmet);
public HashList<PartInfo> GetSFrame(string tag) => GetPartInfo(tag, PFrame, SFrame);
private HashList<PartInfo> GetPartInfo(string tag, HashList<PartInfo> pdata, Dictionary<string, HashList<PartInfo>> sdata)
{
if (tag == Const.PTag_Normal) return pdata;
if (sdata.ContainsKey(tag)) return sdata[tag];
return pdata;
}
#endregion
#region parse
public void Parse()
{
ParseTag(PBare, SBare);
ParseTag(PEye, SEye);
ParseTag(PNose, SNose);
ParseTag(PHair, SHair);
ParseTag(PMouse, SMouse);
ParseTag(PBrow, SBrow);
ParseTag(PBeard, SBeard);
ParseTag(PBody, SBody);
ParseTag(PDecorate, SDecorate);
ParseTag(PBG, SBG);
ParseTag(PHelmet, SHelmet);
ParseTag(PFrame, SFrame);
NameKeys = BaseLanguageMgr.GetCategory(Name);
}
void ParseTag(List<PartInfo> info, Dictionary<string, HashList<PartInfo>> sinfo)
{
foreach (var item2 in info)
{
//加入年龄Tag
Enum<AgeRange>.For(x =>
{
string tagAge = x.ToString();
HashList<PartInfo> temp;
if (sinfo.ContainsKey(tagAge)) temp = sinfo[tagAge];
else
{
temp = new HashList<PartInfo>();
sinfo.Add(tagAge, temp);
}
var addtionName = item2.Name + "_" + tagAge;
if (GRMgr.Head.IsHave(addtionName))
{
PartInfo newPartInfo = item2.Clone() as PartInfo;
newPartInfo.Name = addtionName;
temp.Add(newPartInfo);
}
});
//加入自定义Tag
if (item2.Tag == null) continue;
foreach (var tag in item2.Tag)
{
HashList<PartInfo> temp;
if (sinfo.ContainsKey(tag)) temp = sinfo[tag];
else
{
temp = new HashList<PartInfo>();
sinfo.Add(tag, temp);
}
temp.Add(item2);
if (tag == Const.PTag_Rope)
Rope.Add(item2.Name);
}
}
info.RemoveAll((x) =>
{
return !x.IsIn;
});
}
#endregion
#region is
public bool IsRope(string id)
{
if (Rope.Contains(id))
return true;
return false;
}
#endregion
}
[Serializable]
public class PartInfo : ICloneable
{
public string Name { get; set; } = Const.STR_Inv;
//是否在随机列表中
public bool IsIn { get; set; } = true;
public HashList<string> Tag { get; set; } = new HashList<string>();
public object Clone()
{
return this.MemberwiseClone();
}
}
[Serializable]
public class TDBaseNameData : TDBaseData
{
#region config
public string Splite { get; set; } = "";
public string Last { get; set; } = "";
public GenderInfo Male { get; set; } = new GenderInfo();
public GenderInfo Female { get; set; } = new GenderInfo();
#endregion
#region prop
List<string> All { get; set; } = new List<string>();
public List<string> LastNameKeys { get; private set; } = new List<string>();
#endregion
#region life
public override void OnBeAddedToData()
{
base.OnBeAddedToData();
LastNameKeys.Clear();
LastNameKeys = BaseLanguageMgr.GetCategory(Last);
All.Clear();
All.AddRange(Male.NameKeys);
All.AddRange(Female.NameKeys);
All.AddRange(LastNameKeys);
Male.Parse();
Female.Parse();
}
#endregion
#region get
public string GetPersonName(TDBasePersonData person)
{
string ret = "";
string splite = "";
string firstName = "";
if (!BaseLanguageMgr.Space.IsInv()) splite = BaseLanguageMgr.Space;
else splite = Splite;
if (CustomName.IsInv()) firstName = person.FirstName.GetName();
else firstName = CustomName;
ret = person.LastName.GetName() + splite + firstName;
return ret;
}
public string RandFirstNameKey(Gender gender)
{
return GetInfo(gender).NameKeys.Rand();
}
public string RandLastNameKey()
{
return LastNameKeys.Rand();
}
// 只获得名称
public string RandName(bool isTrans = false)
{
string ret = RandUtil.RandArray(All);
if (isTrans) return BaseLanguageMgr.Get(ret);
return ret;
}
public Dictionary<PHIPart, string> RandHeadIcon(Gender gender, string tag)
{
Dictionary<PHIPart, string> ret = new Dictionary<PHIPart, string>();
RandPart(PHIPart.PBare, ref ret);
RandPart(PHIPart.PEye, ref ret);
RandPart(PHIPart.PNose, ref ret);
RandPart(PHIPart.PHair, ref ret);
RandPart(PHIPart.PMouse, ref ret);
RandPart(PHIPart.PBrow, ref ret);
RandPart(PHIPart.PBeard, ref ret);
RandPart(PHIPart.PHelmet, ref ret);
RandPart(PHIPart.PBody, ref ret);
RandPart(PHIPart.PDecorate, ref ret);
RandPart(PHIPart.PBG, ref ret);
RandPart(PHIPart.PFrame, ref ret);
return ret;
void RandPart(PHIPart part, ref Dictionary<PHIPart, string> data)
{
List<PartInfo> parts = GetParts(part);
var key = parts.Rand();
if (key == null) key = new PartInfo();
data.Add(part, key.Name);
}
List<PartInfo> GetParts(PHIPart part)
{
var info = GetInfo(gender);
//Face
if (part == PHIPart.PBare) return info.GetSBare(tag);
else if (part == PHIPart.PEye) return info.GetSEye(tag);
else if (part == PHIPart.PHair) return info.GetSHair(tag);
else if (part == PHIPart.PNose) return info.GetSNose(tag);
else if (part == PHIPart.PMouse) return info.GetSMouse(tag);
else if (part == PHIPart.PBrow) return info.GetSBrow(tag);
else if (part == PHIPart.PBeard) return info.GetSBeard(tag);
//其他
else if (part == PHIPart.PBG) return info.GetSBG(tag);
else if (part == PHIPart.PBody) return info.GetSBody(tag);
else if (part == PHIPart.PDecorate) return info.GetSDecorate(tag);
else if (part == PHIPart.PFrame) return info.GetSFrame(tag);
else if (part == PHIPart.PHelmet) return info.GetSHelmet(tag);
return new List<PartInfo>();
}
}
public GenderInfo GetInfo(Gender gender)
{
GenderInfo info = new GenderInfo();
if (gender == Gender.Female) info = Female;
else if (gender == Gender.Male) info = Male;
return info;
}
#endregion
}
public class TDBaseName<TData> : TDBaseConfig<TData>
where TData : TDBaseNameData, new()
{
public HashList<string> AllLastName { get; private set; } = new HashList<string>();
public override void OnLuaParseEnd()
{
base.OnLuaParseEnd();
AllLastName.Clear();
foreach (var item in Data)
{
AllLastName.AddRange(item.Value.LastNameKeys);
}
}
}
} | 39.830128 | 130 | 0.54454 | [
"MIT"
] | chengyimingvb/CYMUni | Plugins/_CYM/_Base/TableDatas/TDBaseName.cs | 12,487 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
using Xunity.ScriptableReferences;
using Object = UnityEngine.Object;
namespace Xunity.ScriptableFunctions
{
[CreateAssetMenu(menuName = BASE_MENU + "Vector3FromComponent")]
public class Vector3FromComponent : ScriptableFunction<Component, Vector3>
{
[SerializeField] Method method;
[SerializeField] FloatReference scale = FloatReference.New(true, 1);
[SerializeField] Vector3Reference axisScale = Vector3Reference.New(true, Vector3.one);
readonly Dictionary<Component, Object> cache = new Dictionary<Component, Object>();
enum Method
{
Position = 0,
LocalPosition = 1,
RbVelocity = 10,
Rb2Velocity = 11,
}
public override Vector3 Invoke(Component key)
{
return GetVector3(key).Multiply(axisScale) * scale;
}
Vector3 GetVector3(Component key)
{
switch (method)
{
case Method.Position:
return GetValueFromCache<Transform>(key, GetPosition);
case Method.LocalPosition:
return GetValueFromCache<Transform>(key, GetLocalPosition);
case Method.RbVelocity:
return GetValueFromCache<Rigidbody>(key, GetRbVelocity);
case Method.Rb2Velocity:
return GetValueFromCache<Rigidbody2D>(key, GetRb2Velocity);
default:
throw new ArgumentOutOfRangeException();
}
}
static Vector3 GetPosition(Transform transform)
{
return transform.position;
}
static Vector3 GetLocalPosition(Transform transform)
{
return transform.localPosition;
}
static Vector3 GetRbVelocity(Rigidbody rb)
{
return rb.velocity;
}
static Vector3 GetRb2Velocity(Rigidbody2D rb2)
{
return rb2.velocity;
}
Vector3 GetValueFromCache<T>(Component key, Func<T, Vector3> getter) where T : Object
{
var cached = GetCachedComponent<T>(key);
return cached ? getter(cached) : default(Vector3);
}
T GetCachedComponent<T>(Component key) where T : Object
{
Object cachedValue;
T component;
if (cache.TryGetValue(key, out cachedValue))
{
component = cachedValue as T;
if (component == null)
cache.Remove(key);
else
return component;
}
component = key.GetComponent<T>();
if (component == null)
return default(T);
cache.Add(key, component);
return component;
}
}
} | 30.547368 | 94 | 0.564094 | [
"Unlicense"
] | ixi150/Xunity | ScriptableFunctions/Vector3FromComponent.cs | 2,902 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. 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.
* 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 TencentCloud.Cdb.V20170320.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeTagsOfInstanceIdsRequest : AbstractModel
{
/// <summary>
/// 实例列表。
/// </summary>
[JsonProperty("InstanceIds")]
public string[] InstanceIds{ get; set; }
/// <summary>
/// 分页偏移量。
/// </summary>
[JsonProperty("Offset")]
public long? Offset{ get; set; }
/// <summary>
/// 分页大小。
/// </summary>
[JsonProperty("Limit")]
public long? Limit{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamArraySimple(map, prefix + "InstanceIds.", this.InstanceIds);
this.SetParamSimple(map, prefix + "Offset", this.Offset);
this.SetParamSimple(map, prefix + "Limit", this.Limit);
}
}
}
| 29.862069 | 85 | 0.618938 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Cdb/V20170320/Models/DescribeTagsOfInstanceIdsRequest.cs | 1,764 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the lex-models-2017-04-19.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.LexModelBuildingService.Model
{
/// <summary>
/// Provides information about a bot alias.
/// </summary>
public partial class BotAliasMetadata
{
private string _botName;
private string _botVersion;
private string _checksum;
private ConversationLogsResponse _conversationLogs;
private DateTime? _createdDate;
private string _description;
private DateTime? _lastUpdatedDate;
private string _name;
/// <summary>
/// Gets and sets the property BotName.
/// <para>
/// The name of the bot to which the alias points.
/// </para>
/// </summary>
[AWSProperty(Min=2, Max=50)]
public string BotName
{
get { return this._botName; }
set { this._botName = value; }
}
// Check to see if BotName property is set
internal bool IsSetBotName()
{
return this._botName != null;
}
/// <summary>
/// Gets and sets the property BotVersion.
/// <para>
/// The version of the Amazon Lex bot to which the alias points.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=64)]
public string BotVersion
{
get { return this._botVersion; }
set { this._botVersion = value; }
}
// Check to see if BotVersion property is set
internal bool IsSetBotVersion()
{
return this._botVersion != null;
}
/// <summary>
/// Gets and sets the property Checksum.
/// <para>
/// Checksum of the bot alias.
/// </para>
/// </summary>
public string Checksum
{
get { return this._checksum; }
set { this._checksum = value; }
}
// Check to see if Checksum property is set
internal bool IsSetChecksum()
{
return this._checksum != null;
}
/// <summary>
/// Gets and sets the property ConversationLogs.
/// <para>
/// Settings that determine how Amazon Lex uses conversation logs for the alias.
/// </para>
/// </summary>
public ConversationLogsResponse ConversationLogs
{
get { return this._conversationLogs; }
set { this._conversationLogs = value; }
}
// Check to see if ConversationLogs property is set
internal bool IsSetConversationLogs()
{
return this._conversationLogs != null;
}
/// <summary>
/// Gets and sets the property CreatedDate.
/// <para>
/// The date that the bot alias was created.
/// </para>
/// </summary>
public DateTime CreatedDate
{
get { return this._createdDate.GetValueOrDefault(); }
set { this._createdDate = value; }
}
// Check to see if CreatedDate property is set
internal bool IsSetCreatedDate()
{
return this._createdDate.HasValue;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// A description of the bot alias.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=200)]
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property LastUpdatedDate.
/// <para>
/// The date that the bot alias was updated. When you create a resource, the creation
/// date and last updated date are the same.
/// </para>
/// </summary>
public DateTime LastUpdatedDate
{
get { return this._lastUpdatedDate.GetValueOrDefault(); }
set { this._lastUpdatedDate = value; }
}
// Check to see if LastUpdatedDate property is set
internal bool IsSetLastUpdatedDate()
{
return this._lastUpdatedDate.HasValue;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of the bot alias.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=100)]
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
}
} | 30.169231 | 109 | 0.540711 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/LexModelBuildingService/Generated/Model/BotAliasMetadata.cs | 5,883 | C# |
using System;
using System.IO;
namespace Memoria.Prime.Ini
{
public sealed class StringIniValue : IniValue
{
public String Value;
public StringIniValue(String name)
: base(name)
{
}
public override void ParseValue(String rawString)
{
Value = rawString;
}
public override void WriteValue(StreamWriter sw)
{
sw.Write(Value);
}
}
} | 18.44 | 57 | 0.548807 | [
"MIT"
] | Albeoris/Memoria | Memoria.Prime/Ini/StringIniValue.cs | 463 | C# |
using UnityEngine;
using System.Collections.Generic;
using System;
public class Chatty : MonoBehaviour {
// The font to use.
public Font font;
// The object that displays the sprites.
public GameObject background;
// The backgrounds to display.
private Sprite[] sprites;
// Questions/answers/moods
private string[] questions;
private string[] answers;
private int[] moods;
private int questionIdx;
// [0,1]
// The current mood.
private float mood = 1;
// Whether the buttons are being hovered over.
private bool[] hoverOnButton;
// The last stable mood.
private int lastStableSpriteIndex;
// The temporary mood.
private int temporarySpriteIndex;
// The time for the transition between moods.
private float transitionPeriod = .75f;
// The time in the current transition, or 0 if there is no transition at the moment.
private float transitionTime = 0;
void Start() {
questions = new string[]{
"Hello, my prince.",
"What do you think about the new flowers in the garden?",
"They're imported from Westeros... the flowers, I mean.",
"And the bedsheets... I think I prefer the silk ones over the Egyptian cotton ones.",
"Did you want to attend the Eriksen dinner party next week? I hear they're serving Kobe lobster.",
"It's been a while since we've gone riding together. Would you like to go later this evening?",
"Does this robe make me look fat?",
"The oracle says she sees many offspring in our future.",
"We don't even talk any more. We don't even know what we argue about.",
"Are you happy?",
};
answers = new string[]{
"Hello, my darling.",
"Hey.",
"(Head Nod)",
"What was that, darling?",
"They seem nice.",
"The blue ones are quite striking, but pale in comparison to your beautiful eyes.",
"Nice.",
"Nice!",
"Noice!",
"Then we should go with the silk ones. They do seem warmer.",
"Cool with me.",
"Honestly, I could not care less.",
"Do I have a choice?",
"Of course! I know you and the Eriksens are like besties.",
"You know how I feel about crustaceans. How is that not like eating giant insects?",
"Yes.",
"No.",
"Well, we kind of did when we visited your aunt last week...",
"Yes.",
"Not more than usual.",
"You make the robe look good.",
"That's wonderful, darling!",
"That bitch crazy.",
"...",
"Some people work things out and some just don't know how to change.",
"Let's don't wait 'til the water runs dry.",
"This stream dried up a long time ago, baby.",
"Yes.",
"No.",
"Define \"happy\".",
};
moods = new int[]{
2,
1,
0,
0,
1,
2,
0,
1,
2,
2,
1,
0,
0,
2,
1,
2,
0,
1,
1,
0,
2,
2,
0,
1,
2,
0,
1,
2,
0,
1,
};
sprites = new Sprite[]{
Resources.Load<Sprite>("chatty/chatty-0"),
Resources.Load<Sprite>("chatty/chatty-1"),
Resources.Load<Sprite>("chatty/chatty-2"),
Resources.Load<Sprite>("chatty/chatty-3"),
Resources.Load<Sprite>("chatty/chatty-4"),
};
hoverOnButton = new bool[]{false, false, false};
// Set the initial color.
var spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
var spriteIndex = getStableSpriteIndex();
lastStableSpriteIndex = spriteIndex;
spriteRenderer.sprite = sprites[spriteIndex];
}
// Returns the sprite index of the stable sprite for the current mood.
private int getStableSpriteIndex() {
return 2 * (int)(Mathf.Max(1, Mathf.Ceil(mood*3)) - 1);
}
private void commonAnswerUpdate(int answerOffset) {
var moodToDelta = new Dictionary<int, float>{
{0, -.25f},
{1, -.1f},
{2, .25f},
};
var oldMood = mood;
var oldSpriteIndex = getStableSpriteIndex();
// Update the mood.
mood = Mathf.Min(1, Mathf.Max(0, mood + moodToDelta[moods[questionIdx*3 + answerOffset]]));
// Determine which transition to use.
if (mood >= oldMood) {
temporarySpriteIndex = Math.Min(4, oldSpriteIndex + 1);
} else {
temporarySpriteIndex = Math.Max(0, oldSpriteIndex - 1);
}
//Debug.Log("mood:" + mood);
transitionTime = transitionPeriod;
var moodIndex = getStableSpriteIndex();
if (++questionIdx > questions.Length - 1) {
// Move right to the stable mood for the end of the game.
temporarySpriteIndex = moodIndex;
if (moodIndex == 4) {
// Happy
LevelState.levelState = LevelState.State.ChattyHappy;
// Indifferent
} else if (moodIndex == 2) {
LevelState.levelState = LevelState.State.ChattyIndifferent;
} else {
// Sad
LevelState.levelState = LevelState.State.ChattySad;
}
Application.LoadLevel(5);
}
}
void OnGUI() {
if (questionIdx > questions.Length - 1) {
return;
}
GUI.skin.button.wordWrap = true;
// Clear button backgrounds.
GUI.backgroundColor = new Color(1,1,1,0);
// Make the font
GUI.skin.label.fontSize = Screen.width / 31;
GUI.skin.button.fontSize = Screen.width / 40;
GUI.skin.label.font = font;
GUI.skin.button.font = GUI.skin.label.font;
// Default text color.
var labelAndHighlightColor = new Color(0.184f, 0.341f, 0.498f, 1);
GUI.contentColor = labelAndHighlightColor;
// Text alignment.
GUI.skin.label.alignment = TextAnchor.MiddleCenter;
GUI.skin.button.alignment = TextAnchor.MiddleLeft;
// Pad the label and buttons.
int padding = Screen.width/25;
GUI.skin.label.padding = new RectOffset(padding, padding, 0, 0);
GUI.skin.button.padding = new RectOffset(padding, padding, 0, 0);
// Display the question label.
var buttonAreaSize = new Vector2(Screen.width*.575f, Screen.height*.45f);
GUI.Label(new Rect(0,
Screen.height - buttonAreaSize.y,
Screen.width - buttonAreaSize.x - Screen.width * .05f,
buttonAreaSize.y - padding/2),
questions[questionIdx]);
// Display/update the buttons.
var buttonIndex = -1;
GUILayout.BeginArea(new Rect(Screen.width - buttonAreaSize.x,
Screen.height - buttonAreaSize.y,
buttonAreaSize.x,
buttonAreaSize.y));
GUI.skin.button.margin = new RectOffset(0,0,0,0);
GUILayout.BeginVertical();
var numButtons = 3;
for (int i=0; i<numButtons; i++) {
// Sets the hover color of a button.
if (hoverOnButton[i]) {
GUI.contentColor = labelAndHighlightColor;
} else {
GUI.contentColor = new Color(0.427f,0.431f,0.439f,1);
}
if (GUILayout.Button(answers[questionIdx*numButtons+i], GUILayout.Height(buttonAreaSize.y/3))) {
buttonIndex = i;
}
if (Event.current.type == EventType.Repaint) {
hoverOnButton[i] = GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition);
}
}
GUILayout.EndVertical();
GUILayout.EndArea();
if (buttonIndex >= 0) {
commonAnswerUpdate(buttonIndex);
}
}
void Update() {
var moodState = getStableSpriteIndex();
var spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
ResizeSpriteToScreen(background, Camera.main, 1, 1);
Action<int> render = state => spriteRenderer.sprite = sprites[state];
if (transitionTime > 0) {
transitionTime -= Time.deltaTime;
render(temporarySpriteIndex);
} else {
render(moodState);
}
}
private void ResizeSpriteToScreen(GameObject theSprite,
Camera theCamera,
int fitToScreenWidth,
int fitToScreenHeight) {
SpriteRenderer sr = theSprite.GetComponent<SpriteRenderer>();
theSprite.transform.localScale = new Vector3(1,1,1);
float width = sr.sprite.bounds.size.x;
float height = sr.sprite.bounds.size.y;
float worldScreenHeight = (float)(theCamera.orthographicSize * 2.0);
float worldScreenWidth = (float)(worldScreenHeight / Screen.height * Screen.width);
if (fitToScreenWidth != 0)
{
Vector2 sizeX = new Vector2(worldScreenWidth / width / fitToScreenWidth,theSprite.transform.localScale.y);
theSprite.transform.localScale = sizeX;
}
if (fitToScreenHeight != 0)
{
Vector2 sizeY = new Vector2(theSprite.transform.localScale.x, worldScreenHeight / height / fitToScreenHeight);
theSprite.transform.localScale = sizeY;
}
}
}
| 27.091803 | 113 | 0.652548 | [
"MIT"
] | benoitcorda/GameJam | Assets/Scripts/Chatty.cs | 8,263 | C# |
using Foosball.Services;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Foosball.Extensions
{
public static class RepositoryServiceExtention
{
public static void AddRepository(this IServiceCollection services)
{
services.AddTransient<IRepository, Repository>();
}
}
}
| 23.666667 | 74 | 0.737089 | [
"MIT"
] | DCHRoots/foosball | Foosball/Extensions/RepositoryServiceExtension.cs | 428 | C# |
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Roslynator.Analyzers.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010027004e802c1a5eb763f904a7446ff4b19754f33b9e8ae0046fe19e2c3405b4743c55d38de3f6b61c7dae04b814d01171f2b722a7f5a12d5060506aaf173c40f8ccf81878d1468a722172cb05f4099d8891f1214670d60bc4a6235b66ec04a53f93d8c390d187796eee172535e1a9ed946ce48fff537c1435f7e1aea5e89a31bb")]
[assembly: InternalsVisibleTo("Roslynator.CodeFixes.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100094f4a9a639fd5e875e6517e86f99163ad48615ca8a1935357bbdce2ae4b31b32a4045b09cb3c0ee87bd0c26120c6f94ce0fb00adc4bfe5bc6c18e865d5505e497d9f38d5cb223c0a1977e82f74db9bd48e6de2129344a57b0898e30014521dd6c1d3dabffbbcbe81190737a598e290fdded7ddd9df3516f4d92fc493aa513b8")]
[assembly: InternalsVisibleTo("Roslynator.Refactorings.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100ff5e6943f7503a55c31c082d8fdb88cffb47d587d323d7d8ed5f1d1e6588add35bfb91f8f2dde3f69d1e6e39adbb35cb0fd28f868b8c33ade93b30c27c03bccb00863922286061a8e075f0a84ded2c708b5792c3d207974fb382acdcf8f09b6b4412f5f893ec914d4fb3c364a1f57604883acf9474046386bcb7e9b6d58679bb")]
[assembly: InternalsVisibleTo("Roslynator.Tests.TestConsole, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f10a0a65d7cf36fcf8421994edbc1f6e30cc2d09b8713edccaf6423506cd46963f9f7a5b2a6671834da9446c5c7605bd095bde86918f1f134a4a7b7c4b7ce54b515cfadd1737227bee0b9a6c42f10991228378d07a08114fb8d0c9efcae571f5de5c7b4e0b0d94468d5bef0a30ab4023d1ac32ebb916ce0f3a4bfdb658755cb8")]
| 197.666667 | 395 | 0.944351 | [
"Apache-2.0"
] | IanKemp/Roslynator | src/Tests/TestFramework.VisualBasic/Properties/AssemblyInfo.cs | 1,781 | C# |
using System;
using System.Data;
using System.Diagnostics;
using NUnit.Framework;
using SPSProfessional.SharePoint.Framework.Comms;
namespace SPSProfessional.SharePoint.Framework.Tests.Comms
{
[TestFixture]
public class SPSSchema_Tests
{
[Test]
public void Constructor()
{
SPSSchema schema = new SPSSchema();
Assert.IsNotNull(schema);
Assert.IsNotNull(schema.Schema);
}
[Test]
public void GetTypeFromSqlDbType_All()
{
foreach (object[] type in TestData.SqlDbTratedTypesCastSystemTypes)
{
AssertGetTypeFromSqlDbType((SqlDbType) type[0], (Type) type[1]);
}
}
public void AssertGetTypeFromSqlDbType(SqlDbType sqlDbType, Type expectedType)
{
SPSSchema schema = new SPSSchema();
Trace.WriteLine(string.Format("{0},{1}", expectedType, sqlDbType));
Assert.IsTrue(expectedType == schema.GetSystemTypeFromSqlDbType_Test(sqlDbType.ToString()));
Assert.IsTrue(expectedType == schema.GetSystemTypeFromSqlDbType_Test(sqlDbType));
}
[Test]
public void GetTypeFromSqlDbType_InvalidTypes_All()
{
foreach (object[] type in TestData.SqlDbNoTratedTypes)
{
GetTypeFromSqlDbType_InvalidTypes((SqlDbType) type[0]);
}
}
public void GetTypeFromSqlDbType_InvalidTypes(SqlDbType sqlDbType)
{
SPSSchema schema = new SPSSchema();
Assert.IsNull(schema.GetSystemTypeFromSqlDbType_Test(sqlDbType.ToString()));
Assert.IsNull(schema.GetSystemTypeFromSqlDbType_Test(sqlDbType));
}
[Test]
public void AddParameterSql_All()
{
foreach (object[] type in TestData.SqlDbTratedTypes)
{
AssertAddParameterSql((SqlDbType) type[0]);
}
}
public void AssertAddParameterSql(SqlDbType sqlDbType)
{
SPSSchema schema = new SPSSchema();
schema.AddParameterSql(sqlDbType.ToString(), sqlDbType);
Assert.IsTrue(schema.Schema.Count == 1);
Trace.WriteLine(string.Format("{0}", schema.Schema[0].Name));
Assert.IsTrue(schema.Schema[0].Name == sqlDbType.ToString());
Assert.IsTrue(schema.Schema[0].PropertyType.Equals(schema.GetSystemTypeFromSqlDbType_Test(sqlDbType)));
}
[Test]
public void AddParameterSql_StringType_All()
{
foreach (object[] type in TestData.SqlDbTratedTypes)
{
AssertAddParameterSql_StringType((SqlDbType) type[0]);
}
}
public void AssertAddParameterSql_StringType(SqlDbType sqlDbType)
{
SPSSchema schema = new SPSSchema();
schema.AddParameterSql(sqlDbType.ToString(), sqlDbType.ToString());
Assert.IsTrue(schema.Schema.Count == 1);
Trace.WriteLine(string.Format("{0}", schema.Schema[0].Name));
Assert.IsTrue(schema.Schema[0].Name == sqlDbType.ToString());
Assert.IsTrue(schema.Schema[0].PropertyType.Equals(schema.GetSystemTypeFromSqlDbType_Test(sqlDbType)));
}
[Test]
public void AddParameterSql_NullParameter_All()
{
foreach (object[] type in TestData.SqlDbTratedTypes)
{
AddParameterSql_NullParameter((SqlDbType) type[0]);
}
}
public void AddParameterSql_NullParameter(SqlDbType sqlDbType)
{
SPSSchema schema = new SPSSchema();
schema.AddParameterSql(null, sqlDbType);
Assert.IsTrue(schema.Schema.Count == 1);
Trace.WriteLine(string.Format("{0}", schema.Schema[0].Name));
Assert.IsTrue(schema.Schema[0].PropertyType.Equals(schema.GetSystemTypeFromSqlDbType_Test(sqlDbType)));
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void AddParameterSql_BadType()
{
SPSSchema schema = new SPSSchema();
schema.AddParameterSql("Test", "BadType");
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void AddParameterSql_NullType()
{
SPSSchema schema = new SPSSchema();
schema.AddParameterSql("Test", null);
}
[Test]
//[ExpectedException(typeof(DuplicateNameException))]
public void AddParameterSql_DuplicateType()
{
SPSSchema schema = new SPSSchema();
schema.AddParameterSql("Test", SqlDbType.Int);
schema.AddParameterSql("Test", SqlDbType.Int);
Assert.AreEqual(1,schema.Schema.Count);
}
[Test]
public void AddParameter_All()
{
foreach (object[] type in TestData.AllSystemTypes)
{
AddParameter((Type) type[0]);
}
}
public void AddParameter(Type type)
{
SPSSchema schema = new SPSSchema();
schema.AddParameter(type.ToString(), type);
Assert.IsTrue(schema.Schema.Count == 1);
Trace.WriteLine(string.Format("{0},{1},{2}", type, schema.Schema[0].Name, schema.Schema[0].PropertyType));
Assert.IsTrue(schema.Schema[0].Name == type.ToString());
Assert.IsTrue(schema.Schema[0].PropertyType.Equals(type));
}
[Test]
public void AddParameter_StringType_All()
{
foreach (object[] type in TestData.AllSystemTypes)
{
AddParameter_StringType((Type) type[0]);
}
}
public void AddParameter_StringType(Type type)
{
SPSSchema schema = new SPSSchema();
schema.AddParameter(type.ToString(), type.ToString());
Assert.IsTrue(schema.Schema.Count == 1);
Trace.WriteLine(string.Format("{0},{1},{2}", type, schema.Schema[0].Name, schema.Schema[0].PropertyType));
Assert.IsTrue(schema.Schema[0].Name == type.ToString());
Assert.IsTrue(schema.Schema[0].PropertyType.Equals(type));
}
}
} | 35.522727 | 118 | 0.595649 | [
"MIT"
] | csegura/SPSProfessional-Full-Repo | SPSFramework.2.8/SPSProfessional.SharePoint.Framework.Tests/Comms/SPSSchema_Tests.cs | 6,254 | C# |
using System.Linq;
using Lion.AbpPro.DataDictionaryManagement.DataDictionaries.Aggregates;
using Microsoft.EntityFrameworkCore;
namespace Lion.AbpPro.DataDictionaryManagement.EntityFrameworkCore.DataDictionaries
{
public static class DataDictionaryEfCoreQueryableExtensions
{
public static IQueryable<DataDictionary> IncludeDetails(this IQueryable<DataDictionary> queryable,
bool include = true)
{
if (!include)
{
return queryable;
}
return queryable.Include(x => x.Details);
}
}
} | 29.8 | 107 | 0.677852 | [
"MIT"
] | 312977/abp-vnext-pro | aspnet-core/modules/DataDictionaryManagement/src/Lion.AbpPro.DataDictionaryManagement.EntityFrameworkCore/EntityFrameworkCore/DataDictionaries/DataDictionaryEfCoreQueryableExtensions.cs | 596 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents a named type symbol whose members are declared in source.
/// </summary>
internal abstract partial class SourceMemberContainerTypeSymbol : NamedTypeSymbol
{
// The flags type is used to compact many different bits of information efficiently.
private struct Flags
{
// We current pack everything into two 32-bit ints; layouts for each are given below.
// First int:
//
// | |d|yy|xxxxxxxxxxxxxxxxxxxxxxx|wwwwww|
//
// w = special type. 6 bits.
// x = modifiers. 23 bits.
// y = IsManagedType. 2 bits.
// d = FieldDefinitionsNoted. 1 bit
private const int SpecialTypeOffset = 0;
private const int SpecialTypeSize = 6;
private const int DeclarationModifiersOffset = SpecialTypeSize;
private const int DeclarationModifiersSize = 23;
private const int ManagedKindOffset = DeclarationModifiersOffset + DeclarationModifiersSize;
private const int ManagedKindSize = 2;
private const int FieldDefinitionsNotedOffset = ManagedKindOffset + ManagedKindSize;
private const int FieldDefinitionsNotedSize = 1;
private const int SpecialTypeMask = (1 << SpecialTypeSize) - 1;
private const int DeclarationModifiersMask = (1 << DeclarationModifiersSize) - 1;
private const int ManagedKindMask = (1 << ManagedKindSize) - 1;
private const int FieldDefinitionsNotedBit = 1 << FieldDefinitionsNotedOffset;
private int _flags;
// More flags.
//
// | |zzzz|f|
//
// f = FlattenedMembersIsSorted. 1 bit.
// z = TypeKind. 4 bits.
private const int TypeKindOffset = 1;
private const int TypeKindMask = 0xF;
private const int FlattenedMembersIsSortedBit = 1 << 0;
private int _flags2;
public SpecialType SpecialType
{
get { return (SpecialType)((_flags >> SpecialTypeOffset) & SpecialTypeMask); }
}
public DeclarationModifiers DeclarationModifiers
{
get { return (DeclarationModifiers)((_flags >> DeclarationModifiersOffset) & DeclarationModifiersMask); }
}
public ManagedKind ManagedKind
{
get { return (ManagedKind)((_flags >> ManagedKindOffset) & ManagedKindMask); }
}
public bool FieldDefinitionsNoted
{
get { return (_flags & FieldDefinitionsNotedBit) != 0; }
}
// True if "lazyMembersFlattened" is sorted.
public bool FlattenedMembersIsSorted
{
get { return (_flags2 & FlattenedMembersIsSortedBit) != 0; }
}
public TypeKind TypeKind
{
get { return (TypeKind)((_flags2 >> TypeKindOffset) & TypeKindMask); }
}
#if DEBUG
static Flags()
{
// Verify a few things about the values we combine into flags. This way, if they ever
// change, this will get hit and you will know you have to update this type as well.
// 1) Verify that the range of special types doesn't fall outside the bounds of the
// special type mask.
Debug.Assert(EnumUtilities.ContainsAllValues<SpecialType>(SpecialTypeMask));
// 2) Verify that the range of declaration modifiers doesn't fall outside the bounds of
// the declaration modifier mask.
Debug.Assert(EnumUtilities.ContainsAllValues<DeclarationModifiers>(DeclarationModifiersMask));
}
#endif
public Flags(SpecialType specialType, DeclarationModifiers declarationModifiers, TypeKind typeKind)
{
int specialTypeInt = ((int)specialType & SpecialTypeMask) << SpecialTypeOffset;
int declarationModifiersInt = ((int)declarationModifiers & DeclarationModifiersMask) << DeclarationModifiersOffset;
int typeKindInt = ((int)typeKind & TypeKindMask) << TypeKindOffset;
_flags = specialTypeInt | declarationModifiersInt;
_flags2 = typeKindInt;
}
public void SetFieldDefinitionsNoted()
{
ThreadSafeFlagOperations.Set(ref _flags, FieldDefinitionsNotedBit);
}
public void SetFlattenedMembersIsSorted()
{
ThreadSafeFlagOperations.Set(ref _flags2, (FlattenedMembersIsSortedBit));
}
private static bool BitsAreUnsetOrSame(int bits, int mask)
{
return (bits & mask) == 0 || (bits & mask) == mask;
}
public void SetManagedKind(ManagedKind managedKind)
{
int bitsToSet = ((int)managedKind & ManagedKindMask) << ManagedKindOffset;
Debug.Assert(BitsAreUnsetOrSame(_flags, bitsToSet));
ThreadSafeFlagOperations.Set(ref _flags, bitsToSet);
}
}
protected SymbolCompletionState state;
private Flags _flags;
private readonly NamespaceOrTypeSymbol _containingSymbol;
protected readonly MergedTypeDeclaration declaration;
private MembersAndInitializers _lazyMembersAndInitializers;
private Dictionary<string, ImmutableArray<Symbol>> _lazyMembersDictionary;
private Dictionary<string, ImmutableArray<Symbol>> _lazyEarlyAttributeDecodingMembersDictionary;
private static readonly Dictionary<string, ImmutableArray<NamedTypeSymbol>> s_emptyTypeMembers = new Dictionary<string, ImmutableArray<NamedTypeSymbol>>(EmptyComparer.Instance);
private Dictionary<string, ImmutableArray<NamedTypeSymbol>> _lazyTypeMembers;
private ImmutableArray<Symbol> _lazyMembersFlattened;
private ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> _lazySynthesizedExplicitImplementations;
private int _lazyKnownCircularStruct;
private LexicalSortKey _lazyLexicalSortKey = LexicalSortKey.NotInitialized;
private ThreeState _lazyContainsExtensionMethods;
private ThreeState _lazyAnyMemberHasAttributes;
#region Construction
internal SourceMemberContainerTypeSymbol(
NamespaceOrTypeSymbol containingSymbol,
MergedTypeDeclaration declaration,
DiagnosticBag diagnostics)
{
_containingSymbol = containingSymbol;
this.declaration = declaration;
TypeKind typeKind = declaration.Kind.ToTypeKind();
var modifiers = MakeModifiers(typeKind, diagnostics);
foreach (var singleDeclaration in declaration.Declarations)
{
diagnostics.AddRange(singleDeclaration.Diagnostics);
}
int access = (int)(modifiers & DeclarationModifiers.AccessibilityMask);
if ((access & (access - 1)) != 0)
{ // more than one access modifier
if ((modifiers & DeclarationModifiers.Partial) != 0)
diagnostics.Add(ErrorCode.ERR_PartialModifierConflict, Locations[0], this);
access = access & ~(access - 1); // narrow down to one access modifier
modifiers &= ~DeclarationModifiers.AccessibilityMask; // remove them all
modifiers |= (DeclarationModifiers)access; // except the one
}
var specialType = access == (int)DeclarationModifiers.Public
? MakeSpecialType()
: SpecialType.None;
_flags = new Flags(specialType, modifiers, typeKind);
var containingType = this.ContainingType;
if ((object)containingType != null && containingType.IsSealed && this.DeclaredAccessibility.HasProtected())
{
diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), Locations[0], this);
}
state.NotePartComplete(CompletionPart.TypeArguments); // type arguments need not be computed separately
}
private SpecialType MakeSpecialType()
{
// check if this is one of the COR library types
if (ContainingSymbol.Kind == SymbolKind.Namespace &&
ContainingSymbol.ContainingAssembly.KeepLookingForDeclaredSpecialTypes)
{
//for a namespace, the emitted name is a dot-separated list of containing namespaces
var emittedName = ContainingSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat);
emittedName = MetadataHelpers.BuildQualifiedName(emittedName, MetadataName);
return SpecialTypes.GetTypeFromMetadataName(emittedName);
}
else
{
return SpecialType.None;
}
}
private DeclarationModifiers MakeModifiers(TypeKind typeKind, DiagnosticBag diagnostics)
{
Symbol containingSymbol = this.ContainingSymbol;
DeclarationModifiers defaultAccess;
var allowedModifiers = DeclarationModifiers.AccessibilityMask;
if (containingSymbol.Kind == SymbolKind.Namespace)
{
defaultAccess = DeclarationModifiers.Internal;
}
else
{
allowedModifiers |= DeclarationModifiers.New;
if (((NamedTypeSymbol)containingSymbol).IsInterface)
{
defaultAccess = DeclarationModifiers.Public;
}
else
{
defaultAccess = DeclarationModifiers.Private;
}
}
switch (typeKind)
{
case TypeKind.Class:
case TypeKind.Submission:
allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Static | DeclarationModifiers.Sealed | DeclarationModifiers.Abstract | DeclarationModifiers.Unsafe;
break;
case TypeKind.Struct:
allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Ref | DeclarationModifiers.ReadOnly | DeclarationModifiers.Unsafe;
break;
case TypeKind.Interface:
allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Unsafe;
break;
case TypeKind.Delegate:
allowedModifiers |= DeclarationModifiers.Unsafe;
break;
}
bool modifierErrors;
var mods = MakeAndCheckTypeModifiers(
defaultAccess,
allowedModifiers,
this,
diagnostics,
out modifierErrors);
this.CheckUnsafeModifier(mods, diagnostics);
if (!modifierErrors &&
(mods & DeclarationModifiers.Abstract) != 0 &&
(mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) != 0)
{
diagnostics.Add(ErrorCode.ERR_AbstractSealedStatic, Locations[0], this);
}
if (!modifierErrors &&
(mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) == (DeclarationModifiers.Sealed | DeclarationModifiers.Static))
{
diagnostics.Add(ErrorCode.ERR_SealedStaticClass, Locations[0], this);
}
switch (typeKind)
{
case TypeKind.Interface:
mods |= DeclarationModifiers.Abstract;
break;
case TypeKind.Struct:
case TypeKind.Enum:
mods |= DeclarationModifiers.Sealed;
break;
case TypeKind.Delegate:
mods |= DeclarationModifiers.Sealed;
break;
}
return mods;
}
private DeclarationModifiers MakeAndCheckTypeModifiers(
DeclarationModifiers defaultAccess,
DeclarationModifiers allowedModifiers,
SourceMemberContainerTypeSymbol self,
DiagnosticBag diagnostics,
out bool modifierErrors)
{
modifierErrors = false;
var result = DeclarationModifiers.Unset;
var partCount = declaration.Declarations.Length;
var missingPartial = false;
for (var i = 0; i < partCount; i++)
{
var decl = declaration.Declarations[i];
var mods = decl.Modifiers;
if (partCount > 1 && (mods & DeclarationModifiers.Partial) == 0)
{
missingPartial = true;
}
if (!modifierErrors)
{
mods = ModifierUtils.CheckModifiers(
mods, allowedModifiers, declaration.Declarations[i].NameLocation, diagnostics,
modifierTokens: null, modifierErrors: out modifierErrors);
// It is an error for the same modifier to appear multiple times.
if (!modifierErrors)
{
var info = ModifierUtils.CheckAccessibility(mods, this, isExplicitInterfaceImplementation: false);
if (info != null)
{
diagnostics.Add(info, self.Locations[0]);
modifierErrors = true;
}
}
}
if (result == DeclarationModifiers.Unset)
{
result = mods;
}
else
{
result |= mods;
}
}
if ((result & DeclarationModifiers.AccessibilityMask) == 0)
{
result |= defaultAccess;
}
if (missingPartial)
{
if ((result & DeclarationModifiers.Partial) == 0)
{
// duplicate definitions
switch (self.ContainingSymbol.Kind)
{
case SymbolKind.Namespace:
for (var i = 1; i < partCount; i++)
{
diagnostics.Add(ErrorCode.ERR_DuplicateNameInNS, declaration.Declarations[i].NameLocation, self.Name, self.ContainingSymbol);
modifierErrors = true;
}
break;
case SymbolKind.NamedType:
for (var i = 1; i < partCount; i++)
{
if (ContainingType.Locations.Length == 1 || ContainingType.IsPartial())
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, declaration.Declarations[i].NameLocation, self.ContainingSymbol, self.Name);
modifierErrors = true;
}
break;
}
}
else
{
for (var i = 0; i < partCount; i++)
{
var singleDeclaration = declaration.Declarations[i];
var mods = singleDeclaration.Modifiers;
if ((mods & DeclarationModifiers.Partial) == 0)
{
diagnostics.Add(ErrorCode.ERR_MissingPartial, singleDeclaration.NameLocation, self.Name);
modifierErrors = true;
}
}
}
}
return result;
}
#endregion
#region Completion
internal sealed override bool RequiresCompletion
{
get { return true; }
}
internal sealed override bool HasComplete(CompletionPart part)
{
return state.HasComplete(part);
}
protected abstract void CheckBase(DiagnosticBag diagnostics);
protected abstract void CheckInterfaces(DiagnosticBag diagnostics);
internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken)
{
while (true)
{
// NOTE: cases that depend on GetMembers[ByName] should call RequireCompletionPartMembers.
cancellationToken.ThrowIfCancellationRequested();
var incompletePart = state.NextIncompletePart;
switch (incompletePart)
{
case CompletionPart.Attributes:
GetAttributes();
break;
case CompletionPart.StartBaseType:
case CompletionPart.FinishBaseType:
if (state.NotePartComplete(CompletionPart.StartBaseType))
{
var diagnostics = DiagnosticBag.GetInstance();
CheckBase(diagnostics);
AddDeclarationDiagnostics(diagnostics);
state.NotePartComplete(CompletionPart.FinishBaseType);
diagnostics.Free();
}
break;
case CompletionPart.StartInterfaces:
case CompletionPart.FinishInterfaces:
if (state.NotePartComplete(CompletionPart.StartInterfaces))
{
var diagnostics = DiagnosticBag.GetInstance();
CheckInterfaces(diagnostics);
AddDeclarationDiagnostics(diagnostics);
state.NotePartComplete(CompletionPart.FinishInterfaces);
diagnostics.Free();
}
break;
case CompletionPart.EnumUnderlyingType:
var discarded = this.EnumUnderlyingType;
break;
case CompletionPart.TypeArguments:
{
var tmp = this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; // force type arguments
}
break;
case CompletionPart.TypeParameters:
// force type parameters
foreach (var typeParameter in this.TypeParameters)
{
typeParameter.ForceComplete(locationOpt, cancellationToken);
}
state.NotePartComplete(CompletionPart.TypeParameters);
break;
case CompletionPart.Members:
this.GetMembersByName();
break;
case CompletionPart.TypeMembers:
this.GetTypeMembersUnordered();
break;
case CompletionPart.SynthesizedExplicitImplementations:
this.GetSynthesizedExplicitImplementations(cancellationToken); //force interface and base class errors to be checked
break;
case CompletionPart.StartMemberChecks:
case CompletionPart.FinishMemberChecks:
if (state.NotePartComplete(CompletionPart.StartMemberChecks))
{
var diagnostics = DiagnosticBag.GetInstance();
AfterMembersChecks(diagnostics);
AddDeclarationDiagnostics(diagnostics);
// We may produce a SymbolDeclaredEvent for the enclosing type before events for its contained members
DeclaringCompilation.SymbolDeclaredEvent(this);
var thisThreadCompleted = state.NotePartComplete(CompletionPart.FinishMemberChecks);
Debug.Assert(thisThreadCompleted);
diagnostics.Free();
}
break;
case CompletionPart.MembersCompleted:
{
ImmutableArray<Symbol> members = this.GetMembersUnordered();
bool allCompleted = true;
if (locationOpt == null)
{
foreach (var member in members)
{
cancellationToken.ThrowIfCancellationRequested();
member.ForceComplete(locationOpt, cancellationToken);
}
}
else
{
foreach (var member in members)
{
ForceCompleteMemberByLocation(locationOpt, member, cancellationToken);
allCompleted = allCompleted && member.HasComplete(CompletionPart.All);
}
}
if (!allCompleted)
{
// We did not complete all members so we won't have enough information for
// the PointedAtManagedTypeChecks, so just kick out now.
var allParts = CompletionPart.NamedTypeSymbolWithLocationAll;
state.SpinWaitComplete(allParts, cancellationToken);
return;
}
EnsureFieldDefinitionsNoted();
// We've completed all members, so we're ready for the PointedAtManagedTypeChecks;
// proceed to the next iteration.
state.NotePartComplete(CompletionPart.MembersCompleted);
break;
}
case CompletionPart.None:
return;
default:
// This assert will trigger if we forgot to handle any of the completion parts
Debug.Assert((incompletePart & CompletionPart.NamedTypeSymbolAll) == 0);
// any other values are completion parts intended for other kinds of symbols
state.NotePartComplete(CompletionPart.All & ~CompletionPart.NamedTypeSymbolAll);
break;
}
state.SpinWaitComplete(incompletePart, cancellationToken);
}
throw ExceptionUtilities.Unreachable;
}
internal void EnsureFieldDefinitionsNoted()
{
if (_flags.FieldDefinitionsNoted)
{
return;
}
NoteFieldDefinitions();
}
private void NoteFieldDefinitions()
{
// we must note all fields once therefore we need to lock
lock (this.GetMembersAndInitializers())
{
if (!_flags.FieldDefinitionsNoted)
{
var assembly = (SourceAssemblySymbol)ContainingAssembly;
Accessibility containerEffectiveAccessibility = EffectiveAccessibility();
foreach (var member in _lazyMembersAndInitializers.NonTypeNonIndexerMembers)
{
FieldSymbol field;
if (!member.IsFieldOrFieldLikeEvent(out field) || field.IsConst || field.IsFixedSizeBuffer)
{
continue;
}
Accessibility fieldDeclaredAccessibility = field.DeclaredAccessibility;
if (fieldDeclaredAccessibility == Accessibility.Private)
{
// mark private fields as tentatively unassigned and unread unless we discover otherwise.
assembly.NoteFieldDefinition(field, isInternal: false, isUnread: true);
}
else if (containerEffectiveAccessibility == Accessibility.Private)
{
// mark effectively private fields as tentatively unassigned unless we discover otherwise.
assembly.NoteFieldDefinition(field, isInternal: false, isUnread: false);
}
else if (fieldDeclaredAccessibility == Accessibility.Internal || containerEffectiveAccessibility == Accessibility.Internal)
{
// mark effectively internal fields as tentatively unassigned unless we discover otherwise.
// NOTE: These fields will be reported as unassigned only if internals are not visible from this assembly.
// See property SourceAssemblySymbol.UnusedFieldWarnings.
assembly.NoteFieldDefinition(field, isInternal: true, isUnread: false);
}
}
_flags.SetFieldDefinitionsNoted();
}
}
}
#endregion
#region Containers
public sealed override NamedTypeSymbol ContainingType
{
get
{
return _containingSymbol as NamedTypeSymbol;
}
}
public sealed override Symbol ContainingSymbol
{
get
{
return _containingSymbol;
}
}
#endregion
#region Flags Encoded Properties
public override SpecialType SpecialType
{
get
{
return _flags.SpecialType;
}
}
public override TypeKind TypeKind
{
get
{
return _flags.TypeKind;
}
}
internal MergedTypeDeclaration MergedDeclaration
{
get
{
return this.declaration;
}
}
internal sealed override bool IsInterface
{
get
{
// TypeKind is computed eagerly, so this is cheap.
return this.TypeKind == TypeKind.Interface;
}
}
internal override ManagedKind ManagedKind
{
get
{
var managedKind = _flags.ManagedKind;
if (managedKind == ManagedKind.Unknown)
{
var baseKind = base.ManagedKind;
_flags.SetManagedKind(baseKind);
return baseKind;
}
return managedKind;
}
}
public override bool IsStatic
{
get
{
return (_flags.DeclarationModifiers & DeclarationModifiers.Static) != 0;
}
}
public sealed override bool IsRefLikeType
{
get
{
return (_flags.DeclarationModifiers & DeclarationModifiers.Ref) != 0;
}
}
public override bool IsReadOnly
{
get
{
return (_flags.DeclarationModifiers & DeclarationModifiers.ReadOnly) != 0;
}
}
public override bool IsSealed
{
get
{
return (_flags.DeclarationModifiers & DeclarationModifiers.Sealed) != 0;
}
}
public override bool IsAbstract
{
get
{
return (_flags.DeclarationModifiers & DeclarationModifiers.Abstract) != 0;
}
}
internal bool IsPartial
{
get
{
return (_flags.DeclarationModifiers & DeclarationModifiers.Partial) != 0;
}
}
internal bool IsNew
{
get
{
return (_flags.DeclarationModifiers & DeclarationModifiers.New) != 0;
}
}
public override Accessibility DeclaredAccessibility
{
get
{
return ModifierUtils.EffectiveAccessibility(_flags.DeclarationModifiers);
}
}
/// <summary>
/// Compute the "effective accessibility" of the current class for the purpose of warnings about unused fields.
/// </summary>
private Accessibility EffectiveAccessibility()
{
var result = DeclaredAccessibility;
if (result == Accessibility.Private) return Accessibility.Private;
for (Symbol container = this.ContainingType; (object)container != null; container = container.ContainingType)
{
switch (container.DeclaredAccessibility)
{
case Accessibility.Private:
return Accessibility.Private;
case Accessibility.Internal:
result = Accessibility.Internal;
continue;
}
}
return result;
}
#endregion
#region Syntax
public override bool IsScriptClass
{
get
{
var kind = this.declaration.Declarations[0].Kind;
return kind == DeclarationKind.Script || kind == DeclarationKind.Submission;
}
}
public override bool IsImplicitClass
{
get
{
return this.declaration.Declarations[0].Kind == DeclarationKind.ImplicitClass;
}
}
public override bool IsImplicitlyDeclared
{
get
{
return IsImplicitClass || IsScriptClass;
}
}
public override int Arity
{
get
{
return declaration.Arity;
}
}
public override string Name
{
get
{
return declaration.Name;
}
}
internal override bool MangleName
{
get
{
return Arity > 0;
}
}
internal override LexicalSortKey GetLexicalSortKey()
{
if (!_lazyLexicalSortKey.IsInitialized)
{
_lazyLexicalSortKey.SetFrom(declaration.GetLexicalSortKey(this.DeclaringCompilation));
}
return _lazyLexicalSortKey;
}
public override ImmutableArray<Location> Locations
{
get
{
return declaration.NameLocations.Cast<SourceLocation, Location>();
}
}
public ImmutableArray<SyntaxReference> SyntaxReferences
{
get
{
return this.declaration.SyntaxReferences;
}
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return SyntaxReferences;
}
}
// This method behaves the same was as the base class, but avoids allocations associated with DeclaringSyntaxReferences
internal override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken)
{
var declarations = declaration.Declarations;
if (IsImplicitlyDeclared && declarations.IsEmpty)
{
return ContainingSymbol.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken);
}
foreach (var declaration in declarations)
{
cancellationToken.ThrowIfCancellationRequested();
var syntaxRef = declaration.SyntaxReference;
if (syntaxRef.SyntaxTree == tree &&
(!definedWithinSpan.HasValue || syntaxRef.Span.IntersectsWith(definedWithinSpan.Value)))
{
return true;
}
}
return false;
}
#endregion
#region Members
/// <summary>
/// Encapsulates information about the non-type members of a (i.e. this) type.
/// 1) For non-initializers, symbols are created and stored in a list.
/// 2) For fields and properties, the symbols are stored in (1) and their initializers are
/// stored with other initialized fields and properties from the same syntax tree with
/// the same static-ness.
/// 3) For indexers, syntax (weak) references are stored for later binding.
/// </summary>
/// <remarks>
/// CONSIDER: most types won't have indexers, so we could move the indexer list
/// into a subclass to spare most instances the space required for the field.
/// </remarks>
private sealed class MembersAndInitializers
{
internal readonly ImmutableArray<Symbol> NonTypeNonIndexerMembers;
internal readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers;
internal readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers;
internal readonly ImmutableArray<SyntaxReference> IndexerDeclarations;
internal readonly int StaticInitializersSyntaxLength;
internal readonly int InstanceInitializersSyntaxLength;
public MembersAndInitializers(
ImmutableArray<Symbol> nonTypeNonIndexerMembers,
ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> staticInitializers,
ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> instanceInitializers,
ImmutableArray<SyntaxReference> indexerDeclarations,
int staticInitializersSyntaxLength,
int instanceInitializersSyntaxLength)
{
Debug.Assert(!nonTypeNonIndexerMembers.IsDefault);
Debug.Assert(!staticInitializers.IsDefault);
Debug.Assert(!instanceInitializers.IsDefault);
Debug.Assert(!indexerDeclarations.IsDefault);
Debug.Assert(!nonTypeNonIndexerMembers.Any(s => s is TypeSymbol));
Debug.Assert(!nonTypeNonIndexerMembers.Any(s => s.IsIndexer()));
Debug.Assert(!nonTypeNonIndexerMembers.Any(s => s.IsAccessor() && ((MethodSymbol)s).AssociatedSymbol.IsIndexer()));
Debug.Assert(staticInitializersSyntaxLength == staticInitializers.Sum(s => s.Sum(i => (i.FieldOpt == null || !i.FieldOpt.IsMetadataConstant) ? i.Syntax.Span.Length : 0)));
Debug.Assert(instanceInitializersSyntaxLength == instanceInitializers.Sum(s => s.Sum(i => i.Syntax.Span.Length)));
this.NonTypeNonIndexerMembers = nonTypeNonIndexerMembers;
this.StaticInitializers = staticInitializers;
this.InstanceInitializers = instanceInitializers;
this.IndexerDeclarations = indexerDeclarations;
this.StaticInitializersSyntaxLength = staticInitializersSyntaxLength;
this.InstanceInitializersSyntaxLength = instanceInitializersSyntaxLength;
}
}
internal ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers
{
get { return GetMembersAndInitializers().StaticInitializers; }
}
internal ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers
{
get { return GetMembersAndInitializers().InstanceInitializers; }
}
internal int CalculateSyntaxOffsetInSynthesizedConstructor(int position, SyntaxTree tree, bool isStatic)
{
if (IsScriptClass && !isStatic)
{
int aggregateLength = 0;
foreach (var declaration in this.declaration.Declarations)
{
var syntaxRef = declaration.SyntaxReference;
if (tree == syntaxRef.SyntaxTree)
{
return aggregateLength + position;
}
aggregateLength += syntaxRef.Span.Length;
}
throw ExceptionUtilities.Unreachable;
}
int syntaxOffset;
if (TryCalculateSyntaxOffsetOfPositionInInitializer(position, tree, isStatic, ctorInitializerLength: 0, syntaxOffset: out syntaxOffset))
{
return syntaxOffset;
}
if (declaration.Declarations.Length >= 1 && position == declaration.Declarations[0].Location.SourceSpan.Start)
{
// With dynamic analysis instrumentation, the introducing declaration of a type can provide
// the syntax associated with both the analysis payload local of a synthesized constructor
// and with the constructor itself. If the synthesized constructor includes an initializer with a lambda,
// that lambda needs a closure that captures the analysis payload of the constructor,
// and the offset of the syntax for the local within the constructor is by definition zero.
return 0;
}
// an implicit constructor has no body and no initializer, so the variable has to be declared in a member initializer
throw ExceptionUtilities.Unreachable;
}
/// <summary>
/// Calculates a syntax offset of a syntax position that is contained in a property or field initializer (if it is in fact contained in one).
/// </summary>
internal bool TryCalculateSyntaxOffsetOfPositionInInitializer(int position, SyntaxTree tree, bool isStatic, int ctorInitializerLength, out int syntaxOffset)
{
Debug.Assert(ctorInitializerLength >= 0);
var membersAndInitializers = GetMembersAndInitializers();
var allInitializers = isStatic ? membersAndInitializers.StaticInitializers : membersAndInitializers.InstanceInitializers;
var siblingInitializers = GetInitializersInSourceTree(tree, allInitializers);
int index = IndexOfInitializerContainingPosition(siblingInitializers, position);
if (index < 0)
{
syntaxOffset = 0;
return false;
}
// |<-----------distanceFromCtorBody----------->|
// [ initializer 0 ][ initializer 1 ][ initializer 2 ][ctor initializer][ctor body]
// |<--preceding init len-->| ^
// position
int initializersLength = isStatic ? membersAndInitializers.StaticInitializersSyntaxLength : membersAndInitializers.InstanceInitializersSyntaxLength;
int distanceFromInitializerStart = position - siblingInitializers[index].Syntax.Span.Start;
int distanceFromCtorBody =
initializersLength + ctorInitializerLength -
(siblingInitializers[index].PrecedingInitializersLength + distanceFromInitializerStart);
Debug.Assert(distanceFromCtorBody > 0);
// syntax offset 0 is at the start of the ctor body:
syntaxOffset = -distanceFromCtorBody;
return true;
}
private static ImmutableArray<FieldOrPropertyInitializer> GetInitializersInSourceTree(SyntaxTree tree, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers)
{
var builder = ArrayBuilder<FieldOrPropertyInitializer>.GetInstance();
foreach (var siblingInitializers in initializers)
{
Debug.Assert(!siblingInitializers.IsEmpty);
if (siblingInitializers[0].Syntax.SyntaxTree == tree)
{
builder.AddRange(siblingInitializers);
}
}
return builder.ToImmutableAndFree();
}
private static int IndexOfInitializerContainingPosition(ImmutableArray<FieldOrPropertyInitializer> initializers, int position)
{
// Search for the start of the span (the spans are non-overlapping and sorted)
int index = initializers.BinarySearch(position, (initializer, pos) => initializer.Syntax.Span.Start.CompareTo(pos));
// Binary search returns non-negative result if the position is exactly the start of some span.
if (index >= 0)
{
return index;
}
// Otherwise, ~index is the closest span whose start is greater than the position.
// => Check if the preceding initializer span contains the position.
int precedingInitializerIndex = ~index - 1;
if (precedingInitializerIndex >= 0 && initializers[precedingInitializerIndex].Syntax.Span.Contains(position))
{
return precedingInitializerIndex;
}
return -1;
}
public override IEnumerable<string> MemberNames
{
get { return this.declaration.MemberNames; }
}
internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered()
{
return GetTypeMembersDictionary().Flatten();
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers()
{
return GetTypeMembersDictionary().Flatten(LexicalOrderSymbolComparer.Instance);
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name)
{
ImmutableArray<NamedTypeSymbol> members;
if (GetTypeMembersDictionary().TryGetValue(name, out members))
{
return members;
}
return ImmutableArray<NamedTypeSymbol>.Empty;
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity)
{
return GetTypeMembers(name).WhereAsArray(t => t.Arity == arity);
}
private Dictionary<string, ImmutableArray<NamedTypeSymbol>> GetTypeMembersDictionary()
{
if (_lazyTypeMembers == null)
{
var diagnostics = DiagnosticBag.GetInstance();
if (Interlocked.CompareExchange(ref _lazyTypeMembers, MakeTypeMembers(diagnostics), null) == null)
{
AddDeclarationDiagnostics(diagnostics);
state.NotePartComplete(CompletionPart.TypeMembers);
}
diagnostics.Free();
}
return _lazyTypeMembers;
}
private Dictionary<string, ImmutableArray<NamedTypeSymbol>> MakeTypeMembers(DiagnosticBag diagnostics)
{
var symbols = ArrayBuilder<NamedTypeSymbol>.GetInstance();
var conflictDict = new Dictionary<(string, int), SourceNamedTypeSymbol>();
try
{
foreach (var childDeclaration in declaration.Children)
{
var t = new SourceNamedTypeSymbol(this, childDeclaration, diagnostics);
this.CheckMemberNameDistinctFromType(t, diagnostics);
var key = (t.Name, t.Arity);
SourceNamedTypeSymbol other;
if (conflictDict.TryGetValue(key, out other))
{
if (Locations.Length == 1 || IsPartial)
{
if (t.IsPartial && other.IsPartial)
{
diagnostics.Add(ErrorCode.ERR_PartialTypeKindConflict, t.Locations[0], t);
}
else
{
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, t.Locations[0], this, t.Name);
}
}
}
else
{
conflictDict.Add(key, t);
}
symbols.Add(t);
}
if (IsInterface)
{
foreach (var t in symbols)
{
Binder.CheckFeatureAvailability(t.DeclaringSyntaxReferences[0].GetSyntax(), MessageID.IDS_DefaultInterfaceImplementation, diagnostics, t.Locations[0]);
}
}
Debug.Assert(s_emptyTypeMembers.Count == 0);
return symbols.Count > 0 ?
symbols.ToDictionary(s => s.Name, StringOrdinalComparer.Instance) :
s_emptyTypeMembers;
}
finally
{
symbols.Free();
}
}
private void CheckMemberNameDistinctFromType(Symbol member, DiagnosticBag diagnostics)
{
switch (this.TypeKind)
{
case TypeKind.Class:
case TypeKind.Struct:
if (member.Name == this.Name)
{
diagnostics.Add(ErrorCode.ERR_MemberNameSameAsType, member.Locations[0], this.Name);
}
break;
case TypeKind.Interface:
if (member.IsStatic)
{
goto case TypeKind.Class;
}
break;
}
}
internal override ImmutableArray<Symbol> GetMembersUnordered()
{
var result = _lazyMembersFlattened;
if (result.IsDefault)
{
result = GetMembersByName().Flatten(null); // do not sort.
ImmutableInterlocked.InterlockedInitialize(ref _lazyMembersFlattened, result);
result = _lazyMembersFlattened;
}
return result.ConditionallyDeOrder();
}
public override ImmutableArray<Symbol> GetMembers()
{
if (_flags.FlattenedMembersIsSorted)
{
return _lazyMembersFlattened;
}
else
{
var allMembers = this.GetMembersUnordered();
if (allMembers.Length > 1)
{
// The array isn't sorted. Sort it and remember that we sorted it.
allMembers = allMembers.Sort(LexicalOrderSymbolComparer.Instance);
ImmutableInterlocked.InterlockedExchange(ref _lazyMembersFlattened, allMembers);
}
_flags.SetFlattenedMembersIsSorted();
return allMembers;
}
}
public sealed override ImmutableArray<Symbol> GetMembers(string name)
{
ImmutableArray<Symbol> members;
if (GetMembersByName().TryGetValue(name, out members))
{
return members;
}
return ImmutableArray<Symbol>.Empty;
}
internal override ImmutableArray<Symbol> GetSimpleNonTypeMembers(string name)
{
if (_lazyMembersDictionary != null || declaration.MemberNames.Contains(name))
{
return GetMembers(name);
}
return ImmutableArray<Symbol>.Empty;
}
internal override IEnumerable<FieldSymbol> GetFieldsToEmit()
{
if (this.TypeKind == TypeKind.Enum)
{
// For consistency with Dev10, emit value__ field first.
var valueField = ((SourceNamedTypeSymbol)this).EnumValueField;
Debug.Assert((object)valueField != null);
yield return valueField;
}
foreach (var m in this.GetMembers())
{
switch (m.Kind)
{
case SymbolKind.Field:
yield return (FieldSymbol)m;
break;
case SymbolKind.Event:
FieldSymbol associatedField = ((EventSymbol)m).AssociatedField;
if ((object)associatedField != null)
{
yield return associatedField;
}
break;
}
}
}
/// <summary>
/// During early attribute decoding, we consider a safe subset of all members that will not
/// cause cyclic dependencies. Get all such members for this symbol.
///
/// In particular, this method will return nested types and fields (other than auto-property
/// backing fields).
/// </summary>
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers()
{
return GetEarlyAttributeDecodingMembersDictionary().Flatten();
}
/// <summary>
/// During early attribute decoding, we consider a safe subset of all members that will not
/// cause cyclic dependencies. Get all such members for this symbol that have a particular name.
///
/// In particular, this method will return nested types and fields (other than auto-property
/// backing fields).
/// </summary>
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name)
{
ImmutableArray<Symbol> result;
return GetEarlyAttributeDecodingMembersDictionary().TryGetValue(name, out result) ? result : ImmutableArray<Symbol>.Empty;
}
private Dictionary<string, ImmutableArray<Symbol>> GetEarlyAttributeDecodingMembersDictionary()
{
if (_lazyEarlyAttributeDecodingMembersDictionary == null)
{
var membersAndInitializers = GetMembersAndInitializers(); //NOTE: separately cached
// NOTE: members were added in a single pass over the syntax, so they're already
// in lexical order.
var membersByName = membersAndInitializers.NonTypeNonIndexerMembers.ToDictionary(s => s.Name);
AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary());
Interlocked.CompareExchange(ref _lazyEarlyAttributeDecodingMembersDictionary, membersByName, null);
}
return _lazyEarlyAttributeDecodingMembersDictionary;
}
// NOTE: this method should do as little work as possible
// we often need to get members just to do a lookup.
// All additional checks and diagnostics may be not
// needed yet or at all.
private MembersAndInitializers GetMembersAndInitializers()
{
var membersAndInitializers = _lazyMembersAndInitializers;
if (membersAndInitializers != null)
{
return membersAndInitializers;
}
var diagnostics = DiagnosticBag.GetInstance();
membersAndInitializers = BuildMembersAndInitializers(diagnostics);
var alreadyKnown = Interlocked.CompareExchange(ref _lazyMembersAndInitializers, membersAndInitializers, null);
if (alreadyKnown != null)
{
diagnostics.Free();
return alreadyKnown;
}
AddDeclarationDiagnostics(diagnostics);
diagnostics.Free();
return membersAndInitializers;
}
protected Dictionary<string, ImmutableArray<Symbol>> GetMembersByName()
{
if (this.state.HasComplete(CompletionPart.Members))
{
return _lazyMembersDictionary;
}
return GetMembersByNameSlow();
}
private Dictionary<string, ImmutableArray<Symbol>> GetMembersByNameSlow()
{
if (_lazyMembersDictionary == null)
{
var diagnostics = DiagnosticBag.GetInstance();
var membersDictionary = MakeAllMembers(diagnostics);
if (Interlocked.CompareExchange(ref _lazyMembersDictionary, membersDictionary, null) == null)
{
var memberNames = ArrayBuilder<string>.GetInstance(membersDictionary.Count);
memberNames.AddRange(membersDictionary.Keys);
MergePartialMembers(memberNames, membersDictionary, diagnostics);
memberNames.Free();
AddDeclarationDiagnostics(diagnostics);
state.NotePartComplete(CompletionPart.Members);
}
diagnostics.Free();
}
state.SpinWaitComplete(CompletionPart.Members, default(CancellationToken));
return _lazyMembersDictionary;
}
internal override IEnumerable<Symbol> GetInstanceFieldsAndEvents()
{
var membersAndInitializers = this.GetMembersAndInitializers();
return membersAndInitializers.NonTypeNonIndexerMembers.Where(IsInstanceFieldOrEvent);
}
protected void AfterMembersChecks(DiagnosticBag diagnostics)
{
if (IsInterface)
{
CheckInterfaceMembers(this.GetMembersAndInitializers().NonTypeNonIndexerMembers, diagnostics);
}
CheckMemberNamesDistinctFromType(diagnostics);
CheckMemberNameConflicts(diagnostics);
CheckSpecialMemberErrors(diagnostics);
CheckTypeParameterNameConflicts(diagnostics);
CheckAccessorNameConflicts(diagnostics);
bool unused = KnownCircularStruct;
CheckSequentialOnPartialType(diagnostics);
CheckForProtectedInStaticClass(diagnostics);
CheckForUnmatchedOperators(diagnostics);
var location = Locations[0];
if (this.IsRefLikeType)
{
this.DeclaringCompilation.EnsureIsByRefLikeAttributeExists(diagnostics, location, modifyCompilation: true);
}
if (this.IsReadOnly)
{
this.DeclaringCompilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true);
}
// https://github.com/dotnet/roslyn/issues/30080: Report diagnostics for base type and interfaces at more specific locations.
var baseType = BaseTypeNoUseSiteDiagnostics;
var interfaces = InterfacesNoUseSiteDiagnostics();
if (baseType?.NeedsNullableAttribute() == true ||
interfaces.Any(t => t.NeedsNullableAttribute()))
{
this.DeclaringCompilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: true);
}
}
private void CheckMemberNamesDistinctFromType(DiagnosticBag diagnostics)
{
foreach (var member in GetMembersAndInitializers().NonTypeNonIndexerMembers)
{
CheckMemberNameDistinctFromType(member, diagnostics);
}
}
private void CheckMemberNameConflicts(DiagnosticBag diagnostics)
{
Dictionary<string, ImmutableArray<Symbol>> membersByName = GetMembersByName();
// Collisions involving indexers are handled specially.
CheckIndexerNameConflicts(diagnostics, membersByName);
// key and value will be the same object in these dictionaries.
var methodsBySignature = new Dictionary<SourceMemberMethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.DuplicateSourceComparer);
var conversionsAsMethods = new Dictionary<SourceMemberMethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.DuplicateSourceComparer);
var conversionsAsConversions = new HashSet<SourceUserDefinedConversionSymbol>(ConversionSignatureComparer.Comparer);
// SPEC: The signature of an operator must differ from the signatures of all other
// SPEC: operators declared in the same class.
// DELIBERATE SPEC VIOLATION:
// The specification does not state that a user-defined conversion reserves the names
// op_Implicit or op_Explicit, but nevertheless the native compiler does so; an attempt
// to define a field or a conflicting method with the metadata name of a user-defined
// conversion is an error. We preserve this reasonable behavior.
//
// Similarly, we treat "public static C operator +(C, C)" as colliding with
// "public static C op_Addition(C, C)". Fortunately, this behavior simply
// falls out of treating user-defined operators as ordinary methods; we do
// not need any special handling in this method.
//
// However, we must have special handling for conversions because conversions
// use a completely different rule for detecting collisions between two
// conversions: conversion signatures consist only of the source and target
// types of the conversions, and not the kind of the conversion (implicit or explicit),
// the name of the method, and so on.
//
// Therefore we must detect the following kinds of member name conflicts:
//
// 1. a method, conversion or field has the same name as a (different) field (* see note below)
// 2. a method has the same method signature as another method or conversion
// 3. a conversion has the same conversion signature as another conversion.
//
// However, we must *not* detect "a conversion has the same *method* signature
// as another conversion" because conversions are allowed to overload on
// return type but methods are not.
//
// (*) NOTE: Throughout the rest of this method I will use "field" as a shorthand for
// "non-method, non-conversion, non-type member", rather than spelling out
// "field, property or event...")
foreach (var pair in membersByName)
{
var name = pair.Key;
Symbol lastSym = GetTypeMembers(name).FirstOrDefault();
methodsBySignature.Clear();
// Conversion collisions do not consider the name of the conversion,
// so do not clear that dictionary.
foreach (var symbol in pair.Value)
{
if (symbol.Kind == SymbolKind.NamedType ||
symbol.IsAccessor() ||
symbol.IsIndexer())
{
continue;
}
// We detect the first category of conflict by running down the list of members
// of the same name, and producing an error when we discover any of the following
// "bad transitions".
//
// * a method or conversion that comes after any field (not necessarily directly)
// * a field directly following a field
// * a field directly following a method or conversion
//
// Furthermore: we do not wish to detect collisions between nested types in
// this code; that is tested elsewhere. However, we do wish to detect a collision
// between a nested type and a field, method or conversion. Therefore we
// initialize our "bad transition" detector with a type of the given name,
// if there is one. That way we also detect the transitions of "method following
// type", and so on.
//
// The "lastSym" local below is used to detect these transitions. Its value is
// one of the following:
//
// * a nested type of the given name, or
// * the first method of the given name, or
// * the most recently processed field of the given name.
//
// If either the current symbol or the "last symbol" are not methods then
// there must be a collision:
//
// * if the current symbol is not a method and the last symbol is, then
// there is a field directly following a method of the same name
// * if the current symbol is a method and the last symbol is not, then
// there is a method directly or indirectly following a field of the same name,
// or a method of the same name as a nested type.
// * if neither are methods then either we have a field directly
// following a field of the same name, or a field and a nested type of the same name.
//
if ((object)lastSym != null)
{
if (symbol.Kind != SymbolKind.Method || lastSym.Kind != SymbolKind.Method)
{
if (symbol.Kind != SymbolKind.Field || !symbol.IsImplicitlyDeclared)
{
// The type '{0}' already contains a definition for '{1}'
if (Locations.Length == 1 || IsPartial)
{
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, symbol.Locations[0], this, symbol.Name);
}
}
if (lastSym.Kind == SymbolKind.Method)
{
lastSym = symbol;
}
}
}
else
{
lastSym = symbol;
}
// That takes care of the first category of conflict; we detect the
// second and third categories as follows:
var conversion = symbol as SourceUserDefinedConversionSymbol;
var method = symbol as SourceMemberMethodSymbol;
if ((object)conversion != null)
{
// Does this conversion collide *as a conversion* with any previously-seen
// conversion?
if (!conversionsAsConversions.Add(conversion))
{
// CS0557: Duplicate user-defined conversion in type 'C'
diagnostics.Add(ErrorCode.ERR_DuplicateConversionInClass, conversion.Locations[0], this);
}
else
{
// The other set might already contain a conversion which would collide
// *as a method* with the current conversion.
if (!conversionsAsMethods.ContainsKey(conversion))
{
conversionsAsMethods.Add(conversion, conversion);
}
}
// Does this conversion collide *as a method* with any previously-seen
// non-conversion method?
SourceMemberMethodSymbol previousMethod;
if (methodsBySignature.TryGetValue(conversion, out previousMethod))
{
ReportMethodSignatureCollision(diagnostics, conversion, previousMethod);
}
// Do not add the conversion to the set of previously-seen methods; that set
// is only non-conversion methods.
}
else if ((object)method != null)
{
// Does this method collide *as a method* with any previously-seen
// conversion?
SourceMemberMethodSymbol previousConversion;
if (conversionsAsMethods.TryGetValue(method, out previousConversion))
{
ReportMethodSignatureCollision(diagnostics, method, previousConversion);
}
// Do not add the method to the set of previously-seen conversions.
// Does this method collide *as a method* with any previously-seen
// non-conversion method?
SourceMemberMethodSymbol previousMethod;
if (methodsBySignature.TryGetValue(method, out previousMethod))
{
ReportMethodSignatureCollision(diagnostics, method, previousMethod);
}
else
{
// We haven't seen this method before. Make a note of it in case
// we see a colliding method later.
methodsBySignature.Add(method, method);
}
}
}
}
}
// Report a name conflict; the error is reported on the location of method1.
// UNDONE: Consider adding a secondary location pointing to the second method.
private void ReportMethodSignatureCollision(DiagnosticBag diagnostics, SourceMemberMethodSymbol method1, SourceMemberMethodSymbol method2)
{
// Partial methods are allowed to collide by signature.
if (method1.IsPartial && method2.IsPartial)
{
return;
}
// If method1 is a constructor only because its return type is missing, then
// we've already produced a diagnostic for the missing return type and we suppress the
// diagnostic about duplicate signature.
if (method1.MethodKind == MethodKind.Constructor &&
((ConstructorDeclarationSyntax)method1.SyntaxRef.GetSyntax()).Identifier.ValueText != this.Name)
{
return;
}
Debug.Assert(method1.ParameterCount == method2.ParameterCount);
for (int i = 0; i < method1.ParameterCount; i++)
{
var refKind1 = method1.Parameters[i].RefKind;
var refKind2 = method2.Parameters[i].RefKind;
if (refKind1 != refKind2)
{
// '{0}' cannot define an overloaded {1} that differs only on parameter modifiers '{2}' and '{3}'
var methodKind = method1.MethodKind == MethodKind.Constructor ? MessageID.IDS_SK_CONSTRUCTOR : MessageID.IDS_SK_METHOD;
diagnostics.Add(ErrorCode.ERR_OverloadRefKind, method1.Locations[0], this, methodKind.Localize(), refKind1.ToParameterDisplayString(), refKind2.ToParameterDisplayString());
return;
}
}
// Special case: if there are two destructors, use the destructor syntax instead of "Finalize"
var methodName = (method1.MethodKind == MethodKind.Destructor && method2.MethodKind == MethodKind.Destructor) ?
"~" + this.Name :
method1.Name;
// Type '{1}' already defines a member called '{0}' with the same parameter types
diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, method1.Locations[0], methodName, this);
}
private void CheckIndexerNameConflicts(DiagnosticBag diagnostics, Dictionary<string, ImmutableArray<Symbol>> membersByName)
{
PooledHashSet<string> typeParameterNames = null;
if (this.Arity > 0)
{
typeParameterNames = PooledHashSet<string>.GetInstance();
foreach (TypeParameterSymbol typeParameter in this.TypeParameters)
{
typeParameterNames.Add(typeParameter.Name);
}
}
var indexersBySignature = new Dictionary<PropertySymbol, PropertySymbol>(MemberSignatureComparer.DuplicateSourceComparer);
// Note: Can't assume that all indexers are called WellKnownMemberNames.Indexer because
// they may be explicit interface implementations.
foreach (var members in membersByName.Values)
{
string lastIndexerName = null;
indexersBySignature.Clear();
foreach (var symbol in members)
{
if (symbol.IsIndexer())
{
PropertySymbol indexer = (PropertySymbol)symbol;
CheckIndexerSignatureCollisions(
indexer,
diagnostics,
membersByName,
indexersBySignature,
ref lastIndexerName);
// Also check for collisions with type parameters, which aren't in the member map.
// NOTE: Accessors have normal names and are handled in CheckTypeParameterNameConflicts.
if (typeParameterNames != null)
{
string indexerName = indexer.MetadataName;
if (typeParameterNames.Contains(indexerName))
{
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.Locations[0], this, indexerName);
continue;
}
}
}
}
}
typeParameterNames?.Free();
}
private void CheckIndexerSignatureCollisions(
PropertySymbol indexer,
DiagnosticBag diagnostics,
Dictionary<string, ImmutableArray<Symbol>> membersByName,
Dictionary<PropertySymbol, PropertySymbol> indexersBySignature,
ref string lastIndexerName)
{
if (!indexer.IsExplicitInterfaceImplementation) //explicit implementation names are not checked
{
string indexerName = indexer.MetadataName;
if (lastIndexerName != null && lastIndexerName != indexerName)
{
// NOTE: dev10 checks indexer names by comparing each to the previous.
// For example, if indexers are declared with names A, B, A, B, then there
// will be three errors - one for each time the name is different from the
// previous one. If, on the other hand, the names are A, A, B, B, then
// there will only be one error because only one indexer has a different
// name from the previous one.
diagnostics.Add(ErrorCode.ERR_InconsistentIndexerNames, indexer.Locations[0]);
}
lastIndexerName = indexerName;
if (Locations.Length == 1 || IsPartial)
{
if (membersByName.ContainsKey(indexerName))
{
// The name of the indexer is reserved - it can only be used by other indexers.
Debug.Assert(!membersByName[indexerName].Any(SymbolExtensions.IsIndexer));
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.Locations[0], this, indexerName);
}
}
}
PropertySymbol prevIndexerBySignature;
if (indexersBySignature.TryGetValue(indexer, out prevIndexerBySignature))
{
// Type '{1}' already defines a member called '{0}' with the same parameter types
// NOTE: Dev10 prints "this" as the name of the indexer.
diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, indexer.Locations[0], SyntaxFacts.GetText(SyntaxKind.ThisKeyword), this);
}
else
{
indexersBySignature[indexer] = indexer;
}
}
private void CheckSpecialMemberErrors(DiagnosticBag diagnostics)
{
var conversions = new TypeConversions(this.ContainingAssembly.CorLibrary);
foreach (var member in this.GetMembersUnordered())
{
member.AfterAddingTypeMembersChecks(conversions, diagnostics);
}
}
private void CheckTypeParameterNameConflicts(DiagnosticBag diagnostics)
{
if (this.TypeKind == TypeKind.Delegate)
{
// Delegates do not have conflicts between their type parameter
// names and their methods; it is legal (though odd) to say
// delegate void D<Invoke>(Invoke x);
return;
}
if (Locations.Length == 1 || IsPartial)
{
foreach (var tp in TypeParameters)
{
foreach (var dup in GetMembers(tp.Name))
{
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, dup.Locations[0], this, tp.Name);
}
}
}
}
private void CheckAccessorNameConflicts(DiagnosticBag diagnostics)
{
// Report errors where property and event accessors
// conflict with other members of the same name.
foreach (Symbol symbol in this.GetMembersUnordered())
{
if (symbol.IsExplicitInterfaceImplementation())
{
// If there's a name conflict it will show up as a more specific
// interface implementation error.
continue;
}
switch (symbol.Kind)
{
case SymbolKind.Property:
{
var propertySymbol = (PropertySymbol)symbol;
this.CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: true, diagnostics: diagnostics);
this.CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: false, diagnostics: diagnostics);
break;
}
case SymbolKind.Event:
{
var eventSymbol = (EventSymbol)symbol;
this.CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: true, diagnostics: diagnostics);
this.CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: false, diagnostics: diagnostics);
break;
}
}
}
}
internal override bool KnownCircularStruct
{
get
{
if (_lazyKnownCircularStruct == (int)ThreeState.Unknown)
{
if (TypeKind != TypeKind.Struct)
{
Interlocked.CompareExchange(ref _lazyKnownCircularStruct, (int)ThreeState.False, (int)ThreeState.Unknown);
}
else
{
var diagnostics = DiagnosticBag.GetInstance();
var value = (int)CheckStructCircularity(diagnostics).ToThreeState();
if (Interlocked.CompareExchange(ref _lazyKnownCircularStruct, value, (int)ThreeState.Unknown) == (int)ThreeState.Unknown)
{
AddDeclarationDiagnostics(diagnostics);
}
Debug.Assert(value == _lazyKnownCircularStruct);
diagnostics.Free();
}
}
return _lazyKnownCircularStruct == (int)ThreeState.True;
}
}
private bool CheckStructCircularity(DiagnosticBag diagnostics)
{
Debug.Assert(TypeKind == TypeKind.Struct);
CheckFiniteFlatteningGraph(diagnostics);
return HasStructCircularity(diagnostics);
}
private bool HasStructCircularity(DiagnosticBag diagnostics)
{
foreach (var valuesByName in GetMembersByName().Values)
{
foreach (var member in valuesByName)
{
if (member.Kind != SymbolKind.Field)
{
// NOTE: don't have to check field-like events, because they can't have struct types.
continue;
}
var field = (FieldSymbol)member;
if (field.IsStatic)
{
continue;
}
var type = field.NonPointerType();
if (((object)type != null) &&
(type.TypeKind == TypeKind.Struct) &&
BaseTypeAnalysis.StructDependsOn((NamedTypeSymbol)type, this) &&
!type.IsPrimitiveRecursiveStruct()) // allow System.Int32 to contain a field of its own type
{
// If this is a backing field, report the error on the associated property.
var symbol = field.AssociatedSymbol ?? field;
if (symbol.Kind == SymbolKind.Parameter)
{
// We should stick to members for this error.
symbol = field;
}
// Struct member '{0}' of type '{1}' causes a cycle in the struct layout
diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, symbol.Locations[0], symbol, type);
return true;
}
}
}
return false;
}
private void CheckForProtectedInStaticClass(DiagnosticBag diagnostics)
{
if (!IsStatic)
{
return;
}
// no protected members allowed
foreach (var valuesByName in GetMembersByName().Values)
{
foreach (var member in valuesByName)
{
if (member is TypeSymbol)
{
// Duplicate Dev10's failure to diagnose this error.
continue;
}
if (member.DeclaredAccessibility.HasProtected())
{
if (member.Kind != SymbolKind.Method || ((MethodSymbol)member).MethodKind != MethodKind.Destructor)
{
diagnostics.Add(ErrorCode.ERR_ProtectedInStatic, member.Locations[0], member);
}
}
}
}
}
private void CheckForUnmatchedOperators(DiagnosticBag diagnostics)
{
// SPEC: The true and false unary operators require pairwise declaration.
// SPEC: A compile-time error occurs if a class or struct declares one
// SPEC: of these operators without also declaring the other.
//
// SPEC DEFICIENCY: The line of the specification quoted above should say
// the same thing as the lines below: that the formal parameters of the
// paired true/false operators must match exactly. You can't do
// op true(S) and op false(S?) for example.
// SPEC: Certain binary operators require pairwise declaration. For every
// SPEC: declaration of either operator of a pair, there must be a matching
// SPEC: declaration of the other operator of the pair. Two operator
// SPEC: declarations match when they have the same return type and the same
// SPEC: type for each parameter. The following operators require pairwise
// SPEC: declaration: == and !=, > and <, >= and <=.
CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.TrueOperatorName, WellKnownMemberNames.FalseOperatorName);
CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.EqualityOperatorName, WellKnownMemberNames.InequalityOperatorName);
CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOperatorName, WellKnownMemberNames.GreaterThanOperatorName);
CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOrEqualOperatorName, WellKnownMemberNames.GreaterThanOrEqualOperatorName);
// We also produce a warning if == / != is overridden without also overriding
// Equals and GetHashCode, or if Equals is overridden without GetHashCode.
CheckForEqualityAndGetHashCode(diagnostics);
}
private void CheckForUnmatchedOperator(DiagnosticBag diagnostics, string operatorName1, string operatorName2)
{
var ops1 = this.GetOperators(operatorName1);
var ops2 = this.GetOperators(operatorName2);
CheckForUnmatchedOperator(diagnostics, ops1, ops2, operatorName2);
CheckForUnmatchedOperator(diagnostics, ops2, ops1, operatorName1);
}
private static void CheckForUnmatchedOperator(
DiagnosticBag diagnostics,
ImmutableArray<MethodSymbol> ops1,
ImmutableArray<MethodSymbol> ops2,
string operatorName2)
{
foreach (var op1 in ops1)
{
bool foundMatch = false;
foreach (var op2 in ops2)
{
foundMatch = DoOperatorsPair(op1, op2);
if (foundMatch)
{
break;
}
}
if (!foundMatch)
{
// CS0216: The operator 'C.operator true(C)' requires a matching operator 'false' to also be defined
diagnostics.Add(ErrorCode.ERR_OperatorNeedsMatch, op1.Locations[0], op1,
SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(operatorName2)));
}
}
}
private static bool DoOperatorsPair(MethodSymbol op1, MethodSymbol op2)
{
if (op1.ParameterCount != op2.ParameterCount)
{
return false;
}
for (int p = 0; p < op1.ParameterCount; ++p)
{
if (!op1.ParameterTypesWithAnnotations[p].Equals(op2.ParameterTypesWithAnnotations[p], TypeCompareKind.AllIgnoreOptions))
{
return false;
}
}
if (!op1.ReturnType.Equals(op2.ReturnType, TypeCompareKind.AllIgnoreOptions))
{
return false;
}
return true;
}
private void CheckForEqualityAndGetHashCode(DiagnosticBag diagnostics)
{
if (this.IsInterfaceType())
{
// Interfaces are allowed to define Equals without GetHashCode if they want.
return;
}
bool hasOp = this.GetOperators(WellKnownMemberNames.EqualityOperatorName).Any() ||
this.GetOperators(WellKnownMemberNames.InequalityOperatorName).Any();
bool overridesEquals = this.TypeOverridesObjectMethod("Equals");
if (hasOp || overridesEquals)
{
bool overridesGHC = this.TypeOverridesObjectMethod("GetHashCode");
if (overridesEquals && !overridesGHC)
{
// CS0659: 'C' overrides Object.Equals(object o) but does not override Object.GetHashCode()
diagnostics.Add(ErrorCode.WRN_EqualsWithoutGetHashCode, this.Locations[0], this);
}
if (hasOp && !overridesEquals)
{
// CS0660: 'C' defines operator == or operator != but does not override Object.Equals(object o)
diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutEquals, this.Locations[0], this);
}
if (hasOp && !overridesGHC)
{
// CS0661: 'C' defines operator == or operator != but does not override Object.GetHashCode()
diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutGetHashCode, this.Locations[0], this);
}
}
}
private bool TypeOverridesObjectMethod(string name)
{
foreach (var method in this.GetMembers(name).OfType<MethodSymbol>())
{
if (method.IsOverride && method.GetConstructedLeastOverriddenMethod(this).ContainingType.SpecialType == Microsoft.CodeAnalysis.SpecialType.System_Object)
{
return true;
}
}
return false;
}
private void CheckFiniteFlatteningGraph(DiagnosticBag diagnostics)
{
Debug.Assert(ReferenceEquals(this, this.OriginalDefinition));
if (AllTypeArgumentCount() == 0) return;
var instanceMap = new Dictionary<NamedTypeSymbol, NamedTypeSymbol>(ReferenceEqualityComparer.Instance);
instanceMap.Add(this, this);
foreach (var m in this.GetMembersUnordered())
{
var f = m as FieldSymbol;
if ((object)f == null || !f.IsStatic || f.Type.TypeKind != TypeKind.Struct) continue;
var type = (NamedTypeSymbol)f.Type;
if (InfiniteFlatteningGraph(this, type, instanceMap))
{
// Struct member '{0}' of type '{1}' causes a cycle in the struct layout
diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, f.Locations[0], f, type);
//this.KnownCircularStruct = true;
return;
}
}
}
private static bool InfiniteFlatteningGraph(SourceMemberContainerTypeSymbol top, NamedTypeSymbol t, Dictionary<NamedTypeSymbol, NamedTypeSymbol> instanceMap)
{
if (!t.ContainsTypeParameter()) return false;
NamedTypeSymbol oldInstance;
var tOriginal = t.OriginalDefinition;
if (instanceMap.TryGetValue(tOriginal, out oldInstance))
{
// short circuit when we find a cycle, but only return true when the cycle contains the top struct
return (!TypeSymbol.Equals(oldInstance, t, TypeCompareKind.AllNullableIgnoreOptions)) && ReferenceEquals(tOriginal, top);
}
else
{
instanceMap.Add(tOriginal, t);
try
{
foreach (var m in t.GetMembersUnordered())
{
var f = m as FieldSymbol;
if ((object)f == null || !f.IsStatic || f.Type.TypeKind != TypeKind.Struct) continue;
var type = (NamedTypeSymbol)f.Type;
if (InfiniteFlatteningGraph(top, type, instanceMap)) return true;
}
return false;
}
finally
{
instanceMap.Remove(tOriginal);
}
}
}
private void CheckSequentialOnPartialType(DiagnosticBag diagnostics)
{
if (!IsPartial || this.Layout.Kind != LayoutKind.Sequential)
{
return;
}
SyntaxReference whereFoundField = null;
if (this.SyntaxReferences.Length <= 1)
{
return;
}
foreach (var syntaxRef in this.SyntaxReferences)
{
var syntax = syntaxRef.GetSyntax() as TypeDeclarationSyntax;
if (syntax == null)
{
continue;
}
foreach (var m in syntax.Members)
{
if (HasInstanceData(m))
{
if (whereFoundField != null && whereFoundField != syntaxRef)
{
diagnostics.Add(ErrorCode.WRN_SequentialOnPartialClass, Locations[0], this);
return;
}
whereFoundField = syntaxRef;
}
}
}
}
private static bool HasInstanceData(MemberDeclarationSyntax m)
{
switch (m.Kind())
{
case SyntaxKind.FieldDeclaration:
var fieldDecl = (FieldDeclarationSyntax)m;
return
!ContainsModifier(fieldDecl.Modifiers, SyntaxKind.StaticKeyword) &&
!ContainsModifier(fieldDecl.Modifiers, SyntaxKind.ConstKeyword);
case SyntaxKind.PropertyDeclaration:
// auto-property
var propertyDecl = (PropertyDeclarationSyntax)m;
return
!ContainsModifier(propertyDecl.Modifiers, SyntaxKind.StaticKeyword) &&
!ContainsModifier(propertyDecl.Modifiers, SyntaxKind.AbstractKeyword) &&
!ContainsModifier(propertyDecl.Modifiers, SyntaxKind.ExternKeyword) &&
propertyDecl.AccessorList != null &&
All(propertyDecl.AccessorList.Accessors, a => a.Body == null && a.ExpressionBody == null);
case SyntaxKind.EventFieldDeclaration:
// field-like event declaration
var eventFieldDecl = (EventFieldDeclarationSyntax)m;
return
!ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.StaticKeyword) &&
!ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.AbstractKeyword) &&
!ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.ExternKeyword);
default:
return false;
}
}
private static bool All<T>(SyntaxList<T> list, Func<T, bool> predicate) where T : CSharpSyntaxNode
{
foreach (var t in list) { if (predicate(t)) return true; };
return false;
}
private static bool ContainsModifier(SyntaxTokenList modifiers, SyntaxKind modifier)
{
foreach (var m in modifiers) { if (m.IsKind(modifier)) return true; };
return false;
}
private Dictionary<string, ImmutableArray<Symbol>> MakeAllMembers(DiagnosticBag diagnostics)
{
var membersAndInitializers = GetMembersAndInitializers();
// Most types don't have indexers. If this is one of those types,
// just reuse the dictionary we build for early attribute decoding.
if (membersAndInitializers.IndexerDeclarations.Length == 0)
{
return GetEarlyAttributeDecodingMembersDictionary();
}
// Add indexers (plus their accessors)
var indexerMembers = ArrayBuilder<Symbol>.GetInstance();
Binder binder = null;
SyntaxTree currentTree = null;
foreach (var decl in membersAndInitializers.IndexerDeclarations)
{
var syntax = (IndexerDeclarationSyntax)decl.GetSyntax();
if (binder == null || currentTree != decl.SyntaxTree)
{
currentTree = decl.SyntaxTree;
BinderFactory binderFactory = this.DeclaringCompilation.GetBinderFactory(currentTree);
binder = binderFactory.GetBinder(syntax);
}
var indexer = SourcePropertySymbol.Create(this, binder, syntax, diagnostics);
CheckMemberNameDistinctFromType(indexer, diagnostics);
indexerMembers.Add(indexer);
AddAccessorIfAvailable(indexerMembers, indexer.GetMethod, diagnostics, checkName: true);
AddAccessorIfAvailable(indexerMembers, indexer.SetMethod, diagnostics, checkName: true);
}
var membersByName = MergeIndexersAndNonIndexers(membersAndInitializers.NonTypeNonIndexerMembers, indexerMembers);
indexerMembers.Free();
// Merge types into the member dictionary
AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary());
return membersByName;
}
/// <summary>
/// Merge (already ordered) non-type, non-indexer members with (already ordered) indexer members.
/// </summary>
private static Dictionary<string, ImmutableArray<Symbol>> MergeIndexersAndNonIndexers(ImmutableArray<Symbol> nonIndexerMembers, ArrayBuilder<Symbol> indexerMembers)
{
int nonIndexerCount = nonIndexerMembers.Length;
int indexerCount = indexerMembers.Count;
var merged = ArrayBuilder<Symbol>.GetInstance(nonIndexerCount + indexerCount);
int nonIndexerPos = 0;
int indexerPos = 0;
while (nonIndexerPos < nonIndexerCount && indexerPos < indexerCount)
{
var nonIndexer = nonIndexerMembers[nonIndexerPos];
var indexer = indexerMembers[indexerPos];
if (LexicalOrderSymbolComparer.Instance.Compare(nonIndexer, indexer) < 0)
{
merged.Add(nonIndexer);
nonIndexerPos++;
}
else
{
merged.Add(indexer);
indexerPos++;
}
}
for (; nonIndexerPos < nonIndexerCount; nonIndexerPos++)
{
merged.Add(nonIndexerMembers[nonIndexerPos]);
}
for (; indexerPos < indexerCount; indexerPos++)
{
merged.Add(indexerMembers[indexerPos]);
}
var membersByName = merged.ToDictionary(s => s.Name, StringOrdinalComparer.Instance);
merged.Free();
return membersByName;
}
private static void AddNestedTypesToDictionary(Dictionary<string, ImmutableArray<Symbol>> membersByName, Dictionary<string, ImmutableArray<NamedTypeSymbol>> typesByName)
{
foreach (var pair in typesByName)
{
string name = pair.Key;
ImmutableArray<NamedTypeSymbol> types = pair.Value;
ImmutableArray<Symbol> typesAsSymbols = StaticCast<Symbol>.From(types);
ImmutableArray<Symbol> membersForName;
if (membersByName.TryGetValue(name, out membersForName))
{
membersByName[name] = membersForName.Concat(typesAsSymbols);
}
else
{
membersByName.Add(name, typesAsSymbols);
}
}
}
private class MembersAndInitializersBuilder
{
public readonly ArrayBuilder<Symbol> NonTypeNonIndexerMembers = ArrayBuilder<Symbol>.GetInstance();
public readonly ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance();
public readonly ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance();
public readonly ArrayBuilder<SyntaxReference> IndexerDeclarations = ArrayBuilder<SyntaxReference>.GetInstance();
public int StaticSyntaxLength;
public int InstanceSyntaxLength;
public MembersAndInitializers ToReadOnlyAndFree()
{
return new MembersAndInitializers(
NonTypeNonIndexerMembers.ToImmutableAndFree(),
StaticInitializers.ToImmutableAndFree(),
InstanceInitializers.ToImmutableAndFree(),
IndexerDeclarations.ToImmutableAndFree(),
StaticSyntaxLength,
InstanceSyntaxLength);
}
public void Free()
{
NonTypeNonIndexerMembers.Free();
StaticInitializers.Free();
InstanceInitializers.Free();
IndexerDeclarations.Free();
}
}
private MembersAndInitializers BuildMembersAndInitializers(DiagnosticBag diagnostics)
{
var builder = new MembersAndInitializersBuilder();
AddDeclaredNontypeMembers(builder, diagnostics);
switch (TypeKind)
{
case TypeKind.Struct:
CheckForStructBadInitializers(builder, diagnostics);
CheckForStructDefaultConstructors(builder.NonTypeNonIndexerMembers, isEnum: false, diagnostics: diagnostics);
AddSynthesizedConstructorsIfNecessary(builder.NonTypeNonIndexerMembers, builder.StaticInitializers, diagnostics);
break;
case TypeKind.Enum:
CheckForStructDefaultConstructors(builder.NonTypeNonIndexerMembers, isEnum: true, diagnostics: diagnostics);
AddSynthesizedConstructorsIfNecessary(builder.NonTypeNonIndexerMembers, builder.StaticInitializers, diagnostics);
break;
case TypeKind.Class:
case TypeKind.Interface:
case TypeKind.Submission:
// No additional checking required.
AddSynthesizedConstructorsIfNecessary(builder.NonTypeNonIndexerMembers, builder.StaticInitializers, diagnostics);
break;
default:
break;
}
// We already built the members and initializers on another thread, we might have detected that condition
// during member building on this thread and bailed, which results in incomplete data in the builder.
// In such case we have to avoid creating the instance of MemberAndInitializers since it checks the consistency
// of the data in the builder and would fail in an assertion if we tried to construct it from incomplete builder.
if (_lazyMembersAndInitializers != null)
{
builder.Free();
return null;
}
return builder.ToReadOnlyAndFree();
}
private void AddDeclaredNontypeMembers(MembersAndInitializersBuilder builder, DiagnosticBag diagnostics)
{
foreach (var decl in this.declaration.Declarations)
{
if (!decl.HasAnyNontypeMembers)
{
continue;
}
if (_lazyMembersAndInitializers != null)
{
// membersAndInitializers is already computed. no point to continue.
return;
}
var syntax = decl.SyntaxReference.GetSyntax();
switch (syntax.Kind())
{
case SyntaxKind.EnumDeclaration:
AddEnumMembers(builder, (EnumDeclarationSyntax)syntax, diagnostics);
break;
case SyntaxKind.DelegateDeclaration:
SourceDelegateMethodSymbol.AddDelegateMembers(this, builder.NonTypeNonIndexerMembers, (DelegateDeclarationSyntax)syntax, diagnostics);
break;
case SyntaxKind.NamespaceDeclaration:
// The members of a global anonymous type is in a syntax tree of a namespace declaration or a compilation unit.
AddNonTypeMembers(builder, ((NamespaceDeclarationSyntax)syntax).Members, diagnostics);
break;
case SyntaxKind.CompilationUnit:
AddNonTypeMembers(builder, ((CompilationUnitSyntax)syntax).Members, diagnostics);
break;
case SyntaxKind.ClassDeclaration:
var classDecl = (ClassDeclarationSyntax)syntax;
AddNonTypeMembers(builder, classDecl.Members, diagnostics);
break;
case SyntaxKind.InterfaceDeclaration:
AddNonTypeMembers(builder, ((InterfaceDeclarationSyntax)syntax).Members, diagnostics);
break;
case SyntaxKind.StructDeclaration:
var structDecl = (StructDeclarationSyntax)syntax;
AddNonTypeMembers(builder, structDecl.Members, diagnostics);
break;
default:
throw ExceptionUtilities.UnexpectedValue(syntax.Kind());
}
}
}
internal Binder GetBinder(CSharpSyntaxNode syntaxNode)
{
return this.DeclaringCompilation.GetBinder(syntaxNode);
}
private static void MergePartialMembers(
ArrayBuilder<string> memberNames,
Dictionary<string, ImmutableArray<Symbol>> membersByName,
DiagnosticBag diagnostics)
{
//key and value will be the same object
var methodsBySignature = new Dictionary<MethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.PartialMethodsComparer);
foreach (var name in memberNames)
{
methodsBySignature.Clear();
foreach (var symbol in membersByName[name])
{
var method = symbol as SourceMemberMethodSymbol;
if ((object)method == null || !method.IsPartial)
{
continue; // only partial methods need to be merged
}
SourceMemberMethodSymbol prev;
if (methodsBySignature.TryGetValue(method, out prev))
{
var prevPart = (SourceOrdinaryMethodSymbol)prev;
var methodPart = (SourceOrdinaryMethodSymbol)method;
bool hasImplementation = (object)prevPart.OtherPartOfPartial != null || prevPart.IsPartialImplementation;
bool hasDefinition = (object)prevPart.OtherPartOfPartial != null || prevPart.IsPartialDefinition;
if (hasImplementation && methodPart.IsPartialImplementation)
{
// A partial method may not have multiple implementing declarations
diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneActual, methodPart.Locations[0]);
}
else if (hasDefinition && methodPart.IsPartialDefinition)
{
// A partial method may not have multiple defining declarations
diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneLatent, methodPart.Locations[0]);
}
else
{
membersByName[name] = FixPartialMember(membersByName[name], prevPart, methodPart);
}
}
else
{
methodsBySignature.Add(method, method);
}
}
foreach (SourceOrdinaryMethodSymbol method in methodsBySignature.Values)
{
// partial implementations not paired with a definition
if (method.IsPartialImplementation && (object)method.OtherPartOfPartial == null)
{
diagnostics.Add(ErrorCode.ERR_PartialMethodMustHaveLatent, method.Locations[0], method);
}
else if ((object)method.OtherPartOfPartial != null && MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(method, method.OtherPartOfPartial))
{
diagnostics.Add(ErrorCode.ERR_PartialMethodInconsistentTupleNames, method.Locations[0], method, method.OtherPartOfPartial);
}
}
}
}
/// <summary>
/// Fix up a partial method by combining its defining and implementing declarations, updating the array of symbols (by name),
/// and returning the combined symbol.
/// </summary>
/// <param name="symbols">The symbols array containing both the latent and implementing declaration</param>
/// <param name="part1">One of the two declarations</param>
/// <param name="part2">The other declaration</param>
/// <returns>An updated symbols array containing only one method symbol representing the two parts</returns>
private static ImmutableArray<Symbol> FixPartialMember(ImmutableArray<Symbol> symbols, SourceOrdinaryMethodSymbol part1, SourceOrdinaryMethodSymbol part2)
{
SourceOrdinaryMethodSymbol definition;
SourceOrdinaryMethodSymbol implementation;
if (part1.IsPartialDefinition)
{
definition = part1;
implementation = part2;
}
else
{
definition = part2;
implementation = part1;
}
SourceOrdinaryMethodSymbol.InitializePartialMethodParts(definition, implementation);
// a partial method is represented in the member list by its definition part:
return Remove(symbols, implementation);
}
private static ImmutableArray<Symbol> Remove(ImmutableArray<Symbol> symbols, Symbol symbol)
{
var builder = ArrayBuilder<Symbol>.GetInstance();
foreach (var s in symbols)
{
if (!ReferenceEquals(s, symbol))
{
builder.Add(s);
}
}
return builder.ToImmutableAndFree();
}
/// <summary>
/// Report an error if a member (other than a method) exists with the same name
/// as the property accessor, or if a method exists with the same name and signature.
/// </summary>
private void CheckForMemberConflictWithPropertyAccessor(
PropertySymbol propertySymbol,
bool getNotSet,
DiagnosticBag diagnostics)
{
Debug.Assert(!propertySymbol.IsExplicitInterfaceImplementation); // checked by caller
MethodSymbol accessor = getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod;
string accessorName;
if ((object)accessor != null)
{
accessorName = accessor.Name;
}
else
{
string propertyName = propertySymbol.IsIndexer ? propertySymbol.MetadataName : propertySymbol.Name;
accessorName = SourcePropertyAccessorSymbol.GetAccessorName(propertyName,
getNotSet,
propertySymbol.IsCompilationOutputWinMdObj());
}
foreach (var symbol in GetMembers(accessorName))
{
if (symbol.Kind != SymbolKind.Method)
{
// The type '{0}' already contains a definition for '{1}'
if (Locations.Length == 1 || IsPartial)
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), this, accessorName);
return;
}
else
{
var methodSymbol = (MethodSymbol)symbol;
if ((methodSymbol.MethodKind == MethodKind.Ordinary) &&
ParametersMatchPropertyAccessor(propertySymbol, getNotSet, methodSymbol.Parameters))
{
// Type '{1}' already reserves a member called '{0}' with the same parameter types
diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), accessorName, this);
return;
}
}
}
}
/// <summary>
/// Report an error if a member (other than a method) exists with the same name
/// as the event accessor, or if a method exists with the same name and signature.
/// </summary>
private void CheckForMemberConflictWithEventAccessor(
EventSymbol eventSymbol,
bool isAdder,
DiagnosticBag diagnostics)
{
Debug.Assert(!eventSymbol.IsExplicitInterfaceImplementation); // checked by caller
string accessorName = SourceEventSymbol.GetAccessorName(eventSymbol.Name, isAdder);
foreach (var symbol in GetMembers(accessorName))
{
if (symbol.Kind != SymbolKind.Method)
{
// The type '{0}' already contains a definition for '{1}'
if (Locations.Length == 1 || IsPartial)
diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrEventLocation(eventSymbol, isAdder), this, accessorName);
return;
}
else
{
var methodSymbol = (MethodSymbol)symbol;
if ((methodSymbol.MethodKind == MethodKind.Ordinary) &&
ParametersMatchEventAccessor(eventSymbol, methodSymbol.Parameters))
{
// Type '{1}' already reserves a member called '{0}' with the same parameter types
diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrEventLocation(eventSymbol, isAdder), accessorName, this);
return;
}
}
}
}
/// <summary>
/// Return the location of the accessor, or if no accessor, the location of the property.
/// </summary>
private static Location GetAccessorOrPropertyLocation(PropertySymbol propertySymbol, bool getNotSet)
{
var locationFrom = (Symbol)(getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod) ?? propertySymbol;
return locationFrom.Locations[0];
}
/// <summary>
/// Return the location of the accessor, or if no accessor, the location of the event.
/// </summary>
private static Location GetAccessorOrEventLocation(EventSymbol propertySymbol, bool isAdder)
{
var locationFrom = (Symbol)(isAdder ? propertySymbol.AddMethod : propertySymbol.RemoveMethod) ?? propertySymbol;
return locationFrom.Locations[0];
}
/// <summary>
/// Return true if the method parameters match the parameters of the
/// property accessor, including the value parameter for the setter.
/// </summary>
private static bool ParametersMatchPropertyAccessor(PropertySymbol propertySymbol, bool getNotSet, ImmutableArray<ParameterSymbol> methodParams)
{
var propertyParams = propertySymbol.Parameters;
var numParams = propertyParams.Length + (getNotSet ? 0 : 1);
if (numParams != methodParams.Length)
{
return false;
}
for (int i = 0; i < numParams; i++)
{
var methodParam = methodParams[i];
if (methodParam.RefKind != RefKind.None)
{
return false;
}
var propertyParamType = (((i == numParams - 1) && !getNotSet) ? propertySymbol.TypeWithAnnotations : propertyParams[i].TypeWithAnnotations).Type;
if (!propertyParamType.Equals(methodParam.Type, TypeCompareKind.AllIgnoreOptions))
{
return false;
}
}
return true;
}
/// <summary>
/// Return true if the method parameters match the parameters of the
/// event accessor, including the value parameter.
/// </summary>
private static bool ParametersMatchEventAccessor(EventSymbol eventSymbol, ImmutableArray<ParameterSymbol> methodParams)
{
return
methodParams.Length == 1 &&
methodParams[0].RefKind == RefKind.None &&
eventSymbol.Type.Equals(methodParams[0].Type, TypeCompareKind.AllIgnoreOptions);
}
private void AddEnumMembers(MembersAndInitializersBuilder result, EnumDeclarationSyntax syntax, DiagnosticBag diagnostics)
{
// The previous enum constant used to calculate subsequent
// implicit enum constants. (This is the most recent explicit
// enum constant or the first implicit constant if no explicit values.)
SourceEnumConstantSymbol otherSymbol = null;
// Offset from "otherSymbol".
int otherSymbolOffset = 0;
foreach (var member in syntax.Members)
{
SourceEnumConstantSymbol symbol;
var valueOpt = member.EqualsValue;
if (valueOpt != null)
{
symbol = SourceEnumConstantSymbol.CreateExplicitValuedConstant(this, member, diagnostics);
}
else
{
symbol = SourceEnumConstantSymbol.CreateImplicitValuedConstant(this, member, otherSymbol, otherSymbolOffset, diagnostics);
}
result.NonTypeNonIndexerMembers.Add(symbol);
if (valueOpt != null || (object)otherSymbol == null)
{
otherSymbol = symbol;
otherSymbolOffset = 1;
}
else
{
otherSymbolOffset++;
}
}
}
private static void AddInitializer(ref ArrayBuilder<FieldOrPropertyInitializer> initializers, ref int aggregateSyntaxLength, FieldSymbol fieldOpt, CSharpSyntaxNode node)
{
if (initializers == null)
{
initializers = new ArrayBuilder<FieldOrPropertyInitializer>();
}
else
{
// initializers should be added in syntax order:
Debug.Assert(node.SyntaxTree == initializers.Last().Syntax.SyntaxTree);
Debug.Assert(node.SpanStart > initializers.Last().Syntax.GetSyntax().SpanStart);
}
int currentLength = aggregateSyntaxLength;
// A constant field of type decimal needs a field initializer, so
// check if it is a metadata constant, not just a constant to exclude
// decimals. Other constants do not need field initializers.
if (fieldOpt == null || !fieldOpt.IsMetadataConstant)
{
// ignore leading and trailing trivia of the node:
aggregateSyntaxLength += node.Span.Length;
}
initializers.Add(new FieldOrPropertyInitializer(fieldOpt, node, currentLength));
}
private static void AddInitializers(ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>> allInitializers, ArrayBuilder<FieldOrPropertyInitializer> siblingsOpt)
{
if (siblingsOpt != null)
{
allInitializers.Add(siblingsOpt.ToImmutableAndFree());
}
}
private static void CheckInterfaceMembers(ImmutableArray<Symbol> nonTypeMembers, DiagnosticBag diagnostics)
{
foreach (var member in nonTypeMembers)
{
CheckInterfaceMember(member, diagnostics);
}
}
private static void CheckInterfaceMember(Symbol member, DiagnosticBag diagnostics)
{
switch (member.Kind)
{
case SymbolKind.Field:
break;
case SymbolKind.Method:
var meth = (MethodSymbol)member;
switch (meth.MethodKind)
{
case MethodKind.Constructor:
diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConstructors, member.Locations[0]);
break;
case MethodKind.Conversion:
diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, member.Locations[0]);
break;
case MethodKind.UserDefinedOperator:
if (meth.Name == WellKnownMemberNames.EqualityOperatorName || meth.Name == WellKnownMemberNames.InequalityOperatorName)
{
diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, member.Locations[0]);
}
break;
case MethodKind.Destructor:
diagnostics.Add(ErrorCode.ERR_OnlyClassesCanContainDestructors, member.Locations[0]);
break;
case MethodKind.ExplicitInterfaceImplementation:
//CS0541 is handled in SourcePropertySymbol
case MethodKind.Ordinary:
case MethodKind.LocalFunction:
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
case MethodKind.EventAdd:
case MethodKind.EventRemove:
case MethodKind.StaticConstructor:
break;
default:
throw ExceptionUtilities.UnexpectedValue(meth.MethodKind);
}
break;
case SymbolKind.Property:
break;
case SymbolKind.Event:
break;
default:
throw ExceptionUtilities.UnexpectedValue(member.Kind);
}
}
private static void CheckForStructDefaultConstructors(
ArrayBuilder<Symbol> members,
bool isEnum,
DiagnosticBag diagnostics)
{
foreach (var s in members)
{
var m = s as MethodSymbol;
if ((object)m != null)
{
if (m.MethodKind == MethodKind.Constructor && m.ParameterCount == 0)
{
if (isEnum)
{
diagnostics.Add(ErrorCode.ERR_EnumsCantContainDefaultConstructor, m.Locations[0]);
}
else
{
diagnostics.Add(ErrorCode.ERR_StructsCantContainDefaultConstructor, m.Locations[0]);
}
}
}
}
}
private void CheckForStructBadInitializers(MembersAndInitializersBuilder builder, DiagnosticBag diagnostics)
{
Debug.Assert(TypeKind == TypeKind.Struct);
foreach (var initializers in builder.InstanceInitializers)
{
foreach (FieldOrPropertyInitializer initializer in initializers)
{
// '{0}': cannot have instance field initializers in structs
diagnostics.Add(ErrorCode.ERR_FieldInitializerInStruct, (initializer.FieldOpt.AssociatedSymbol ?? initializer.FieldOpt).Locations[0], this);
}
}
}
private void AddSynthesizedConstructorsIfNecessary(ArrayBuilder<Symbol> members, ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>> staticInitializers, DiagnosticBag diagnostics)
{
//we're not calling the helpers on NamedTypeSymbol base, because those call
//GetMembers and we're inside a GetMembers call ourselves (i.e. stack overflow)
var hasInstanceConstructor = false;
var hasParameterlessInstanceConstructor = false;
var hasStaticConstructor = false;
// CONSIDER: if this traversal becomes a bottleneck, the flags could be made outputs of the
// dictionary construction process. For now, this is more encapsulated.
foreach (var member in members)
{
if (member.Kind == SymbolKind.Method)
{
var method = (MethodSymbol)member;
switch (method.MethodKind)
{
case MethodKind.Constructor:
hasInstanceConstructor = true;
hasParameterlessInstanceConstructor = hasParameterlessInstanceConstructor || method.ParameterCount == 0;
break;
case MethodKind.StaticConstructor:
hasStaticConstructor = true;
break;
}
}
//kick out early if we've seen everything we're looking for
if (hasInstanceConstructor && hasStaticConstructor)
{
break;
}
}
// NOTE: Per section 11.3.8 of the spec, "every struct implicitly has a parameterless instance constructor".
// We won't insert a parameterless constructor for a struct if there already is one.
// We don't expect anything to be emitted, but it should be in the symbol table.
if ((!hasParameterlessInstanceConstructor && this.IsStructType()) || (!hasInstanceConstructor && !this.IsStatic && !this.IsInterface))
{
members.Add((this.TypeKind == TypeKind.Submission) ?
new SynthesizedSubmissionConstructor(this, diagnostics) :
new SynthesizedInstanceConstructor(this));
}
// constants don't count, since they do not exist as fields at runtime
// NOTE: even for decimal constants (which require field initializers),
// we do not create .cctor here since a static constructor implicitly created for a decimal
// should not appear in the list returned by public API like GetMembers().
if (!hasStaticConstructor && HasNonConstantInitializer(staticInitializers))
{
// Note: we don't have to put anything in the method - the binder will
// do that when processing field initializers.
members.Add(new SynthesizedStaticConstructor(this));
}
if (this.IsScriptClass)
{
var scriptInitializer = new SynthesizedInteractiveInitializerMethod(this, diagnostics);
members.Add(scriptInitializer);
var scriptEntryPoint = SynthesizedEntryPointSymbol.Create(scriptInitializer, diagnostics);
members.Add(scriptEntryPoint);
}
}
private static bool HasNonConstantInitializer(ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>> initializers)
{
return initializers.Any(siblings => siblings.Any(initializer => !initializer.FieldOpt.IsConst));
}
private void AddNonTypeMembers(
MembersAndInitializersBuilder builder,
SyntaxList<MemberDeclarationSyntax> members,
DiagnosticBag diagnostics)
{
if (members.Count == 0)
{
return;
}
var firstMember = members[0];
var bodyBinder = this.GetBinder(firstMember);
ArrayBuilder<FieldOrPropertyInitializer> staticInitializers = null;
ArrayBuilder<FieldOrPropertyInitializer> instanceInitializers = null;
foreach (var m in members)
{
if (_lazyMembersAndInitializers != null)
{
// membersAndInitializers is already computed. no point to continue.
return;
}
bool reportMisplacedGlobalCode = !m.HasErrors;
switch (m.Kind())
{
case SyntaxKind.FieldDeclaration:
{
var fieldSyntax = (FieldDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(fieldSyntax.Declaration.Variables.First().Identifier));
}
bool modifierErrors;
var modifiers = SourceMemberFieldSymbol.MakeModifiers(this, fieldSyntax.Declaration.Variables[0].Identifier, fieldSyntax.Modifiers, diagnostics, out modifierErrors);
foreach (var variable in fieldSyntax.Declaration.Variables)
{
var fieldSymbol = (modifiers & DeclarationModifiers.Fixed) == 0
? new SourceMemberFieldSymbolFromDeclarator(this, variable, modifiers, modifierErrors, diagnostics)
: new SourceFixedFieldSymbol(this, variable, modifiers, modifierErrors, diagnostics);
builder.NonTypeNonIndexerMembers.Add(fieldSymbol);
if (IsScriptClass)
{
// also gather expression-declared variables from the bracketed argument lists and the initializers
ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeNonIndexerMembers, variable, this,
DeclarationModifiers.Private | (modifiers & DeclarationModifiers.Static),
fieldSymbol);
}
if (variable.Initializer != null)
{
if (fieldSymbol.IsStatic)
{
AddInitializer(ref staticInitializers, ref builder.StaticSyntaxLength, fieldSymbol, variable.Initializer);
}
else
{
AddInitializer(ref instanceInitializers, ref builder.InstanceSyntaxLength, fieldSymbol, variable.Initializer);
}
}
}
}
break;
case SyntaxKind.MethodDeclaration:
{
var methodSyntax = (MethodDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(methodSyntax.Identifier));
}
var method = SourceOrdinaryMethodSymbol.CreateMethodSymbol(this, bodyBinder, methodSyntax, diagnostics);
builder.NonTypeNonIndexerMembers.Add(method);
}
break;
case SyntaxKind.ConstructorDeclaration:
{
var constructorSyntax = (ConstructorDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(constructorSyntax.Identifier));
}
var constructor = SourceConstructorSymbol.CreateConstructorSymbol(this, constructorSyntax, diagnostics);
builder.NonTypeNonIndexerMembers.Add(constructor);
}
break;
case SyntaxKind.DestructorDeclaration:
{
var destructorSyntax = (DestructorDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(destructorSyntax.Identifier));
}
// CONSIDER: if this doesn't (directly or indirectly) override object.Finalize, the
// runtime won't consider it a finalizer and it will not be marked as a destructor
// when it is loaded from metadata. Perhaps we should just treat it as an Ordinary
// method in such cases?
var destructor = new SourceDestructorSymbol(this, destructorSyntax, diagnostics);
builder.NonTypeNonIndexerMembers.Add(destructor);
}
break;
case SyntaxKind.PropertyDeclaration:
{
var propertySyntax = (PropertyDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(propertySyntax.Identifier));
}
var property = SourcePropertySymbol.Create(this, bodyBinder, propertySyntax, diagnostics);
builder.NonTypeNonIndexerMembers.Add(property);
AddAccessorIfAvailable(builder.NonTypeNonIndexerMembers, property.GetMethod, diagnostics);
AddAccessorIfAvailable(builder.NonTypeNonIndexerMembers, property.SetMethod, diagnostics);
FieldSymbol backingField = property.BackingField;
// TODO: can we leave this out of the member list?
// From the 10/12/11 design notes:
// In addition, we will change autoproperties to behavior in
// a similar manner and make the autoproperty fields private.
if ((object)backingField != null)
{
builder.NonTypeNonIndexerMembers.Add(backingField);
var initializer = propertySyntax.Initializer;
if (initializer != null)
{
if (IsScriptClass)
{
// also gather expression-declared variables from the initializer
ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeNonIndexerMembers,
initializer,
this,
DeclarationModifiers.Private | (property.IsStatic ? DeclarationModifiers.Static : 0),
backingField);
}
if (property.IsStatic)
{
AddInitializer(ref staticInitializers, ref builder.StaticSyntaxLength, backingField, initializer);
}
else
{
AddInitializer(ref instanceInitializers, ref builder.InstanceSyntaxLength, backingField, initializer);
}
}
}
}
break;
case SyntaxKind.EventFieldDeclaration:
{
var eventFieldSyntax = (EventFieldDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(
ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(eventFieldSyntax.Declaration.Variables.First().Identifier));
}
foreach (VariableDeclaratorSyntax declarator in eventFieldSyntax.Declaration.Variables)
{
SourceFieldLikeEventSymbol @event = new SourceFieldLikeEventSymbol(this, bodyBinder, eventFieldSyntax.Modifiers, declarator, diagnostics);
builder.NonTypeNonIndexerMembers.Add(@event);
FieldSymbol associatedField = @event.AssociatedField;
if (IsScriptClass)
{
// also gather expression-declared variables from the bracketed argument lists and the initializers
ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeNonIndexerMembers, declarator, this,
DeclarationModifiers.Private | (@event.IsStatic ? DeclarationModifiers.Static : 0),
associatedField);
}
if ((object)associatedField != null)
{
// NOTE: specifically don't add the associated field to the members list
// (regard it as an implementation detail).
if (declarator.Initializer != null)
{
if (associatedField.IsStatic)
{
AddInitializer(ref staticInitializers, ref builder.StaticSyntaxLength, associatedField, declarator.Initializer);
}
else
{
AddInitializer(ref instanceInitializers, ref builder.InstanceSyntaxLength, associatedField, declarator.Initializer);
}
}
}
Debug.Assert((object)@event.AddMethod != null);
Debug.Assert((object)@event.RemoveMethod != null);
AddAccessorIfAvailable(builder.NonTypeNonIndexerMembers, @event.AddMethod, diagnostics);
AddAccessorIfAvailable(builder.NonTypeNonIndexerMembers, @event.RemoveMethod, diagnostics);
}
}
break;
case SyntaxKind.EventDeclaration:
{
var eventSyntax = (EventDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(eventSyntax.Identifier));
}
var @event = new SourceCustomEventSymbol(this, bodyBinder, eventSyntax, diagnostics);
builder.NonTypeNonIndexerMembers.Add(@event);
AddAccessorIfAvailable(builder.NonTypeNonIndexerMembers, @event.AddMethod, diagnostics);
AddAccessorIfAvailable(builder.NonTypeNonIndexerMembers, @event.RemoveMethod, diagnostics);
Debug.Assert((object)@event.AssociatedField == null);
}
break;
case SyntaxKind.IndexerDeclaration:
{
var indexerSyntax = (IndexerDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(indexerSyntax.ThisKeyword));
}
// We can't create the indexer symbol yet, because we don't know
// what name it will have after attribute binding (because of
// IndexerNameAttribute). Instead, we'll keep a (weak) reference
// to the syntax and bind it again after early attribute decoding.
builder.IndexerDeclarations.Add(indexerSyntax.GetReference());
}
break;
case SyntaxKind.ConversionOperatorDeclaration:
{
var conversionOperatorSyntax = (ConversionOperatorDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(conversionOperatorSyntax.OperatorKeyword));
}
var method = SourceUserDefinedConversionSymbol.CreateUserDefinedConversionSymbol
(this, conversionOperatorSyntax, diagnostics);
builder.NonTypeNonIndexerMembers.Add(method);
}
break;
case SyntaxKind.OperatorDeclaration:
{
var operatorSyntax = (OperatorDeclarationSyntax)m;
if (IsImplicitClass && reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected,
new SourceLocation(operatorSyntax.OperatorKeyword));
}
var method = SourceUserDefinedOperatorSymbol.CreateUserDefinedOperatorSymbol
(this, operatorSyntax, diagnostics);
builder.NonTypeNonIndexerMembers.Add(method);
}
break;
case SyntaxKind.GlobalStatement:
{
var globalStatement = ((GlobalStatementSyntax)m).Statement;
if (IsScriptClass)
{
var innerStatement = globalStatement;
// drill into any LabeledStatements
while (innerStatement.Kind() == SyntaxKind.LabeledStatement)
{
innerStatement = ((LabeledStatementSyntax)innerStatement).Statement;
}
switch (innerStatement.Kind())
{
case SyntaxKind.LocalDeclarationStatement:
// We shouldn't reach this place, but field declarations preceded with a label end up here.
// This is tracked by https://github.com/dotnet/roslyn/issues/13712. Let's do our best for now.
var decl = (LocalDeclarationStatementSyntax)innerStatement;
foreach (var vdecl in decl.Declaration.Variables)
{
// also gather expression-declared variables from the bracketed argument lists and the initializers
ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeNonIndexerMembers, vdecl, this, DeclarationModifiers.Private,
containingFieldOpt: null);
}
break;
case SyntaxKind.ExpressionStatement:
case SyntaxKind.IfStatement:
case SyntaxKind.YieldReturnStatement:
case SyntaxKind.ReturnStatement:
case SyntaxKind.ThrowStatement:
case SyntaxKind.SwitchStatement:
case SyntaxKind.LockStatement:
ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeNonIndexerMembers,
innerStatement,
this,
DeclarationModifiers.Private,
containingFieldOpt: null);
break;
default:
// no other statement introduces variables into the enclosing scope
break;
}
AddInitializer(ref instanceInitializers, ref builder.InstanceSyntaxLength, null, globalStatement);
}
else if (reportMisplacedGlobalCode)
{
diagnostics.Add(ErrorCode.ERR_GlobalStatement, new SourceLocation(globalStatement));
}
}
break;
default:
Debug.Assert(
SyntaxFacts.IsTypeDeclaration(m.Kind()) ||
m.Kind() == SyntaxKind.NamespaceDeclaration ||
m.Kind() == SyntaxKind.IncompleteMember);
break;
}
}
AddInitializers(builder.InstanceInitializers, instanceInitializers);
AddInitializers(builder.StaticInitializers, staticInitializers);
}
private void AddAccessorIfAvailable(ArrayBuilder<Symbol> symbols, MethodSymbol accessorOpt, DiagnosticBag diagnostics, bool checkName = false)
{
if ((object)accessorOpt != null)
{
symbols.Add(accessorOpt);
if (checkName)
{
CheckMemberNameDistinctFromType(accessorOpt, diagnostics);
}
}
}
#endregion
#region Extension Methods
internal bool ContainsExtensionMethods
{
get
{
if (!_lazyContainsExtensionMethods.HasValue())
{
bool containsExtensionMethods = ((this.IsStatic && !this.IsGenericType) || this.IsScriptClass) && this.declaration.ContainsExtensionMethods;
_lazyContainsExtensionMethods = containsExtensionMethods.ToThreeState();
}
return _lazyContainsExtensionMethods.Value();
}
}
internal bool AnyMemberHasAttributes
{
get
{
if (!_lazyAnyMemberHasAttributes.HasValue())
{
bool anyMemberHasAttributes = this.declaration.AnyMemberHasAttributes;
_lazyAnyMemberHasAttributes = anyMemberHasAttributes.ToThreeState();
}
return _lazyAnyMemberHasAttributes.Value();
}
}
public override bool MightContainExtensionMethods
{
get
{
return this.ContainsExtensionMethods;
}
}
#endregion
public sealed override NamedTypeSymbol ConstructedFrom
{
get { return this; }
}
}
}
| 44.210621 | 193 | 0.536938 | [
"Apache-2.0"
] | avodovnik/roslyn | src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs | 148,196 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Microsoft.TemplateEngine.Abstractions;
using Microsoft.TemplateEngine.Abstractions.Mount;
using Microsoft.TemplateEngine.Core;
using Microsoft.TemplateEngine.Core.Contracts;
using Microsoft.TemplateEngine.Core.Operations;
using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions;
using Microsoft.TemplateEngine.Utils;
using Newtonsoft.Json.Linq;
namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Config
{
internal class ReplacementConfig : IOperationConfig
{
public string Key => Replacement.OperationName;
public Guid Id => new Guid("62DB7F1F-A10E-46F0-953F-A28A03A81CD1");
public IEnumerable<IOperationProvider> ConfigureFromJObject(JObject rawConfiguration, IDirectory templateRoot)
{
string original = rawConfiguration.ToString("original");
string replacement = rawConfiguration.ToString("replacement");
string id = rawConfiguration.ToString("id");
bool onByDefault = rawConfiguration.ToBool("onByDefault");
JArray onlyIf = rawConfiguration.Get<JArray>("onlyIf");
TokenConfig coreConfig = original.TokenConfigBuilder();
if (onlyIf != null)
{
foreach (JToken entry in onlyIf.Children())
{
if (!(entry is JObject x))
{
continue;
}
string before = entry.ToString("before");
string after = entry.ToString("after");
TokenConfig entryConfig = coreConfig;
if (!string.IsNullOrEmpty(before))
{
entryConfig = entryConfig.OnlyIfBefore(before);
}
if (!string.IsNullOrEmpty(after))
{
entryConfig = entryConfig.OnlyIfAfter(after);
}
yield return new Replacement(entryConfig, replacement, id, onByDefault);
}
}
else
{
yield return new Replacement(coreConfig, replacement, id, onByDefault);
}
}
internal static IOperationProvider Setup(IEngineEnvironmentSettings environmentSettings, IReplacementTokens tokens, IParameterSet parameters)
{
if (parameters.TryGetRuntimeValue(environmentSettings, tokens.VariableName, out object newValueObject))
{
string newValue = newValueObject.ToString();
return new Replacement(tokens.OriginalValue, newValue, null, true);
}
else
{
environmentSettings.Host.Logger.LogDebug($"Couldn't find a parameter called {tokens.VariableName}");
return null;
}
}
}
}
| 38.271605 | 149 | 0.61129 | [
"MIT"
] | 2mol/templating | src/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Config/ReplacementConfig.cs | 3,100 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Maui.Controls.CustomAttributes;
using Microsoft.Maui.Controls.Internals;
#if UITEST
using Xamarin.UITest;
using NUnit.Framework;
using Microsoft.Maui.Controls.UITests;
#endif
namespace Microsoft.Maui.Controls.ControlGallery.Issues
{
[Preserve(AllMembers = true)]
[Issue(IssueTracker.Github, 8743, "[Bug][UWP] SearchBar does not respect FontSize on 4.3.0",
PlatformAffected.UWP)]
#if UITEST
[NUnit.Framework.Category(UITestCategories.SearchBar)]
#endif
public class Issue8743 : TestContentPage
{
protected override void Init()
{
Title = "Issue 8743";
StackLayout layout = new StackLayout();
Label instructions = new Label
{
Text = "Check that the font size in the search bars below matches the size specified in the placeholders."
};
SearchBar normalSearchBar = new SearchBar
{
Placeholder = "FontSize = default"
};
SearchBar largeSearchBar = new SearchBar
{
FontSize = Device.GetNamedSize(NamedSize.Large, typeof(SearchBar)),
Placeholder = "FontSize = Large"
};
SearchBar size100SearchBar = new SearchBar
{
FontSize = 100f,
Placeholder = "FontSize = 100.0"
};
layout.Children.Add(instructions);
layout.Children.Add(normalSearchBar);
layout.Children.Add(largeSearchBar);
layout.Children.Add(size100SearchBar);
Content = layout;
}
}
}
| 23.936508 | 110 | 0.734748 | [
"MIT"
] | jongalloway/maui | src/ControlGallery/src/Xamarin.Forms.Controls.Issues.Shared/Issue8743.cs | 1,510 | C# |
using System;
public class PlayWithTrees
{
public static void Main()
{
var tree =
new Tree<int>(7,
new Tree<int>(19,
new Tree<int>(1),
new Tree<int>(12),
new Tree<int>(31)),
new Tree<int>(21),
new Tree<int>(14,
new Tree<int>(23),
new Tree<int>(6)));
Console.WriteLine("Tree (indented):");
tree.Print();
Console.Write("Tree nodes: ");
tree.Each(c => Console.Write(" " + c));
Console.WriteLine();
Console.WriteLine();
var binaryTree =
new BinaryTree<string>("*",
new BinaryTree<string>("+",
new BinaryTree<string>("3"),
new BinaryTree<string>("2")),
new BinaryTree<string>("-",
new BinaryTree<string>("9"),
new BinaryTree<string>("6")));
Console.WriteLine("Binary tree (indented, pre-order):");
binaryTree.PrintIndentedPreOrder();
Console.Write("Binary tree nodes (in-order):");
binaryTree.EachInOrder(c => Console.Write(" " + c));
Console.WriteLine();
Console.Write("Binary tree nodes (post-order):");
binaryTree.EachPostOrder(c => Console.Write(" " + c));
Console.WriteLine();
}
} | 30.06383 | 64 | 0.478415 | [
"MIT"
] | mayapeneva/Data-Structures | 03. Basic-Trees-Tree-BinaryTree/BasicTreesLab/Trees/PlayWithTrees.cs | 1,415 | C# |
using System.Windows;
using System.Windows.Controls;
namespace TicTacToe.UI.Units
{
public class GameBoardItem : ListBoxItem
{
static GameBoardItem()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(GameBoardItem), new FrameworkPropertyMetadata(typeof(GameBoardItem)));
}
}
}
| 20.785714 | 121 | 0.783505 | [
"MIT"
] | ZTZEROS/tictactoe-wpf | src/TicTacToe/UI/Units/GameBoardItem.cs | 293 | C# |
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using SFB;
[RequireComponent(typeof(Button))]
public class CanvasSampleOpenFileImage : MonoBehaviour, IPointerDownHandler {
public RawImage output;
public GameObject loadingMsg = null;
#if UNITY_WEBGL && !UNITY_EDITOR
//
// WebGL
//
[DllImport("__Internal")]
private static extern void UploadFile(string gameObjectName, string methodName, string filter, bool multiple);
public void OnPointerDown(PointerEventData eventData) {
UploadFile(gameObject.name, "OnFileUpload", ".png, .jpg", false);
}
// Called from browser
public void OnFileUpload(string url) {
StartCoroutine(OutputRoutine(url));
}
#else
//
// Standalone platforms & editor
//
public void OnPointerDown(PointerEventData eventData) { }
void Start() {
var button = GetComponent<Button>();
button.onClick.AddListener(OnClick);
Debug.Assert(loadingMsg != null);
loadingMsg.SetActive(false);
}
private void OnClick() {
var extensions = new[] {
new ExtensionFilter("Image Files", "png", "jpg", "jpeg" ),
};
var paths = StandaloneFileBrowser.OpenFilePanel("Title", "", extensions, false);
if (paths.Length > 0) {
loadingMsg.SetActive(true);
StartCoroutine(OutputRoutine(new System.Uri(paths[0]).AbsoluteUri));
}
}
#endif
private IEnumerator OutputRoutine(string url) {
var loader = new WWW(url);
yield return loader;
output.texture = loader.texture;
loadingMsg.SetActive(false);
}
} | 28.822581 | 114 | 0.660325 | [
"MIT"
] | xeratol/UnityStandaloneFileBrowser | Assets/StandaloneFileBrowser/Sample/CanvasSampleOpenFileImage.cs | 1,787 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Threading.Tasks;
namespace ECCE.Models
{
public class ProdutoModel
{
public tb_produto tb_produto { get; set; }
public string JsonLTFoto { get; set; }
public string JsonLTGenero { get; set; }
}
public class ProdutoView
{
public tb_produto tb_produto { get; set; }
public List<produtogeneroModel> produtogeneroModel { get; set; }
public List<produtofotoModel> produtofotoModel { get; set; }
}
public class ProdutoVWList {
public tb_produto tb_produto { get; set; }
public string Foto { get; set; }
}
public class tb_produto
{
[Key]
public int CodigoProduto { get; set; }
[Display(Name = "Código", Prompt = "")]
public string CodigoInterno { get; set; }
[Display(Name = "Nome", Prompt = "")]
public string Nome { get; set; }
[Display(Name = "Descrição", Prompt = "")]
public string Descricao { get; set; }
[Display(Name = "Valor", Prompt = "")]
public decimal Valor { get; set; }
[Display(Name = "Fotos", Prompt = "")]
public string Foto { get; set; }
[Display(Name = "Data Registro", Prompt = "")]
public DateTime DataRegistro { get; set; }
[Display(Name = "Peso", Prompt = "")]
public double Peso { get; set; }
[Display(Name = "Quantidade", Prompt = "")]
public int Quantidade { get; set; }
[Display(Name = "Ativo", Prompt = "Sim / Não")]
public string Ativo { get; set; }
[Display(Name = "Tamanho", Prompt = "")]
public string Tamanho { get; set; }
[Display(Name = "Ordem de Exposição", Prompt = "")]
public int OrdemTamanho { get; set; }
}
}
| 26.575342 | 72 | 0.581443 | [
"MIT"
] | JrCbSilva/EcommerceEmCasaComEstilo | ECCE/ECCE/Models/tb_produto.cs | 1,948 | C# |
using Imagin.Common.Converters;
using Imagin.Common.Models;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
namespace Imagin.Common.Controls
{
public partial class LayoutRootControl : UserControl
{
public ILayoutControl Child
{
get => Root.Child as ILayoutControl;
set => Root.Child = value as UIElement;
}
public DockView DockView { get; private set; }
public readonly LayoutWindowControl Window;
internal Content ActiveContent { get; private set; }
/// ......................................................................................................................
public static DependencyProperty EmptyMarkerStyleProperty = DependencyProperty.Register(nameof(EmptyMarkerStyle), typeof(Style), typeof(LayoutRootControl), new FrameworkPropertyMetadata(null));
public Style EmptyMarkerStyle
{
get => (Style)GetValue(EmptyMarkerStyleProperty);
set => SetValue(EmptyMarkerStyleProperty, value);
}
public static DependencyProperty PrimaryMarkerStyleProperty = DependencyProperty.Register(nameof(PrimaryMarkerStyle), typeof(Style), typeof(LayoutRootControl), new FrameworkPropertyMetadata(null));
public Style PrimaryMarkerStyle
{
get => (Style)GetValue(PrimaryMarkerStyleProperty);
set => SetValue(PrimaryMarkerStyleProperty, value);
}
public static DependencyProperty SecondaryMarkerStyleProperty = DependencyProperty.Register(nameof(SecondaryMarkerStyle), typeof(Style), typeof(LayoutRootControl), new FrameworkPropertyMetadata(null));
public Style SecondaryMarkerStyle
{
get => (Style)GetValue(SecondaryMarkerStyleProperty);
set => SetValue(SecondaryMarkerStyleProperty, value);
}
public static DependencyProperty SelectionStyleProperty = DependencyProperty.Register(nameof(SelectionStyle), typeof(Style), typeof(LayoutRootControl), new FrameworkPropertyMetadata(null));
public Style SelectionStyle
{
get => (Style)GetValue(SelectionStyleProperty);
set => SetValue(SelectionStyleProperty, value);
}
/// ......................................................................................................................
public LayoutRootControl(DockView input, LayoutWindowControl window)
{
DockView = input;
Window = window;
InitializeComponent();
var multiBinding = new MultiBinding()
{
Converter = new MultiConverter<Visibility>(values =>
{
if ((values[1] as ILayoutControl)?.Root.Equals(this) == true)
return Visibility.Visible;
return Visibility.Collapsed;
}),
Mode = BindingMode.OneWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
multiBinding.Bindings.Add(new Binding("Drag") { Source = DockView });
multiBinding.Bindings.Add(new Binding("Drag.MouseOver") { Source = DockView });
Markers.SetBinding(VisibilityProperty, multiBinding);
foreach (MaskedImage i in SecondaryMarkers.Children)
{
if (i.Tag is Docks docks && docks == Docks.Center)
{
i.SetBinding(VisibilityProperty, new Binding()
{
Converter = new DefaultConverter<ILayoutControl, Visibility>(j =>
{
if (DockView.Dragging)
{
if (DockView.Drag.Content?.First() is Document && DockView.Drag.MouseOver is LayoutDocumentGroupControl)
return Visibility.Visible;
if (DockView.Drag.Content?.First() is Models.Panel && DockView.Drag.MouseOver is LayoutPanelGroupControl)
return Visibility.Visible;
}
return Visibility.Collapsed;
}, j => null),
Mode = BindingMode.OneWay,
Path = new PropertyPath($"{nameof(DockView.Drag)}.{nameof(DockView.Drag.MouseOver)}"),
Source = DockView,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
});
break;
}
}
}
/// ......................................................................................................................
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonUp(e);
DockView.Drag?.End(false);
}
/// ......................................................................................................................
void OnPrimaryMarkerMouseEnter(object sender, MouseEventArgs e)
{
if (DockView.Dragging)
{
switch ((Docks)(sender as FrameworkElement).Tag)
{
case Docks.Left:
Select(0, 0, ActualHeight, ActualWidth / 2);
break;
case Docks.Top:
Select(0, 0, ActualHeight / 2, ActualWidth);
break;
case Docks.Right:
Select(ActualWidth / 2, 0, ActualHeight, ActualWidth / 2);
break;
case Docks.Bottom:
Select(0, ActualHeight / 2, ActualHeight / 2, ActualWidth);
break;
}
}
}
void OnPrimaryMarkerMouseLeave(object sender, MouseEventArgs e) => Selection.Height = Selection.Width = 0;
void OnPrimaryMarkerMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
DockView.Dock(DockView.Drag.MouseOver.Root, (Docks)(sender as FrameworkElement).Tag, null, DockView.Drag.ActualContent);
DockView.Drag.End(true);
}
/// ......................................................................................................................
void OnSecondaryMarkerMouseEnter(object sender, MouseEventArgs e)
{
if (DockView.Dragging)
{
switch ((Docks)(sender as FrameworkElement).Tag)
{
case Docks.Left:
Select(DockView.Drag.MousePosition.X - (DockView.Drag.MouseOver.ActualWidth / 2), DockView.Drag.MousePosition.Y - (DockView.Drag.MouseOver.ActualHeight / 2), DockView.Drag.MouseOver.ActualHeight, DockView.Drag.MouseOver.ActualWidth / 2);
break;
case Docks.Top:
Select(DockView.Drag.MousePosition.X - (DockView.Drag.MouseOver.ActualWidth / 2), DockView.Drag.MousePosition.Y - (DockView.Drag.MouseOver.ActualHeight / 2), DockView.Drag.MouseOver.ActualHeight / 2, DockView.Drag.MouseOver.ActualWidth);
break;
case Docks.Right:
Select(DockView.Drag.MousePosition.X, DockView.Drag.MousePosition.Y - (DockView.Drag.MouseOver.ActualHeight / 2), DockView.Drag.MouseOver.ActualHeight, DockView.Drag.MouseOver.ActualWidth / 2);
break;
case Docks.Bottom:
Select(DockView.Drag.MousePosition.X - (DockView.Drag.MouseOver.ActualWidth / 2), DockView.Drag.MousePosition.Y, DockView.Drag.MouseOver.ActualHeight / 2, DockView.Drag.MouseOver.ActualWidth);
break;
case Docks.Center:
Select(DockView.Drag.MousePosition.X - (DockView.Drag.MouseOver.ActualWidth / 2), DockView.Drag.MousePosition.Y - (DockView.Drag.MouseOver.ActualHeight / 2), DockView.Drag.MouseOver.ActualHeight, DockView.Drag.MouseOver.ActualWidth);
break;
}
}
}
void OnSecondaryMarkerMouseLeave(object sender, MouseEventArgs e) => Selection.Height = Selection.Width = 0;
void OnSecondaryMarkerMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
bool result()
{
var docks = (Docks)(sender as FrameworkElement).Tag;
if (docks == Docks.Center)
return DockView.DockCenter(DockView.Drag);
object b = DockView.Drag.ActualContent;
var parent = DockView.Drag.MouseOver.GetParent();
if (parent == null)
{
DockView.Dock(DockView.Drag.MouseOver.Root, docks, null, DockView.Drag.ActualContent);
return true;
}
var index = DockView.Drag.MouseOver.GetIndex();
//If a parent exists, the index should always be >= 0; if it isn't, something wrong is happening somewhere...
if (index == -1)
return false;
DockView.Dock(DockView.Drag.MouseOver.Root, docks, DockView.Drag.MouseOver, DockView.Drag.ActualContent);
return true;
}
DockView.Drag.End(result());
}
/// ......................................................................................................................
public void Activate(Content content)
{
ActiveContent = content;
}
public void Select(double x, double y, double height, double width)
{
Selection.Height = height;
Selection.Width = width;
Canvas.SetLeft(Selection, x);
Canvas.SetTop(Selection, y);
}
}
} | 45.772727 | 261 | 0.528103 | [
"BSD-2-Clause"
] | lwFace/Imagin.NET | Imagin.Common.WPF/Controls/DockView/Controls/LayoutRootControl.xaml.cs | 10,072 | C# |
// Copyright (c) Zain Al-Ahmary. All rights reserved.
// Licensed under the MIT License, (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at https://mit-license.org/
using HDDL.Language.HDSL.Results;
using HDDL.IO.Disk;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
namespace HDDL.Data
{
/// <summary>
/// Provides data encapsulation to allow modification of systems without complete overhauls
/// </summary>
public class DataHandler : IDataHandler, IDisposable
{
public const int InfiniteDepth = -1;
/// <summary>
/// The connection string to the database
/// </summary>
public string ConnectionString { get; private set; }
/// <summary>
/// The bookmark cache
/// </summary>
private List<BookmarkItem> _bookmarkCache;
/// <summary>
/// The exclusion cache
/// </summary>
private List<ExclusionItem> _exclusionCache;
/// <summary>
/// The watch cache
/// </summary>
private List<WatchItem> _watchCache;
/// <summary>
/// The ward cache
/// </summary>
private List<WardItem> _wardCache;
/// <summary>
/// The column name mapping cache
/// </summary>
private List<ColumnNameMappingItem> _columnNameMappingCache;
/// <summary>
/// Stores pending database actions for DiskItems
/// </summary>
private RecordActionContainer<DiskItem> _diskItems;
/// <summary>
/// Stores pending database actions for Bookmarks
/// </summary>
private RecordActionContainer<BookmarkItem> _bookmarks;
/// <summary>
/// Stores pending database actions for Exclusions
/// </summary>
private RecordActionContainer<ExclusionItem> _exclusions;
/// <summary>
/// Stores pending database actions for Watches
/// </summary>
private RecordActionContainer<WatchItem> _watches;
/// <summary>
/// Stores pending database actions for Wards
/// </summary>
private RecordActionContainer<WardItem> _wards;
/// <summary>
/// Stores pending database actions for DiskItemHashLogItems
/// </summary>
private RecordActionContainer<DiskItemHashLogItem> _hashLogs;
/// <summary>
/// Stores the pending database actions for the ColumnNameMappingItems
/// </summary>
private RecordActionContainer<ColumnNameMappingItem> _columnNameMappings;
/// <summary>
/// The current database connection
/// </summary>
private SQLiteConnection _connection;
/// <summary>
/// Creates a DataHandler
/// </summary>
/// <param name="connectionString">The connection string</param>
public DataHandler(string connectionString)
{
ConnectionString = connectionString;
_diskItems = new RecordActionContainer<DiskItem>();
_bookmarks = new RecordActionContainer<BookmarkItem>();
_exclusions = new RecordActionContainer<ExclusionItem>();
_watches = new RecordActionContainer<WatchItem>();
_wards = new RecordActionContainer<WardItem>();
_hashLogs = new RecordActionContainer<DiskItemHashLogItem>();
_columnNameMappings = new RecordActionContainer<ColumnNameMappingItem>();
_bookmarkCache = null;
_exclusionCache = null;
_watchCache = null;
_wardCache = null;
_columnNameMappingCache = null;
}
~DataHandler()
{
Dispose();
}
/// <summary>
/// Safely obtains a DataHandler
///
/// Will throw exception if database file is in use
/// </summary>
/// <param name="dbPath">The path to look at</param>
/// <returns></returns>
public static DataHandler Get(string dbPath)
{
if (!File.Exists(dbPath))
{
InitializeDatabase(dbPath);
}
return new DataHandler(dbPath);
}
#region General Utility
/// <summary>
/// Takes a type and returns a default width to display it (in character count)
/// </summary>
/// <param name="propertyType">The type</param>
/// <returns>The number of characters width its column should be</returns>
private int GetWidthByType(Type propertyType)
{
var width = ColumnDefinition.UnrestrictedWidth;
if (propertyType == typeof(long))
{
width = 10;
}
else if (propertyType == typeof(DateTime))
{
width = 22;
}
else if (propertyType == typeof(string))
{
width = 100;
}
else if (propertyType == typeof(bool))
{
width = 3;
}
else if (propertyType == typeof(Guid))
{
width = Guid.Empty.ToString().Length;
}
else if (propertyType == typeof(int))
{
width = 10;
}
else if (propertyType == typeof(TimeSpan))
{
width = 20;
}
return width;
}
/// <summary>
/// Generates items in the insertion queue for the given type
/// </summary>
/// <param name="type">The type to generate records for</param>
/// <returns>The number of records queued insertion</returns>
private long QueueRecordsForType(Type type)
{
var generated = 0;
var props = type.GetProperties();
foreach (var p in props)
{
if (p.PropertyType != typeof(DiskItem))
{
Insert(new ColumnNameMappingItem()
{
Id = Guid.NewGuid(),
Name = p.Name,
Alias = p.Name,
IsActive = true,
HostType = type.FullName,
IsDefault = false,
DisplayWidth = GetWidthByType(p.PropertyType)
});
generated++;
}
}
return generated;
}
#endregion
#region Database Utility
/// <summary>
/// Initializes the database at the indicated path.
/// Recreates it if it already exists
/// </summary>
/// <param name="recreate">If true, deletes and rebuilds the file database</param>
/// <param name="connectionString">The connection string</param>
public static void InitializeDatabase(string connectionString, bool recreate = false)
{
if (recreate && File.Exists(connectionString))
{
File.Delete(connectionString);
}
if (!File.Exists(connectionString))
{
SQLiteConnection.CreateFile(connectionString);
// create the tables
using (var sqltCon = new SQLiteConnection($"data source={connectionString}"))
{
using (var command = new SQLiteCommand(
@"
create table if not exists diskitems (
id text not null primary key,
parentId text references diskitems(id) on delete cascade,
firstScanned text not null,
lastScanned text not null,
path text not null unique,
depth integer not null,
itemName text not null,
isFile integer not null,
extension text,
size integer,
lastWritten text,
lastAccessed text,
created text not null,
hash text,
lastHashed text,
attributes integer,
unc text not null
);
create unique index diskitems_path_index on diskitems(path);
create index diskitems_itemName_index on diskitems(itemName);
create table if not exists bookmarks (
id text not null primary key,
target text not null,
itemName text not null
);
create unique index bookmarks_itemName_index on bookmarks(itemName);
create table if not exists watches (
id text not null primary key,
path text not null,
inPassiveMode integer not null
);
create unique index watches_path_index on watches(path);
create table if not exists wards (
id text not null primary key,
path text not null,
call text not null,
scheduledFor text not null,
interval text not null
);
create unique index wards_path_index on wards(path);
create table if not exists exclusions (
id text not null primary key,
path text not null
);
create unique index exclusions_path_index on exclusions(path);
create table if not exists hashlog (
id text not null primary key,
path text not null,
occurred text not null,
oldhash text,
newhash text,
unc text not null
);
create table if not exists columnnamemappings (
id text not null primary key,
name text not null,
alias text not null,
isActive integer not null,
type text not null,
isDefault integer not null,
width integer not null
);
create unique index columnnamemappings_name_index on columnnamemappings(name, type);
create unique index columnnamemappings_alias_index on columnnamemappings(alias, type);",
sqltCon))
{
if (sqltCon.State == ConnectionState.Closed)
sqltCon.Open();
command.ExecuteNonQuery();
}
}
using (var dh = new DataHandler(connectionString))
{
dh.ResetColumnNameMappingTable();
}
}
}
/// <summary>
/// Ensures that a connection is available and open
/// </summary>
/// <returns></returns>
private SQLiteConnection EnsureConnection()
{
if (_connection == null)
{
_connection = new SQLiteConnection($"data source={ConnectionString}");
_connection.Open();
// add extensions
_connection.EnableExtensions(true);
_connection.LoadExtension("re");
_connection.LoadExtension("fuzzy");
}
if (_connection.State == ConnectionState.Closed)
_connection.Open();
return _connection;
}
/// <summary>
/// Executes a query
/// </summary>
/// <param name="sql">The sql to execute</param>
private void ExecuteNonQuery(string sql)
{
using (var command = new SQLiteCommand(sql, EnsureConnection()))
{
command.ExecuteNonQuery();
}
}
/// <summary>
/// Executes a query
/// </summary>
/// <param name="sql">The sql to execute</param>
/// <param name="behavior">The commands behavior</param>
private SQLiteDataReader ExecuteReader(string sql, CommandBehavior behavior = CommandBehavior.Default)
{
using (var command = new SQLiteCommand(sql, EnsureConnection()))
{
return command.ExecuteReader(behavior);
}
}
/// <summary>
/// Executes a query with a single return value
/// </summary>
/// <param name="sql">The sql to execute</param>
/// <param name="behavior">The commands behavior</param>
private T ExecuteScalar<T>(string sql, CommandBehavior behavior = CommandBehavior.Default)
{
T result = default(T);
using (var command = new SQLiteCommand(sql, EnsureConnection()))
{
result = (T)command.ExecuteScalar();
}
return result;
}
/// <summary>
/// Executes a SQL query and returns the number of records returned by it
/// </summary>
/// <param name="sql">The query to execute</param>
/// <returns></returns>
private long GetCount(string sql)
{
using (var command = new SQLiteCommand($"select count(id) from {sql}", EnsureConnection()))
{
return (long)command.ExecuteScalar();
}
}
#endregion
#region Column Name Mappings
/// <summary>
/// Retrieves and returns the mapping for a given column type combination
/// </summary>
/// <param name="nameorAlias">The name of the column</param>
/// <param name="hostType">The name of the hosting type</param>
/// <returns>Null or the record</returns>
public ColumnNameMappingItem GetMappingByNameAndType(string nameorAlias, Type hostType)
{
var mapping = GetColumnNameMappings(hostType)
.Where(m =>
m.Name.Equals(nameorAlias, StringComparison.InvariantCultureIgnoreCase) ||
m.Alias.Equals(nameorAlias, StringComparison.InvariantCultureIgnoreCase))
.SingleOrDefault();
if (mapping != null)
{
return mapping;
}
return null;
}
/// <summary>
/// Retrieves the type of the given column
/// </summary>
/// <param name="nameOrAlias">Either the column name or alias, as defined in a mapping</param>
/// <param name="recordType">The type where the column is defined</param>
/// <returns>The type or null</returns>
public Type? GetColumnType(string nameOrAlias, Type recordType)
{
var mapping = GetColumnNameMappings(recordType)
.Where(m =>
m.Name.Equals(nameOrAlias, StringComparison.InvariantCultureIgnoreCase) ||
m.Alias.Equals(nameOrAlias, StringComparison.InvariantCultureIgnoreCase))
.SingleOrDefault();
if (mapping != null)
{
return mapping.DataType;
}
return null;
}
/// <summary>
/// Performs the initial write for default mappings
/// </summary>
/// <returns>A tuple in the format total [inserts, updates, deletes]</returns>
public Tuple<long, long, long> ResetColumnNameMappingTable()
{
var deletions = ClearColumnNameMappings();
// Create an alias records for the various types
QueueRecordsForType(typeof(DiskItem));
QueueRecordsForType(typeof(WardItem));
QueueRecordsForType(typeof(WatchItem));
QueueRecordsForType(typeof(DiskItemHashLogItem));
var result = WriteColumnNameMappings();
return new Tuple<long, long, long>(result.Item1, result.Item2, result.Item3 + deletions);
}
/// <summary>
/// Retrieves and returns the ColumnNameMappings
/// </summary>
/// <param name="forType">The type to pull mappings for</param>
/// <returns></returns>
public List<ColumnNameMappingItem> GetColumnNameMappings(Type forType)
{
if (_columnNameMappingCache == null ||
(_columnNameMappingCache != null && _columnNameMappingCache.Count == 0))
{
_columnNameMappingCache = new List<ColumnNameMappingItem>();
var mappings = ExecuteReader(@$"select * from columnnamemappings");
while (mappings.Read())
{
_columnNameMappingCache.Add(new ColumnNameMappingItem(mappings));
}
}
return _columnNameMappingCache.Where(m => m.HostType == forType.FullName).ToList();
}
/// <summary>
/// Retrieves and returns the ColumnNameMappings
/// </summary>
/// <returns></returns>
public List<ColumnNameMappingItem> GetAllColumnNameMappings()
{
if (_columnNameMappingCache == null ||
(_columnNameMappingCache != null && _columnNameMappingCache.Count == 0))
{
_columnNameMappingCache = new List<ColumnNameMappingItem>();
var mappings = ExecuteReader(@$"select * from columnnamemappings");
while (mappings.Read())
{
_columnNameMappingCache.Add(new ColumnNameMappingItem(mappings));
}
}
return _columnNameMappingCache;
}
/// <summary>
/// Clears any cached bookmarks, forcing them to be reloaded for the next GetBookmarks() call
/// </summary>
public void ClearColumnNameMappingCache()
{
if (_columnNameMappingCache == null) return;
_columnNameMappingCache.Clear();
_columnNameMappingCache = null;
}
/// <summary>
/// Deletes all ColumnNameMappings from the database
/// </summary>
public long ClearColumnNameMappings()
{
ClearColumnNameMappingCache();
var count = GetCount("columnnamemappings");
ExecuteNonQuery("delete from columnnamemappings");
return count;
}
/// <summary>
/// Queues the records for transactionary insertion
/// </summary>
/// <param name="items">The records to be added</param>
/// <returns></returns>
public void Insert(params ColumnNameMappingItem[] items)
{
foreach (var item in items)
{
_columnNameMappings.Inserts.Add(item);
}
}
/// <summary>
/// Queues the records for the transactionary update
/// </summary>
/// <param name="items">The records to be updated</param>
public void Update(params ColumnNameMappingItem[] items)
{
foreach (var item in items)
{
_columnNameMappings.Updates.Add(item);
}
}
/// <summary>
/// Queues the records for the transactionary deletion
/// </summary>
/// <param name="items"></param>
public void Delete(params ColumnNameMappingItem[] items)
{
foreach (var item in items)
{
_columnNameMappings.Deletions.Add(item);
}
}
/// <summary>
/// Performs a transactionary database execution of all pending inserts, updates, and deletes
/// </summary>
/// <returns>A tuple in the format total [inserts, updates, deletes]</returns>
public Tuple<long, long, long> WriteColumnNameMappings()
{
long inserts = 0, updates = 0, deletes = 0;
if (_columnNameMappings.HasWork)
{
using (var transaction = EnsureConnection().BeginTransaction())
{
if (_columnNameMappings.Inserts.Count > 0)
{
foreach (var insert in _columnNameMappings.Inserts)
{
ExecuteNonQuery(insert.ToInsertStatement());
inserts++;
}
_columnNameMappings.Inserts.Clear();
}
if (_columnNameMappings.Updates.Count > 0)
{
foreach (var update in _columnNameMappings.Updates)
{
ExecuteNonQuery(update.ToUpdateStatement());
updates++;
}
_columnNameMappings.Updates.Clear();
}
if (_columnNameMappings.Deletions.Count > 0)
{
var sql = $"({ string.Join(", ", from delete in _columnNameMappings.Deletions select $"'{delete.Id}'") })";
deletes = GetCount($"columnnamemappings where id in {sql};");
ExecuteNonQuery($"DELETE from columnnamemappings where id in {sql};");
_columnNameMappings.Deletions.Clear();
}
transaction.Commit();
}
}
if (inserts > 0 || updates > 0 || deletes > 0)
{
ClearColumnNameMappingCache();
}
return new Tuple<long, long, long>(inserts, updates, deletes);
}
#endregion
#region DiskItemHashLog Related
/// <summary>
/// Retrieves all hashlogs for records that match the criteria
/// </summary>
/// <param name="whereDetail">The filtering detail provided through the Find statement's where clause</param>
/// <param name="sortGroupDetail">The sorting and grouping detail provided through the Find statement's appropriate clause</param>
/// <param name="paths">The paths to search</param>
/// <returns>The matching DiskItems</returns>
internal IEnumerable<DiskItemHashLogItem> GetFilteredHashLogs(string whereDetail, string sortGroupDetail, IEnumerable<string> paths)
{
if (paths.Any())
{
var pathListing = string.Join("','", paths);
var results = new List<DiskItemHashLogItem>();
// retrieve all hashlogs for all retrieved records by parent id
var detailClause = string.IsNullOrWhiteSpace(whereDetail) ? string.Empty : $" and {whereDetail}";
var records = ExecuteReader($"select * from hashlog where path in ('{pathListing}'){detailClause}{sortGroupDetail}");
while (records.Read())
{
results.Add(new DiskItemHashLogItem(records));
}
return results.ToArray();
}
return new DiskItemHashLogItem[] { };
}
/// <summary>
/// Deletes all DiskitemHashLogs from the database
/// </summary>
public long ClearDiskItemHashLogs()
{
var count = GetCount("hashlog");
ExecuteNonQuery("delete from hashlog");
return count;
}
/// <summary>
/// Queues the records for transactionary insertion
/// </summary>
/// <param name="items">The records to be added</param>
/// <returns></returns>
public void Insert(params DiskItemHashLogItem[] items)
{
foreach (var item in items)
{
_hashLogs.Inserts.Add(item);
}
}
/// <summary>
/// Queues the records for the transactionary update
/// </summary>
/// <param name="items">The records to be updated</param>
public void Update(params DiskItemHashLogItem[] items)
{
foreach (var item in items)
{
_hashLogs.Updates.Add(item);
}
}
/// <summary>
/// Queues the records for the transactionary deletion
/// </summary>
/// <param name="items"></param>
public void Delete(params DiskItemHashLogItem[] items)
{
foreach (var item in items)
{
_hashLogs.Deletions.Add(item);
}
}
/// <summary>
/// Performs a transactionary database execution of all pending inserts, updates, and deletes
/// </summary>
/// <returns>A tuple in the format total [inserts, updates, deletes]</returns>
public Tuple<long, long, long> WriteDiskItemHashLogs()
{
long inserts = 0, updates = 0, deletes = 0;
if (_hashLogs.HasWork)
{
using (var transaction = EnsureConnection().BeginTransaction())
{
if (_hashLogs.Inserts.Count > 0)
{
foreach (var insert in _hashLogs.Inserts)
{
ExecuteNonQuery(insert.ToInsertStatement());
inserts++;
}
_hashLogs.Inserts.Clear();
}
if (_hashLogs.Updates.Count > 0)
{
foreach (var update in _hashLogs.Updates)
{
ExecuteNonQuery(update.ToUpdateStatement());
updates++;
}
_hashLogs.Updates.Clear();
}
if (_hashLogs.Deletions.Count > 0)
{
var sql = $"({ string.Join(", ", from delete in _hashLogs.Deletions select $"'{delete.Id}'") })";
deletes = GetCount($"hashlog where id in {sql};");
ExecuteNonQuery($"DELETE from hashlog where id in {sql};");
_hashLogs.Deletions.Clear();
}
transaction.Commit();
}
}
return new Tuple<long, long, long>(inserts, updates, deletes);
}
#endregion
#region Watch Related
/// <summary>
/// Retrieves all wards for the given paths and criteria
/// </summary>
/// <param name="whereDetail">The filtering detail provided through the Find statement's where clause</param>
/// <param name="sortGroupDetail">The sorting and grouping detail provided through the Find statement's appropriate clause</param>
/// <param name="paths">The paths to search</param>
/// <returns>The matching DiskItems</returns>
internal IEnumerable<WatchItem> GetFilteredWatches(string whereDetail, string sortGroupDetail, IEnumerable<string> paths)
{
if (paths.Any())
{
var pathListing = string.Join("','", paths);
var results = new List<WatchItem>();
// retrieve all hashlogs for all retrieved records by parent id
var detailClause = string.IsNullOrWhiteSpace(whereDetail) ? string.Empty : $" and {whereDetail}";
var records = ExecuteReader($"select * from watches where path in ('{pathListing}'){detailClause}{sortGroupDetail}");
while (records.Read())
{
DiskItem di = null;
if (!(records["path"] is DBNull))
{
di = GetDiskItemByPath(records.GetString("path"));
}
results.Add(new WatchItem(records, di));
}
return results.ToArray();
}
return new WatchItem[] { };
}
/// <summary>
/// Retrieves and returns the watches
/// </summary>
/// <returns></returns>
public List<WatchItem> GetWatches()
{
if (_watchCache == null ||
(_watchCache != null && _watchCache.Count == 0))
{
_watchCache = new List<WatchItem>();
var watches = ExecuteReader(@"select * from watches");
while (watches.Read())
{
DiskItem di = null;
if (!(watches["path"] is DBNull))
{
di = GetDiskItemByPath(watches.GetString("path"));
}
_watchCache.Add(new WatchItem(watches, di));
}
}
return _watchCache;
}
/// <summary>
/// Clears any cached bookmarks, forcing them to be reloaded for the next GetBookmarks() call
/// </summary>
public void ClearWatchCache()
{
if (_watchCache == null) return;
_watchCache.Clear();
_watchCache = null;
}
/// <summary>
/// Deletes all watches from the database
/// </summary>
public long ClearWatches()
{
ClearWatchCache();
var count = GetCount("watches");
ExecuteNonQuery("delete from watches");
return count;
}
/// <summary>
/// Queues the records for transactionary insertion
/// </summary>
/// <param name="items">The records to be added</param>
/// <returns></returns>
public void Insert(params WatchItem[] items)
{
foreach (var item in items)
{
_watches.Inserts.Add(item);
}
}
/// <summary>
/// Queues the records for transactionary insertion
/// </summary>
/// <param name="items">The records to be added</param>
/// <returns></returns>
public void Insert(params string[] items)
{
foreach (var item in items)
{
_watches.Inserts.Add(new WatchItem()
{
Id = Guid.NewGuid(),
InPassiveMode = false,
Path = item,
Target = null
});
}
}
/// <summary>
/// Queues the records for the transactionary update
/// </summary>
/// <param name="items">The records to be updated</param>
public void Update(params WatchItem[] items)
{
foreach (var item in items)
{
_watches.Updates.Add(item);
}
}
/// <summary>
/// Queues the record(s) for a reset (having its passive mode turned off to force a fresh disk scan)
/// </summary>
/// <param name="items">The records to be updated</param>
public void Reset(params WatchItem[] items)
{
foreach (var item in items)
{
item.InPassiveMode = false;
_watches.Updates.Add(item);
}
}
/// <summary>
/// Queues the record(s) for a reset (having its passive mode turned off to force a fresh disk scan)
/// </summary>
/// <param name="items">The records to be updated</param>
public void Reset(params string[] items)
{
foreach (var item in items)
{
var watch = GetWatches().Where(w => w.Path == item).SingleOrDefault();
watch.InPassiveMode = false;
_watches.Updates.Add(watch);
}
}
/// <summary>
/// Queues the records for the transactionary deletion
/// </summary>
/// <param name="items"></param>
public void Delete(params WatchItem[] items)
{
foreach (var item in items)
{
_watches.Deletions.Add(item);
}
}
/// <summary>
/// Performs a transactionary database execution of all pending inserts, updates, and deletes
/// </summary>
/// <returns>A tuple in the format total [inserts, updates, deletes]</returns>
public Tuple<long, long, long> WriteWatches()
{
long inserts = 0, updates = 0, deletes = 0;
if (_watches.HasWork)
{
using (var transaction = EnsureConnection().BeginTransaction())
{
if (_watches.Inserts.Count > 0)
{
foreach (var insert in _watches.Inserts)
{
ExecuteNonQuery(insert.ToInsertStatement());
inserts++;
}
_watches.Inserts.Clear();
}
if (_watches.Updates.Count > 0)
{
foreach (var update in _watches.Updates)
{
ExecuteNonQuery(update.ToUpdateStatement());
updates++;
}
_watches.Updates.Clear();
}
if (_watches.Deletions.Count > 0)
{
var sql = $"({ string.Join(", ", from delete in _watches.Deletions select $"'{delete.Id}'") })";
deletes = GetCount($"watches where id in {sql};");
ExecuteNonQuery($"DELETE from watches where id in {sql};");
_watches.Deletions.Clear();
}
transaction.Commit();
}
}
if (inserts > 0 || updates > 0 || deletes > 0)
{
ClearWatchCache();
}
return new Tuple<long, long, long>(inserts, updates, deletes);
}
#endregion
#region Ward Related
/// <summary>
/// Retrieves all wards for the given paths and criteria
/// </summary>
/// <param name="whereDetail">The filtering detail provided through the Find statement's where clause</param>
/// <param name="sortGroupDetail">The sorting and grouping detail provided through the Find statement's appropriate clause</param>
/// <param name="paths">The paths to search</param>
/// <returns>The matching DiskItems</returns>
internal IEnumerable<WardItem> GetFilteredWards(string whereDetail, string sortGroupDetail, IEnumerable<string> paths)
{
if (paths.Any())
{
var pathListing = string.Join("','", paths);
var results = new List<WardItem>();
// retrieve all hashlogs for all retrieved records by parent id
var detailClause = string.IsNullOrWhiteSpace(whereDetail) ? string.Empty : $" and {whereDetail}";
var records = ExecuteReader($"select * from wards where path in ('{pathListing}'){detailClause}{sortGroupDetail}");
while (records.Read())
{
DiskItem di = null;
if (!(records["path"] is DBNull))
{
di = GetDiskItemByPath(records.GetString("path"));
}
results.Add(new WardItem(records, di));
}
return results.ToArray();
}
return new WardItem[] { };
}
/// <summary>
/// Retrieves and returns the wards
/// </summary>
/// <returns></returns>
public List<WardItem> GetWards()
{
if (_wardCache == null ||
(_wardCache != null && _wardCache.Count == 0))
{
_wardCache = new List<WardItem>();
var wards = ExecuteReader(@"select * from wards");
while (wards.Read())
{
DiskItem di = null;
if (!(wards["path"] is DBNull))
{
di = GetDiskItemByPath(wards.GetString("path"));
}
_wardCache.Add(new WardItem(wards, di));
}
}
return _wardCache;
}
/// <summary>
/// Clears any cached wards, forcing them to be reloaded for the next GetBookmarks() call
/// </summary>
public void ClearWardCache()
{
if (_wardCache == null) return;
_wardCache.Clear();
_wardCache = null;
}
/// <summary>
/// Deletes all watches from the database
/// </summary>
public long ClearWards()
{
ClearWardCache();
var count = GetCount("wards");
ExecuteNonQuery("delete from wards");
return count;
}
/// <summary>
/// Queues the records for transactionary insertion
/// </summary>
/// <param name="items">The records to be added</param>
/// <returns></returns>
public void Insert(params WardItem[] items)
{
foreach (var item in items)
{
_wards.Inserts.Add(item);
}
}
/// <summary>
/// Queues the records for the transactionary update
/// </summary>
/// <param name="items">The records to be updated</param>
public void Update(params WardItem[] items)
{
foreach (var item in items)
{
_wards.Updates.Add(item);
}
}
/// <summary>
/// Queues the records for the transactionary deletion
/// </summary>
/// <param name="items"></param>
public void Delete(params WardItem[] items)
{
foreach (var item in items)
{
_wards.Deletions.Add(item);
}
}
/// <summary>
/// Performs a transactionary database execution of all pending inserts, updates, and deletes
/// </summary>
/// <returns>A tuple in the format total [inserts, updates, deletes]</returns>
public Tuple<long, long, long> WriteWards()
{
long inserts = 0, updates = 0, deletes = 0;
if (_wards.HasWork)
{
using (var transaction = EnsureConnection().BeginTransaction())
{
if (_wards.Inserts.Count > 0)
{
foreach (var insert in _wards.Inserts)
{
ExecuteNonQuery(insert.ToInsertStatement());
inserts++;
}
_wards.Inserts.Clear();
}
if (_wards.Updates.Count > 0)
{
foreach (var update in _wards.Updates)
{
ExecuteNonQuery(update.ToUpdateStatement());
updates++;
}
_wards.Updates.Clear();
}
if (_wards.Deletions.Count > 0)
{
var sql = $"({ string.Join(", ", from delete in _wards.Deletions select $"'{delete.Id}'") })";
deletes = GetCount($"wards where id in {sql};");
ExecuteNonQuery($"DELETE from wards where id in {sql};");
_wards.Deletions.Clear();
}
transaction.Commit();
}
}
if (inserts > 0 || updates > 0 || deletes > 0)
{
ClearWardCache();
}
return new Tuple<long, long, long>(inserts, updates, deletes);
}
#endregion
#region Exclusion Related
/// <summary>
/// Retrieves and returns the bookmarks
/// </summary>
/// <returns></returns>
public List<ExclusionItem> GetExclusions()
{
if (_exclusionCache == null ||
(_exclusionCache != null && _exclusionCache.Count == 0))
{
_exclusionCache = new List<ExclusionItem>();
var exclusions = ExecuteReader(@"select * from exclusions");
while (exclusions.Read())
{
_exclusionCache.Add(new ExclusionItem(exclusions));
}
}
return _exclusionCache;
}
/// <summary>
/// Retrieves and returns all Exclusions and expands dynamic exclusions (removing dead ones from the list)
/// </summary>
/// <returns></returns>
public List<ExclusionItem> GetProcessedExclusions()
{
var results = new List<ExclusionItem>();
foreach (var e in GetExclusions())
{
if (e.IsDynamic)
{
e.Path = ApplyBookmarks(e.Path);
}
results.Add(e);
}
return results;
}
/// <summary>
/// Clears any cached bookmarks, forcing them to be reloaded for the next GetBookmarks() call
/// </summary>
public void ClearExclusionCache()
{
if (_exclusionCache == null) return;
_exclusionCache.Clear();
_exclusionCache = null;
}
/// <summary>
/// Deletes all bookmarks from the database
/// </summary>
public long ClearExclusions()
{
ClearExclusionCache();
var count = GetCount("exclusions");
ExecuteNonQuery("delete from exclusions");
return count;
}
/// <summary>
/// Queues the records for transactionary insertion
/// </summary>
/// <param name="items">The records to be added</param>
/// <returns></returns>
public void Insert(params ExclusionItem[] items)
{
foreach (var item in items)
{
_exclusions.Inserts.Add(item);
}
}
/// <summary>
/// Queues the records for the transactionary update
/// </summary>
/// <param name="items">The records to be updated</param>
public void Update(params ExclusionItem[] items)
{
foreach (var item in items)
{
_exclusions.Updates.Add(item);
}
}
/// <summary>
/// Queues the records for the transactionary deletion
/// </summary>
/// <param name="items"></param>
public void Delete(params ExclusionItem[] items)
{
foreach (var item in items)
{
_exclusions.Deletions.Add(item);
}
}
/// <summary>
/// Performs a transactionary database execution of all pending inserts, updates, and deletes
/// </summary>
/// <returns>A tuple in the format total [inserts, updates, deletes]</returns>
public Tuple<long, long, long> WriteExclusions()
{
long inserts = 0, updates = 0, deletes = 0;
if (_exclusions.HasWork)
{
using (var transaction = EnsureConnection().BeginTransaction())
{
if (_exclusions.Inserts.Count > 0)
{
foreach (var insert in _exclusions.Inserts)
{
ExecuteNonQuery(insert.ToInsertStatement());
inserts++;
}
_exclusions.Inserts.Clear();
}
if (_exclusions.Updates.Count > 0)
{
foreach (var update in _exclusions.Updates)
{
ExecuteNonQuery(update.ToUpdateStatement());
updates++;
}
_exclusions.Updates.Clear();
}
if (_exclusions.Deletions.Count > 0)
{
var sql = $"({ string.Join(", ", from delete in _exclusions.Deletions select $"'{delete.Id}'") })";
deletes = GetCount($"exclusions where id in {sql};");
ExecuteNonQuery($"DELETE from exclusions where id in {sql};");
_exclusions.Deletions.Clear();
}
transaction.Commit();
}
}
if (inserts > 0 || updates > 0 || deletes > 0)
{
ClearExclusionCache();
}
return new Tuple<long, long, long>(inserts, updates, deletes);
}
#endregion
#region Bookmark Related
/// <summary>
/// Replaces bookmarks with their values
/// </summary>
/// <param name="text">The text to look over</param>
/// <param name="markType">The type of bookmark to apply</param>
/// <returns>Return the result</returns>
public string ApplyBookmarks(string text)
{
foreach (var bm in GetBookmarks())
{
text = text.Replace($"[{bm.ItemName}]", bm.Target);
}
return text;
}
/// <summary>
/// Retrieves and returns the bookmarks
/// </summary>
/// <returns></returns>
public List<BookmarkItem> GetBookmarks()
{
if (_bookmarkCache == null ||
(_bookmarkCache != null && _bookmarkCache.Count == 0))
{
_bookmarkCache = new List<BookmarkItem>();
var bookmarks = ExecuteReader(@"select * from bookmarks");
while (bookmarks.Read())
{
_bookmarkCache.Add(new BookmarkItem(bookmarks));
}
}
return _bookmarkCache;
}
/// <summary>
/// Clears any cached bookmarks, forcing them to be reloaded for the next GetBookmarks() call
/// </summary>
public void ClearBookmarkCache()
{
if (_bookmarkCache == null) return;
_bookmarkCache.Clear();
_bookmarkCache = null;
}
/// <summary>
/// Deletes all bookmarks from the database
/// </summary>
public long ClearBookmarks()
{
ClearBookmarkCache();
var count = GetCount("bookmarks");
ExecuteNonQuery("delete from bookmarks");
return count;
}
/// <summary>
/// Queues the records for transactionary insertion
/// </summary>
/// <param name="items">The records to be added</param>
/// <returns></returns>
public void Insert(params BookmarkItem[] items)
{
foreach (var item in items)
{
_bookmarks.Inserts.Add(item);
}
}
/// <summary>
/// Queues the records for the transactionary update
/// </summary>
/// <param name="items">The records to be updated</param>
public void Update(params BookmarkItem[] items)
{
foreach (var item in items)
{
_bookmarks.Updates.Add(item);
}
}
/// <summary>
/// Queues the records for the transactionary deletion
/// </summary>
/// <param name="items"></param>
public void Delete(params BookmarkItem[] items)
{
foreach (var item in items)
{
_bookmarks.Deletions.Add(item);
}
}
/// <summary>
/// Performs a transactionary database execution of all pending inserts, updates, and deletes
/// </summary>
/// <returns>A tuple in the format total [inserts, updates, deletes]</returns>
public Tuple<long, long, long> WriteBookmarks()
{
long inserts = 0, updates = 0, deletes = 0;
if (_bookmarks.HasWork)
{
using (var transaction = EnsureConnection().BeginTransaction())
{
if (_bookmarks.Inserts.Count > 0)
{
foreach (var insert in _bookmarks.Inserts)
{
ExecuteNonQuery(insert.ToInsertStatement());
inserts++;
}
_bookmarks.Inserts.Clear();
}
if (_bookmarks.Updates.Count > 0)
{
foreach (var update in _bookmarks.Updates)
{
ExecuteNonQuery(update.ToUpdateStatement());
updates++;
}
_bookmarks.Updates.Clear();
}
if (_bookmarks.Deletions.Count > 0)
{
var sql = $"({ string.Join(", ", from delete in _bookmarks.Deletions select $"'{delete.Id}'") })";
deletes = GetCount($"bookmarks where id in {sql};");
ExecuteNonQuery($"DELETE from bookmarks where id in {sql};");
_bookmarks.Deletions.Clear();
}
transaction.Commit();
}
}
if (inserts > 0 || updates > 0 || deletes > 0)
{
ClearBookmarkCache();
}
return new Tuple<long, long, long>(inserts, updates, deletes);
}
#endregion
#region DiskItem Related
/// <summary>
/// Retrieves and returns the current number of Disk Items in the database
/// </summary>
/// <returns>The number of Disk Item records in the database</returns>
public long GetDiskItemCount()
{
var count = ExecuteScalar<long>("select count(*) from diskitems;");
return count;
}
/// <summary>
/// Updates the provided records' integrity hashes and last hashed dates
/// </summary>
/// <param name="diskitems">The records to check</param>
/// <returns></returns>
public int UpdateHashes(IEnumerable<DiskItem> diskitems)
{
var count = 0;
if (diskitems.Count() > 0)
{
using (var transaction = EnsureConnection().BeginTransaction())
{
foreach (var diskitem in diskitems)
{
ExecuteNonQuery(diskitem.ToHashUpdateStatement());
count++;
}
transaction.Commit();
}
}
return count;
}
/// <summary>
/// Removes the matching diskitem records from the database, effectively removing tracking for those files.
/// Subsequent scans can however return the records to the structure.
/// </summary>
/// <param name="whereDetail">The filtering detail provided through the Find statement's where clause</param>
/// <param name="paths">The paths to search</param>
/// <returns></returns>
public int PurgeQueried(string whereDetail, IEnumerable<string> paths)
{
var queries = new List<string>();
if (paths.Count() > 0)
{
foreach (var path in paths)
{
var query = $"[directive] diskitems"; // " where path like '{path}%'"
// build the where clause
var whereRequired = false;
var whereClause = new StringBuilder();
if (paths.Count() > 0)
{
whereClause.Append($"path like '{path}%'");
whereRequired = true;
}
if (!string.IsNullOrWhiteSpace(whereDetail))
{
if (whereClause.Length > 0)
{
whereClause.Append($" and ");
}
whereClause.Append($"({whereDetail});");
whereRequired = true;
}
if (whereRequired)
{
queries.Add($"{query} where {whereClause}");
}
}
}
else
{
// if we have no paths, check if there's a whereDetail defined.
if (!string.IsNullOrWhiteSpace(whereDetail))
{
queries.Add($"[directive] diskitems where ({whereDetail});");
}
else
{
queries.Add($"[directive] diskitems;");
}
}
// get a count of the number of records that will be purged
var count = 0;
var reader = ExecuteReader(string.Join('\n', queries).Replace("[directive]", "select count(*) from"));
if (reader.HasRows)
{
do
{
while (reader.HasRows && reader.Read())
{
count += reader.GetInt32(0);
}
}
while (reader.NextResult());
}
// Perform the deletions
ExecuteNonQuery(string.Join('\n', queries).Replace("[directive]", "delete from"));
return count;
}
/// <summary>
/// Retrieves all records at the provided depths relative to the given path, obeying all defined criteria
/// </summary>
/// <param name="whereDetail">The filtering detail provided through the Find statement's where clause</param>
/// <param name="sortGroupDetail">The sorting and grouping detail provided through the Find statement's appropriate clause</param>
/// <param name="paths">The paths to search</param>
/// <param name="depthSpecification">The depth criteria for the search</param>
/// <returns>The matching DiskItems</returns>
private IEnumerable<DiskItem> GetFilteredDiskItems(string whereDetail, string sortGroupDetail, IEnumerable<string> paths, string depthSpecification)
{
var queries = new List<string>();
var results = new List<DiskItem>();
foreach (var path in paths)
{
var depth = PathHelper.GetDependencyCount(new DiskItemType(path, false));
var query = $"select * from diskitems where path like '{path}%' and {depthSpecification}".Replace("[current]", depth.ToString());
if (!string.IsNullOrWhiteSpace(whereDetail))
{
queries.Add($"{query} and ({whereDetail}){sortGroupDetail};");
}
else
{
queries.Add($"{query}{sortGroupDetail};");
}
}
var reader = ExecuteReader(string.Join('\n', queries));
if (reader.HasRows)
{
do
{
while (reader.HasRows && reader.Read())
{
results.Add(new DiskItem(reader));
}
}
while (reader.NextResult());
}
return results;
}
/// <summary>
/// Retrieves all records immediately inside of any of the provided paths, matching the given filter with the provided whereDetail
/// </summary>
/// <param name="whereDetail">The filtering detail provided through the Find statement's where clause</param>
/// <param name="sortGroupDetail">The sorting and grouping detail provided through the Find statement's appropriate clause</param>
/// <param name="paths">The paths to search</param>
/// <returns>The matching DiskItems</returns>
public IEnumerable<DiskItem> GetFilteredDiskItemsByIn(string whereDetail, string sortGroupDetail, IEnumerable<string> paths)
{
return GetFilteredDiskItems(whereDetail, sortGroupDetail, paths, $"depth = ([current] + 1)");
}
/// <summary>
/// Retrieves all records located at any depth inside of any of the provided paths, matching the given filter with the provided whereDetail
/// </summary>
/// <param name="whereDetail">The filtering detail provided through the Find statement's where clause</param>
/// <param name="sortGroupDetail">The sorting and grouping detail provided through the Find statement's appropriate clause</param>
/// <param name="paths">The paths to search</param>
/// <returns>The matching DiskItems</returns>
public IEnumerable<DiskItem> GetFilteredDiskItemsByWithin(string whereDetail, string sortGroupDetail, IEnumerable<string> paths)
{
return GetFilteredDiskItems(whereDetail, sortGroupDetail, paths, $"depth > [current]");
}
/// <summary>
/// Retrieves all records located within any subdirectories immediately inside of any of the provided paths, matching the given filter with the provided whereDetail
/// </summary>
/// <param name="whereDetail">The filtering detail provided through the Find statement's where clause</param>
/// <param name="sortGroupDetail">The sorting and grouping detail provided through the Find statement's appropriate clause</param>
/// <param name="paths">The paths to search</param>
/// <returns>The matching DiskItems</returns>
public IEnumerable<DiskItem> GetFilteredDiskItemsByUnder(string whereDetail, string sortGroupDetail, IEnumerable<string> paths)
{
return GetFilteredDiskItems(whereDetail, sortGroupDetail, paths, $"depth > ([current] + 1)");
}
/// <summary>
/// Attempts to retrieve and return a DiskItem by it's path
/// </summary>
/// <param name="paths">The paths to search for</param>
/// <returns>The DiskItem if found, null otherwise</returns>
public DiskItem GetDiskItemByPath(string path)
{
DiskItem result = null;
var reader = ExecuteReader($"select * from diskitems where path = '{DataHelper.Sanitize(path)}';");
if (reader.HasRows && reader.Read())
{
result = new DiskItem(reader);
}
return result;
}
/// <summary>
/// Retrieves and returns all disk items with paths that perfectly match an item in the given list
/// </summary>
/// <param name="paths">The paths to search for</param>
/// <returns></returns>
public IEnumerable<DiskItem> GetDiskItemsByPaths(IEnumerable<string> paths)
{
List<DiskItem> results = new List<DiskItem>();
var reader = ExecuteReader($"select * from diskitems where path in {DataHelper.GetListing(paths, true)};");
if (reader.HasRows)
{
while (reader.Read())
{
results.Add(new DiskItem(reader));
}
}
return results;
}
/// <summary>
/// Deletes all records located within one of the given paths with a LastScanned value prior to the timestamp
/// </summary>
/// <param name="timestamp">The cut off point for records' "old" status</param>
/// <param name="paths">The disk paths where old files must reside</param>
/// <returns>The number of records deleted</returns>
public long DeleteOldDiskItems(DateTime timestamp, IEnumerable<string> paths)
{
var where = $"where {DataHelper.GetListing(paths, true, " or ", "path like '", "%'")} and lastscanned < '{DateTimeDataHelper.ConvertToString(timestamp)}';";
var count = GetCount($"diskitems {where}");
ExecuteNonQuery($"delete from diskitems {where}");
return count;
}
/// <summary>
/// Queues the records for transactionary insertion
/// </summary>
/// <param name="items">The records to be added</param>
/// <returns></returns>
public void Insert(params DiskItem[] items)
{
foreach (var item in items)
{
_diskItems.Inserts.Add(item);
}
}
/// <summary>
/// Queues the records for the transactionary update
/// </summary>
/// <param name="items">The records to be updated</param>
public void Update(params DiskItem[] items)
{
foreach (var item in items)
{
_diskItems.Updates.Add(item);
}
}
/// <summary>
/// Queues the records for the transactionary deletion
/// </summary>
/// <param name="items"></param>
public void Delete(params DiskItem[] items)
{
foreach (var item in items)
{
_diskItems.Deletions.Add(item);
}
}
/// <summary>
/// Performs a transactionary database execution of all pending inserts, updates, and deletes
/// </summary>
/// <returns>A tuple in the format total [inserts, updates, deletes]</returns>
public Tuple<long, long, long> WriteDiskItems()
{
long inserts = 0, updates = 0, deletes = 0;
if (_diskItems.HasWork)
{
using (var transaction = EnsureConnection().BeginTransaction())
{
if (_diskItems.Inserts.Count > 0)
{
foreach (var insert in _diskItems.Inserts)
{
ExecuteNonQuery(insert.ToInsertStatement());
inserts++;
}
_diskItems.Inserts.Clear();
}
if (_diskItems.Updates.Count > 0)
{
foreach (var update in _diskItems.Updates)
{
ExecuteNonQuery(update.ToUpdateStatement());
updates++;
}
_diskItems.Updates.Clear();
}
if (_diskItems.Deletions.Count > 0)
{
var sql = $"({ string.Join(", ", from delete in _diskItems.Deletions select $"'{delete.Id}'") })";
deletes = GetCount($"diskitems where id in {sql};");
ExecuteNonQuery($"DELETE from diskitems where id in {sql};");
_diskItems.Deletions.Clear();
}
transaction.Commit();
}
}
return new Tuple<long, long, long>(inserts, updates, deletes);
}
#endregion
public void Dispose()
{
if (_connection != null)
{
if (_connection.State != ConnectionState.Closed)
{
_connection.Close();
}
_connection.Dispose();
_connection = null;
}
}
}
}
| 36.426979 | 172 | 0.49293 | [
"MIT"
] | zainta/Harddrive-Library | Harddrive-Library/Data/DataHandler.cs | 65,352 | C# |
namespace Workflow;
internal class WorkflowException<TContext> : Exception where TContext : WorkflowBaseContext
{
public WorkflowException(Exception exception, TContext context, IWorkflowStep<TContext> step)
: base($"Step: {step.GetType().Name}, Context - {context.PropertiesToString<TContext>()}", exception)
{
}
} | 37.555556 | 109 | 0.736686 | [
"MIT"
] | byCrookie/Workflow | src/Workflow/WorkflowException.cs | 340 | C# |
namespace Sistema_cantina
{
partial class Form1
{
/// <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.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.txtCodigo = new System.Windows.Forms.TextBox();
this.picImagem = new System.Windows.Forms.PictureBox();
this.lstCaixa = new System.Windows.Forms.ListBox();
((System.ComponentModel.ISupportInitialize)(this.picImagem)).BeginInit();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(124, 19);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(104, 13);
this.label1.TabIndex = 0;
this.label1.Text = "SISTEMA CANTINA";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 78);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(125, 13);
this.label2.TabIndex = 1;
this.label2.Text = "CÓDIGO DO PRODUTO";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(12, 273);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(84, 13);
this.label3.TabIndex = 2;
this.label3.Text = "VALOR TOTAL:";
//
// txtCodigo
//
this.txtCodigo.Location = new System.Drawing.Point(15, 108);
this.txtCodigo.Name = "txtCodigo";
this.txtCodigo.Size = new System.Drawing.Size(144, 20);
this.txtCodigo.TabIndex = 3;
this.txtCodigo.TextChanged += new System.EventHandler(this.txtCodigo_TextChanged);
//
// picImagem
//
this.picImagem.Location = new System.Drawing.Point(15, 150);
this.picImagem.Name = "picImagem";
this.picImagem.Size = new System.Drawing.Size(144, 107);
this.picImagem.TabIndex = 4;
this.picImagem.TabStop = false;
//
// lstCaixa
//
this.lstCaixa.FormattingEnabled = true;
this.lstCaixa.Location = new System.Drawing.Point(198, 108);
this.lstCaixa.Name = "lstCaixa";
this.lstCaixa.Size = new System.Drawing.Size(120, 147);
this.lstCaixa.TabIndex = 5;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(335, 321);
this.Controls.Add(this.lstCaixa);
this.Controls.Add(this.picImagem);
this.Controls.Add(this.txtCodigo);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.picImagem)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtCodigo;
private System.Windows.Forms.PictureBox picImagem;
private System.Windows.Forms.ListBox lstCaixa;
}
}
| 39.098361 | 124 | 0.557862 | [
"MIT"
] | FireWallSP/SistemaCantina | Sistema_cantina/Form1.Designer.cs | 4,785 | C# |
using System.Collections;
using System.Collections.Generic;
using ReGoap.Unity;
using UnityEngine;
public class HappyAnimalGoal : ReGoapGoalAdvanced<string, object>
{
protected override void Awake()
{
base.Awake();
goal.Set("foodEaten", true);
}
}
| 19.857143 | 65 | 0.697842 | [
"MIT"
] | uug-trento/goap-unity | Assets/Scripts/HappyAnimalGoal.cs | 280 | C# |
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OrmTest
{
public partial class NewUnitTest
{
public static SqlSugarClient Db=> new SqlSugarClient(new ConnectionConfig()
{
DbType = DbType.SqlServer,
ConnectionString = Config.ConnectionString,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true,
AopEvents = new AopEvents
{
OnLogExecuting = (sql, p) =>
{
Console.WriteLine(sql);
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
}
}
});
public static void RestData()
{
Db.DbMaintenance.TruncateTable<Order>();
Db.DbMaintenance.TruncateTable<OrderItem>();
}
public static void Init()
{
UCustom01.Init();
UCustom02.Init();
UCustom03.Init();
UCustom04.Init();
UCustom05.Init();
UCustom06.Init();
SubQueryTest();
UConfig();
DeleteTest();
Fastest2();
SplitTest();
Filter();
Insert();
Insert2();
Enum();
Tran();
Queue();
CodeFirst();
Updateable();
Json();
Ado();
Queryable();
Queryable2();
QueryableAsync();
AopTest();
//Thread();
//Thread2();
//Thread3();
}
}
}
| 26.030769 | 108 | 0.459811 | [
"Apache-2.0"
] | chenketian/SqlSugar | Src/Asp.Net/SqlServerTest/UnitTest/Main.cs | 1,694 | 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.ServerlessApplicationRepository")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWSServerlessApplicationRepository. First release of the AWS Serverless Application Repository SDK.")]
[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.101.3")] | 46.09375 | 179 | 0.75661 | [
"Apache-2.0"
] | damianh/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/ServerlessApplicationRepository/Properties/AssemblyInfo.cs | 1,475 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
#pragma warning disable CS8618
[JsiiByValue(fqn: "aws.Wafv2WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatement")]
public class Wafv2WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatement : aws.IWafv2WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatement
{
/// <summary>statement block.</summary>
[JsiiProperty(name: "statement", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatementStatement\"},\"kind\":\"array\"}}", isOverride: true)]
public aws.IWafv2WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatementStatement[] Statement
{
get;
set;
}
}
}
| 45.857143 | 246 | 0.778816 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/Wafv2WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatement.cs | 963 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameScore : MonoBehaviour {
Text scoreUIText;
int score;
public int Score
{
get
{
return this.score;
}
set
{
score = value;
UpdateScoreTextUI();
}
}
// Use this for initialization
void Start () {
//Get the Text UI commponent of this gameObject
scoreUIText = GetComponent<Text>();
}
//Function to update the score text UI
void UpdateScoreTextUI()
{
string scoreStr = string.Format("{0:000000000}", Score);
scoreUIText.text = scoreStr;
}
}
| 18.410256 | 64 | 0.579387 | [
"MIT"
] | boonitis/gamejam2018-kalawar | Doraemon/Assets/Scripts/GameScore.cs | 720 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the nimble-2020-08-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.NimbleStudio.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.NimbleStudio.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for GetLaunchProfile operation
/// </summary>
public class GetLaunchProfileResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
GetLaunchProfileResponse response = new GetLaunchProfileResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("launchProfile", targetDepth))
{
var unmarshaller = LaunchProfileUnmarshaller.Instance;
response.LaunchProfile = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException"))
{
return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ConflictException"))
{
return ConflictExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerErrorException"))
{
return InternalServerErrorExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException"))
{
return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceQuotaExceededException"))
{
return ServiceQuotaExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottlingException"))
{
return ThrottlingExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException"))
{
return ValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonNimbleStudioException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static GetLaunchProfileResponseUnmarshaller _instance = new GetLaunchProfileResponseUnmarshaller();
internal static GetLaunchProfileResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static GetLaunchProfileResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.492537 | 195 | 0.639209 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/NimbleStudio/Generated/Model/Internal/MarshallTransformations/GetLaunchProfileResponseUnmarshaller.cs | 5,560 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Prosperity.Droid")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Prosperity.Droid")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[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("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
| 36.542857 | 84 | 0.756059 | [
"MIT"
] | alberteije/Prosperity | Prosperity/Prosperity.Droid/Properties/AssemblyInfo.cs | 1,282 | C# |
using System;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Windows.Input;
using Xamarin.Forms;
namespace Prism.Behaviors
{
/// <summary>
/// Behavior class that enable using <see cref="ICommand" /> to react on events raised by <see cref="BindableObject" /> bindable.
/// </summary>
/// <para>
/// There are multiple ways to pass a parameter to the <see cref="ICommand.Execute"/> method.
/// Setting the <see cref="CommandParameter"/> will always result in that value will be sent.
/// The <see cref="EventArgsParameterPath"/> will walk the property path on the instance of <see cref="EventArgs"/> for the event and, if any property found, pass that parameter.
/// The <see cref="EventArgsConverter"/> will call the <see cref="IValueConverter.Convert"/> method with the <see cref="EventArgsConverterParameter"/> and pass the result as parameter.
/// </para>
/// <para>
/// The order of evaluation for the parameter to be sent to the <see cref="ICommand.Execute"/> method is
/// 1. <see cref="CommandParameter"/>
/// 2. <see cref="EventArgsParameterPath"/>
/// 3. <see cref="EventArgsConverter"/>
/// and as soon as a non-<c>null</c> value is found, the evaluation is stopped.
/// </para>
/// <example>
/// <ListView>
/// <ListView.Behaviors>
/// <behaviors:EventToCommandBehavior EventName="ItemTapped" Command={Binding ItemTappedCommand} />
/// </ListView.Behaviors>
/// </ListView>
/// </example>
// This is a modified version of https://anthonysimmon.com/eventtocommand-in-xamarin-forms-apps/
public class EventToCommandBehavior : BehaviorBase<BindableObject>
{
/// <summary>
/// Bindable property for Name of the event that will be forwarded to
/// <see cref="EventToCommandBehavior.Command"/>
/// </summary>
public static readonly BindableProperty EventNameProperty =
BindableProperty.Create(nameof(EventName), typeof(string), typeof(EventToCommandBehavior));
/// <summary>
/// Bindable property for Command to execute
/// </summary>
public static readonly BindableProperty CommandProperty =
BindableProperty.Create(nameof(Command), typeof(ICommand), typeof(EventToCommandBehavior));
/// <summary>
/// Bindable property for Argument sent to <see cref="ICommand.Execute(object)"/>
/// </summary>
public static readonly BindableProperty CommandParameterProperty =
BindableProperty.Create(nameof(CommandParameter), typeof(object), typeof(EventToCommandBehavior));
/// <summary>
/// Bindable property to set instance of <see cref="IValueConverter" /> to convert the <see cref="EventArgs" /> for <see cref="EventName" />
/// </summary>
public static readonly BindableProperty EventArgsConverterProperty =
BindableProperty.Create(nameof(EventArgsConverter), typeof(IValueConverter), typeof(EventToCommandBehavior));
/// <summary>
/// Bindable property to set Argument passed as parameter to <see cref="IValueConverter.Convert" />
/// </summary>
public static readonly BindableProperty EventArgsConverterParameterProperty =
BindableProperty.Create(nameof(EventArgsConverterParameter), typeof(object), typeof(EventToCommandBehavior));
/// <summary>
/// Bindable property to set Parameter path to extract property from <see cref="EventArgs"/> instance to pass to <see cref="ICommand.Execute"/>
/// </summary>
public static readonly BindableProperty EventArgsParameterPathProperty =
BindableProperty.Create(
nameof(EventArgsParameterPath),
typeof(string),
typeof(EventToCommandBehavior));
/// <summary>
/// <see cref="EventInfo"/>
/// </summary>
protected EventInfo _eventInfo;
/// <summary>
/// Delegate to Invoke when event is raised
/// </summary>
protected Delegate _handler;
/// <summary>
/// Parameter path to extract property from <see cref="EventArgs"/> instance to pass to <see cref="ICommand.Execute"/>
/// </summary>
public string EventArgsParameterPath
{
get { return (string)GetValue(EventArgsParameterPathProperty); }
set { SetValue(EventArgsParameterPathProperty, value); }
}
/// <summary>
/// Name of the event that will be forwared to <see cref="Command" />
/// </summary>
/// <remarks>
/// An event that is invalid for the attached <see cref="View" /> will result in <see cref="ArgumentException" /> thrown.
/// </remarks>
public string EventName
{
get { return (string)GetValue(EventNameProperty); }
set { SetValue(EventNameProperty, value); }
}
/// <summary>
/// The command to execute
/// </summary>
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
/// <summary>
/// Argument sent to <see cref="ICommand.Execute" />
/// </summary>
/// <para>
/// If <see cref="EventArgsConverter" /> and <see cref="EventArgsConverterParameter" /> is set then the result of the
/// conversion
/// will be sent.
/// </para>
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
/// <summary>
/// Instance of <see cref="IValueConverter" /> to convert the <see cref="EventArgs" /> for <see cref="EventName" />
/// </summary>
public IValueConverter EventArgsConverter
{
get { return (IValueConverter)GetValue(EventArgsConverterProperty); }
set { SetValue(EventArgsConverterProperty, value); }
}
/// <summary>
/// Argument passed as parameter to <see cref="IValueConverter.Convert" />
/// </summary>
public object EventArgsConverterParameter
{
get { return GetValue(EventArgsConverterParameterProperty); }
set { SetValue(EventArgsConverterParameterProperty, value); }
}
/// <summary>
/// Subscribes to the event <see cref="BindableObject"/> object
/// </summary>
/// <param name="bindable">Bindable object that is source of event to Attach</param>
/// <exception cref="ArgumentException">Thrown if no matching event exists on
/// <see cref="BindableObject"/></exception>
protected override void OnAttachedTo(BindableObject bindable)
{
base.OnAttachedTo(bindable);
_eventInfo = AssociatedObject
.GetType()
.GetRuntimeEvent(EventName);
if (_eventInfo == null)
{
throw new ArgumentException(
$"No matching event '{EventName}' on attached type '{bindable.GetType().Name}'");
}
AddEventHandler(_eventInfo, AssociatedObject, OnEventRaised);
}
/// <summary>
/// Unsubscribes from the event on <paramref name="bindable"/>
/// </summary>
/// <param name="bindable"><see cref="BindableObject"/> that is source of event</param>
protected override void OnDetachingFrom(BindableObject bindable)
{
if (_handler != null)
{
_eventInfo.RemoveEventHandler(AssociatedObject, _handler);
}
_handler = null;
_eventInfo = null;
base.OnDetachingFrom(bindable);
}
private void AddEventHandler(EventInfo eventInfo, object item, Action<object, EventArgs> action)
{
var eventParameters = eventInfo.EventHandlerType
.GetRuntimeMethods().First(m => m.Name == "Invoke")
.GetParameters()
.Select(p => Expression.Parameter(p.ParameterType))
.ToArray();
var actionInvoke = action.GetType()
.GetRuntimeMethods().First(m => m.Name == "Invoke");
_handler = Expression.Lambda(
eventInfo.EventHandlerType,
Expression.Call(Expression.Constant(action), actionInvoke, eventParameters[0], eventParameters[1]),
eventParameters)
.Compile();
eventInfo.AddEventHandler(item, _handler);
}
/// <summary>
/// Method called when event is raised
/// </summary>
/// <param name="sender">Source of that raised the event</param>
/// <param name="eventArgs">Arguments of the raised event</param>
protected virtual void OnEventRaised(object sender, EventArgs eventArgs)
{
if (Command == null)
{
return;
}
var parameter = CommandParameter;
if (parameter == null && !string.IsNullOrEmpty(EventArgsParameterPath))
{
//Walk the ParameterPath for nested properties.
var propertyPathParts = EventArgsParameterPath.Split('.');
object propertyValue = eventArgs;
foreach (var propertyPathPart in propertyPathParts)
{
var propInfo = propertyValue.GetType().GetRuntimeProperty(propertyPathPart);
if (propInfo == null)
throw new MissingMemberException($"Unable to find {EventArgsParameterPath}");
propertyValue = propInfo.GetValue(propertyValue);
if (propertyValue == null)
{
break;
}
}
parameter = propertyValue;
}
if (parameter == null && eventArgs != null && eventArgs != EventArgs.Empty && EventArgsConverter != null)
{
parameter = EventArgsConverter.Convert(eventArgs, typeof(object), EventArgsConverterParameter,
CultureInfo.CurrentUICulture);
}
if (Command.CanExecute(parameter))
{
Command.Execute(parameter);
}
}
}
} | 41.920635 | 188 | 0.59769 | [
"MIT"
] | Algorithman/Prism | src/Forms/Prism.Forms/Behaviors/EventToCommandBehavior.cs | 10,566 | C# |
/*
* ProWritingAid API V2
*
* Official ProWritingAid API Version 2
*
* OpenAPI spec version: v2
* Contact: hello@prowritingaid.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Reflection;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
namespace ProWritingAid.SDK.Client
{
/// <summary>
/// <see cref="GlobalConfiguration"/> provides a compile-time extension point for globally configuring
/// API Clients.
/// </summary>
/// <remarks>
/// A customized implementation via partial class may reside in another file and may
/// be excluded from automatic generation via a .swagger-codegen-ignore file.
/// </remarks>
public partial class GlobalConfiguration : Configuration
{
}
} | 25 | 106 | 0.710588 | [
"Apache-2.0"
] | prowriting/prowritingaid.csharp | ProWritingAid.SDK/Client/GlobalConfiguration.cs | 850 | C# |
namespace SE347.L11_HelloWork.Authentication.External
{
public class ExternalAuthUserInfo
{
public string ProviderKey { get; set; }
public string Name { get; set; }
public string EmailAddress { get; set; }
public string Surname { get; set; }
public string Provider { get; set; }
}
}
| 21.25 | 54 | 0.623529 | [
"MIT"
] | NgocSon288/HelloWork | aspnet-core/src/SE347.L11_HelloWork.Web.Core/Authentication/External/ExternalAuthUserInfo.cs | 342 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. 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.
* 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 TencentCloud.Vod.V20180717.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeAdaptiveDynamicStreamingTemplatesRequest : AbstractModel
{
/// <summary>
/// Unique ID filter of transcoding to adaptive bitrate streaming templates. Array length limit: 100.
/// </summary>
[JsonProperty("Definitions")]
public ulong?[] Definitions{ get; set; }
/// <summary>
/// Paged offset. Default value: 0.
/// </summary>
[JsonProperty("Offset")]
public ulong? Offset{ get; set; }
/// <summary>
/// Number of returned entries. Default value: 10. Maximum value: 100.
/// </summary>
[JsonProperty("Limit")]
public ulong? Limit{ get; set; }
/// <summary>
/// Template type filter. Valid values:
/// <li>Preset: preset template;</li>
/// <li>Custom: custom template.</li>
/// </summary>
[JsonProperty("Type")]
public string Type{ get; set; }
/// <summary>
/// ID of a [subapplication](https://intl.cloud.tencent.com/document/product/266/14574?from_cn_redirect=1) in VOD. If you need to access a resource in a subapplication, enter the subapplication ID in this field; otherwise, leave it empty.
/// </summary>
[JsonProperty("SubAppId")]
public ulong? SubAppId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamArraySimple(map, prefix + "Definitions.", this.Definitions);
this.SetParamSimple(map, prefix + "Offset", this.Offset);
this.SetParamSimple(map, prefix + "Limit", this.Limit);
this.SetParamSimple(map, prefix + "Type", this.Type);
this.SetParamSimple(map, prefix + "SubAppId", this.SubAppId);
}
}
}
| 36.445946 | 246 | 0.628105 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet-intl-en | TencentCloud/Vod/V20180717/Models/DescribeAdaptiveDynamicStreamingTemplatesRequest.cs | 2,697 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _02.Guitar
{
class Program
{
static void Main(string[] args)
{
int[] nums = Console.ReadLine()
.Split(new string[] { ", " }, StringSplitOptions.None)
.Select(int.Parse)
.ToArray();
int start = int.Parse(Console.ReadLine());
int max = int.Parse(Console.ReadLine());
bool[,] matrix = new bool[nums.Length + 1, max + 1];
matrix[0, start] = true;
for (int row = 0; row < matrix.GetLength(0) - 1; row++)
{
for (int col = 0; col < matrix.GetLength(1); col++)
{
if (matrix[row, col] == true)
{
int value = nums[row];
if (col - value >= 0)
{
matrix[row + 1, col - value] = true;
}
if (col + value <= max)
{
matrix[row + 1, col + value] = true;
}
}
}
}
int biggestVolume = matrix.GetLength(1) - 1;
while (biggestVolume >= 0)
{
if (matrix[matrix.GetLength(0) - 1, biggestVolume] == true)
{
break;
}
biggestVolume--;
}
Console.WriteLine(biggestVolume);
}
}
}
| 30.811321 | 75 | 0.393754 | [
"MIT"
] | KristiyanSevov/Algorithms | Exercises/12. PracticalProblems 2 (Lab)/02. Guitar/Program.cs | 1,635 | C# |
using System.Threading.Tasks;
using GoNorth.Data.FlexFieldDatabase;
using GoNorth.Data.Styr;
using GoNorth.Services.Export.Data;
using GoNorth.Services.Export.Dialog.ActionRendering.ConfigObject;
using GoNorth.Services.Export.Placeholder;
using GoNorth.Services.Export.Placeholder.ScribanRenderingEngine.LanguageKeyGenerator;
using Microsoft.Extensions.Localization;
namespace GoNorth.Services.Export.Dialog.ActionRendering.ScribanRenderingEngine
{
/// <summary>
/// Class for rendering a spawn item action with scriban
/// </summary>
public class ScribanSpawnItemActionRenderer : ScribanSpawnObjectAtMarkerActionRenderer
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="cachedDbAccess">Cached Db Access</param>
/// <param name="scribanLanguageKeyGenerator">Scriban Language Key Generator</param>
/// <param name="localizerFactory">String localizer factor</param>
public ScribanSpawnItemActionRenderer(IExportCachedDbAccess cachedDbAccess, IScribanLanguageKeyGenerator scribanLanguageKeyGenerator, IStringLocalizerFactory localizerFactory) :
base(cachedDbAccess, scribanLanguageKeyGenerator, localizerFactory)
{
}
/// <summary>
/// Returns the value object to use
/// </summary>
/// <param name="parsedData">Parsed data</param>
/// <param name="flexFieldObject">Flex field object</param>
/// <param name="errorCollection">Error Collection</param>
/// <returns>Value Object</returns>
protected override async Task<IFlexFieldExportable> GetValueObject(SpawnObjectActionData parsedData, FlexFieldObject flexFieldObject, ExportPlaceholderErrorCollection errorCollection)
{
StyrItem foundItem = await _cachedDbAccess.GetItemById(parsedData.ObjectId);
if(foundItem == null)
{
errorCollection.AddDialogItemNotFoundError();
return null;
}
return foundItem;
}
}
} | 44.479167 | 192 | 0.676815 | [
"MIT"
] | Dyescape/GoNorth | Services/Export/Dialog/ActionRendering/ScribanRenderingEngine/ScribanSpawnItemActionRenderer.cs | 2,135 | C# |
using System;
using System.Collections.Generic;
namespace FakerUnitTest.Test
{
public class NullableFieldsClassNoConstructor
{
public DateTime dateTimeField;
public List<byte> listField;
public object objectField;
}
}
| 19.692308 | 49 | 0.710938 | [
"MIT"
] | RedDiamond69/Faker | FakerUnitTest/Test/NullableFieldsClassNoConstructor.cs | 258 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using FluentDbTools.Common.Abstractions;
using Example.FluentDbTools.Database;
using Example.FluentDbTools.Migration;
namespace TestUtilities.FluentDbTools
{
public static class TestServiceProvider
{
public static IServiceProvider GetDatabaseExampleServiceProvider(
SupportedDatabaseTypes databaseType = SupportedDatabaseTypes.Postgres,
Dictionary<string, string> additionalOverrideConfig = null)
{
var overrideConfig = OverrideConfig.GetInMemoryOverrideConfig(databaseType);
additionalOverrideConfig?.ToList().ForEach(x => overrideConfig[x.Key] = x.Value);
return DbExampleBuilder.BuildDbExample(databaseType, overrideConfig);
}
public static IServiceProvider GetMigrationExampleServiceProvider(
SupportedDatabaseTypes databaseType = SupportedDatabaseTypes.Postgres,
Dictionary<string, string> additionalOverrideConfig = null)
{
var overrideConfig = OverrideConfig.GetInMemoryOverrideConfig(databaseType);
additionalOverrideConfig?.ToList().ForEach(x => overrideConfig[x.Key] = x.Value);
return MigrationBuilder.BuildMigration(databaseType, overrideConfig);
}
}
} | 44.066667 | 93 | 0.729198 | [
"MIT"
] | DIPSAS/FluentDbTools | src/FluentDbTools/Tests/TestUtilities.FluentDbTools/TestServiceProvider.cs | 1,324 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using DotnetSpider.Core;
using DotnetSpider.Data;
using DotnetSpider.Data.Storage;
using DotnetSpider.Downloader;
using DotnetSpider.Downloader.Entity;
using DotnetSpider.MessageQueue;
using DotnetSpider.RequestSupply;
using DotnetSpider.Scheduler;
using DotnetSpider.Statistics;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
[assembly: InternalsVisibleTo("DotnetSpider.Tests")]
[assembly: InternalsVisibleTo("DotnetSpider.Sample")]
namespace DotnetSpider
{
/// <summary>
/// Depth 是独立的系统,只有真的是解析出来的新请求才会导致 Depth 加 1, Depth 一般不能作为 Request 的 Hash 计算,因为不同深度会有相同的链接
/// 下载和解析导致的重试都不需要更改 Depth, 直接调用下载分发服务,跳过 Scheduler
/// </summary>
public partial class Spider
{
private readonly IServiceProvider _services;
private readonly ISpiderOptions _options;
/// <summary>
/// 结束前的处理工作
/// </summary>
/// <returns></returns>
protected virtual Task OnExiting()
{
#if NETFRAMEWORK
return Framework.CompletedTask;
#else
return Task.CompletedTask;
#endif
}
/// <summary>
/// 构造方法
/// </summary>
/// <param name="mq"></param>
/// <param name="options"></param>
/// <param name="logger"></param>
/// <param name="services">服务提供接口</param>
/// <param name="statisticsService"></param>
public Spider(
IMessageQueue mq,
IStatisticsService statisticsService,
ISpiderOptions options,
ILogger<Spider> logger,
IServiceProvider services)
{
_services = services;
_statisticsService = statisticsService;
_mq = mq;
_options = options;
_logger = logger;
Console.CancelKeyPress += ConsoleCancelKeyPress;
}
/// <summary>
/// 创建爬虫对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T Create<T>() where T : Spider
{
var builder = new SpiderBuilder();
builder.AddSerilog();
builder.ConfigureAppConfiguration();
builder.UseStandalone();
builder.AddSpider<T>();
var factory = builder.Build();
return factory.Create<T>();
}
/// <summary>
/// 设置 Id 为 Guid
/// </summary>
public Spider NewGuidId()
{
CheckIfRunning();
Id = Guid.NewGuid().ToString("N");
return this;
}
/// <summary>
/// 添加请求的配置方法
/// 可以计算 Cookie, Sign 等操作
/// </summary>
/// <param name="configureDelegate">配置方法</param>
/// <returns></returns>
public Spider AddConfigureRequestDelegate(Action<Request> configureDelegate)
{
Check.NotNull(configureDelegate, nameof(configureDelegate));
_configureRequestDelegates.Add(configureDelegate);
return this;
}
/// <summary>
/// 添加数据流处理器 Add data stream processor
/// </summary>
/// <param name="dataFlow">数据流处理器</param>
/// <returns></returns>
public Spider AddDataFlow(IDataFlow dataFlow)
{
Check.NotNull(dataFlow, nameof(dataFlow));
CheckIfRunning();
dataFlow.Logger = _services.GetRequiredService<ILoggerFactory>().CreateLogger(dataFlow.GetType());
_dataFlows.Add(dataFlow);
return this;
}
/// <summary>
/// 添加请求供应器 Add request provider
/// </summary>
/// <param name="supply">请求供应器</param>
/// <returns></returns>
public Spider AddRequestSupply(IRequestSupply supply)
{
Check.NotNull(supply, nameof(supply));
CheckIfRunning();
_requestSupplies.Add(supply);
return this;
}
/// <summary>
/// 添加请求 Add request
/// </summary>
/// <param name="requests">请求 request</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.Synchronized)]
public Spider AddRequests(params Request[] requests)
{
Check.NotNull(requests, nameof(requests));
foreach (var request in requests)
{
request.OwnerId = Id;
request.Depth = request.Depth == 0 ? 1 : request.Depth;
_requests.Add(request);
if (_requests.Count % EnqueueBatchCount == 0)
{
EnqueueRequests();
}
}
return this;
}
/// <summary>
/// 添加链接
/// </summary>
/// <param name="urls">链接</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.Synchronized)]
public Spider AddRequests(params string[] urls)
{
Check.NotNull(urls, nameof(urls));
foreach (var url in urls)
{
var request = new Request {Url = url, OwnerId = Id, Depth = 1, Method = HttpMethod.Get};
_requests.Add(request);
if (_requests.Count % EnqueueBatchCount == 0)
{
EnqueueRequests();
}
}
return this;
}
/// <summary>
/// 启动爬虫
/// </summary>
/// <param name="args">启动参数</param>
/// <returns></returns>
public Task RunAsync(params string[] args)
{
CheckIfRunning();
// 此方法不能放到异步里, 如果在调用 RunAsync 后再直接调用 ExitBySignal 有可能会因会执行顺序原因导致先调用退出,然后退出信号被重置
ResetMmfSignal();
return Task.Factory.StartNew(async () =>
{
try
{
_logger.LogInformation("初始化爬虫");
// 初始化设置
Initialize();
// 设置默认调度器
_scheduler = _scheduler ?? new QueueDistinctBfsScheduler();
// 设置状态为: 运行
Status = Status.Running;
// 添加任务启动的监控信息
await _statisticsService.StartAsync(Id);
// 订阅数据流,如果订阅失败
_mq.Subscribe($"{Framework.ResponseHandlerTopic}{Id}",
async message => await HandleMessage(message));
_logger.LogInformation($"任务 {Id} 订阅消息队列成功");
// 如果设置了要分配 10 个下载器,当收到 10 个下载器已经分配好时,认为分配完成
_allocated.Set(0);
// 如果有任何一个下载器代理分配失败,收到消息后直接把此值赋为 false,爬虫退出
_allocatedSuccess = true;
// 先分配下载器,因为分配下载器的开销、时间更小,后面 RequestSupply 可能加载大量的请求,时间开销很大
await AllotDownloaderAsync();
// 等待 30 秒如果没有完成分配,超时结束
for (var i = 0; i < 200; ++i)
{
if (!_allocatedSuccess)
{
_logger.LogInformation($"任务 {Id} 分配下载器代理失败");
return;
}
if (_allocated.Value == DownloaderSettings.DownloaderCount)
{
_logger.LogInformation($"任务 {Id} 分配下载器代理成功");
break;
}
Thread.Sleep(150);
}
if (_allocated.Value == 0)
{
_logger.LogInformation($"任务 {Id} 分配下载器代理失败");
return;
}
// 通过供应接口添加请求
foreach (var requestSupply in _requestSupplies)
{
requestSupply.Run(request => AddRequests(request));
}
// 把列表中可能剩余的请求加入队列
EnqueueRequests();
_logger.LogInformation($"任务 {Id} 加载下载请求结束");
// 初始化各数据流处理器
foreach (var dataFlow in _dataFlows)
{
await dataFlow.InitAsync();
}
_logger.LogInformation($"任务 {Id} 数据流处理器初始化完成");
_enqueued.Set(0);
_responded.Set(0);
_enqueuedRequestDict.Clear();
// 启动速度控制器
StartSpeedControllerAsync().ConfigureAwait(false).GetAwaiter();
_lastRequestedTime = DateTime.Now;
// 等待退出信号
await WaitForExiting();
}
catch (Exception e)
{
_logger.LogError(e.ToString());
}
finally
{
foreach (var dataFlow in _dataFlows)
{
try
{
dataFlow.Dispose();
}
catch (Exception ex)
{
_logger.LogError($"任务 {Id} 释放 {dataFlow.GetType().Name} 失败: {ex}");
}
}
try
{
// TODO: 如果订阅消息队列失败,此处是否应该再尝试上报,会导致两倍的重试时间
// 添加任务退出的监控信息
await _statisticsService.ExitAsync(Id);
// 最后打印一次任务状态信息
await _statisticsService.PrintStatisticsAsync(Id);
}
catch (Exception e)
{
_logger.LogInformation($"任务 {Id} 上传退出信息失败: {e}");
}
try
{
await OnExiting();
}
catch (Exception e)
{
_logger.LogInformation($"任务 {Id} 退出事件处理失败: {e}");
}
// 标识任务退出完成
Status = Status.Exited;
_logger.LogInformation($"任务 {Id} 退出");
}
});
}
/// <summary>
/// 暂停爬虫
/// </summary>
public void Pause()
{
Status = Status.Paused;
}
/// <summary>
/// 继续爬虫
/// </summary>
public void Continue()
{
Status = Status.Running;
}
/// <summary>
/// 退出爬虫
/// </summary>
public Spider Exit()
{
_logger.LogInformation($"任务 {Id} 退出中...");
Status = Status.Exiting;
// 直接取消订阅即可: 1. 如果是本地应用,
_mq.Unsubscribe($"{Framework.ResponseHandlerTopic}{Id}");
return this;
}
/// <summary>
/// 发送退出信号
/// </summary>
public Spider ExitBySignal()
{
if (MmfSignal)
{
var mmf = MemoryMappedFile.CreateFromFile(Path.Combine("mmf-signal", Id), FileMode.OpenOrCreate, null,
4,
MemoryMappedFileAccess.ReadWrite);
using (var accessor = mmf.CreateViewAccessor())
{
accessor.Write(0, true);
accessor.Flush();
}
_logger.LogInformation($"任务 {Id} 推送退出信号到 MMF 成功");
return this;
}
throw new SpiderException($"任务 {Id} 未开启 MMF 控制");
}
public void Run(params string[] args)
{
RunAsync(args).Wait();
}
/// <summary>
/// 等待任务结束
/// </summary>
public void WaitForExit(long milliseconds = 0)
{
milliseconds = milliseconds <= 0 ? long.MaxValue : milliseconds;
var waited = 0;
while (Status != Status.Exited && waited < milliseconds)
{
Thread.Sleep(100);
waited += 100;
}
}
/// <summary>
/// 初始化配置
/// </summary>
protected virtual void Initialize()
{
}
/// <summary>
/// 从配置文件中获取数据存储器
/// </summary>
/// <returns></returns>
/// <exception cref="SpiderException"></exception>
public StorageBase GetDefaultStorage()
{
return GetDefaultStorage(_options);
}
internal static StorageBase GetDefaultStorage(ISpiderOptions options)
{
var type = Type.GetType(options.Storage);
if (type == null)
{
throw new SpiderException("存储器类型配置不正确,或者未添加对应的库");
}
if (!typeof(StorageBase).IsAssignableFrom(type))
{
throw new SpiderException("存储器类型配置不正确");
}
var method = type.GetMethod("CreateFromOptions");
if (method == null)
{
throw new SpiderException("存储器未实现 CreateFromOptions 方法,无法自动创建");
}
var storage = method.Invoke(null, new object[] {options});
if (storage == null)
{
throw new SpiderException("创建默认存储器失败");
}
return (StorageBase) storage;
}
private void ResetMmfSignal()
{
if (MmfSignal)
{
if (!Directory.Exists("mmf-signal"))
{
Directory.CreateDirectory("mmf-signal");
}
var mmf = MemoryMappedFile.CreateFromFile(Path.Combine("mmf-signal", Id), FileMode.OpenOrCreate, null,
4, MemoryMappedFileAccess.ReadWrite);
using (var accessor = mmf.CreateViewAccessor())
{
accessor.Write(0, false);
accessor.Flush();
_logger.LogInformation("任务 {Id} 初始化 MMF 退出信号");
}
}
}
/// <summary>
/// 爬虫速度控制器
/// </summary>
/// <returns></returns>
private Task StartSpeedControllerAsync()
{
return Task.Factory.StartNew(async () =>
{
bool @break = false;
var mmf = MmfSignal
? MemoryMappedFile.CreateFromFile(Path.Combine("mmf-signal", Id), FileMode.OpenOrCreate, null, 4,
MemoryMappedFileAccess.ReadWrite)
: null;
using (var accessor = mmf?.CreateViewAccessor())
{
_logger.LogInformation($"任务 {Id} 速度控制器启动");
var paused = 0;
while (!@break)
{
Thread.Sleep(_speedControllerInterval);
try
{
switch (Status)
{
case Status.Running:
{
try
{
// 判断是否过多下载请求未得到回应
if (_enqueued.Value - _responded.Value > NonRespondedLimitation)
{
if (paused > NonRespondedTimeLimitation)
{
_logger.LogInformation(
$"任务 {Id} {NonRespondedTimeLimitation} 秒未收到下载回应");
@break = true;
break;
}
paused += _speedControllerInterval;
_logger.LogInformation($"任务 {Id} 速度控制器因过多下载请求未得到回应暂停");
continue;
}
paused = 0;
// 重试超时的下载请求
var timeoutRequests = new List<Request>();
var now = DateTime.Now;
foreach (var kv in _enqueuedRequestDict)
{
if (!((now - kv.Value.CreationTime).TotalSeconds > RespondedTimeout))
{
continue;
}
kv.Value.RetriedTimes++;
if (kv.Value.RetriedTimes > RespondedTimeoutRetryTimes)
{
_logger.LogInformation(
$"任务 {Id} 重试下载请求 {RespondedTimeoutRetryTimes} 次未收到下载回应");
@break = true;
break;
}
timeoutRequests.Add(kv.Value);
}
// 如果有超时的下载则重试,无超时的下载则从调度队列里取
if (timeoutRequests.Count > 0)
{
await EnqueueRequests(timeoutRequests.ToArray());
}
else
{
var requests = _scheduler.Dequeue(Id, _dequeueBatchCount);
if (requests == null || requests.Length == 0) break;
foreach (var request in requests)
{
foreach (var configureRequestDelegate in _configureRequestDelegates)
{
configureRequestDelegate(request);
}
}
await EnqueueRequests(requests);
}
}
catch (Exception e)
{
_logger.LogError($"任务 {Id} 速度控制器运转失败: {e}");
}
break;
}
case Status.Paused:
{
_logger.LogDebug($"任务 {Id} 速度控制器暂停");
break;
}
case Status.Exiting:
case Status.Exited:
{
@break = true;
break;
}
}
if (!@break && accessor != null && accessor.ReadBoolean(0))
{
_logger.LogInformation($"任务 {Id} 收到 MMF 退出信号");
Exit();
}
}
catch (Exception e)
{
_logger.LogError($"任务 {Id} 速度控制器运转失败: {e}");
}
}
}
_logger.LogInformation($"任务 {Id} 速度控制器退出");
});
}
/// <summary>
/// 分配下载器
/// </summary>
/// <returns>是否分配成功</returns>
private async Task AllotDownloaderAsync()
{
var json = JsonConvert.SerializeObject(new AllocateDownloaderMessage
{
OwnerId = Id,
AllowAutoRedirect = DownloaderSettings.AllowAutoRedirect,
UseProxy = DownloaderSettings.UseProxy,
DownloaderCount = DownloaderSettings.DownloaderCount,
Cookies = DownloaderSettings.Cookies,
DecodeHtml = DownloaderSettings.DecodeHtml,
Timeout = DownloaderSettings.Timeout,
Type = DownloaderSettings.Type,
UseCookies = DownloaderSettings.UseCookies,
CreationTime = DateTime.Now
});
await _mq.PublishAsync(Framework.DownloaderCenterTopic, $"|{Framework.AllocateDownloaderCommand}|{json}");
}
private async Task HandleMessage(string message)
{
if (string.IsNullOrWhiteSpace(message))
{
_logger.LogWarning($"任务 {Id} 接收到空消息");
return;
}
var commandMessage = message.ToCommandMessage();
if (commandMessage != null)
{
switch (commandMessage.Command)
{
case Framework.AllocateDownloaderCommand:
{
if (commandMessage.Message == "true")
{
_allocated.Inc();
}
else
{
_logger.LogError($"任务 {Id} 分配下载器代理失败");
_allocatedSuccess = false;
}
break;
}
default:
{
_logger.LogError($"任务 {Id} 未能处理命令: {message}");
break;
}
}
return;
}
_lastRequestedTime = DateTime.Now;
Response[] responses;
try
{
responses = JsonConvert.DeserializeObject<Response[]>(message);
}
catch
{
_logger.LogError($"任务 {Id} 接收到异常消息: {message}");
return;
}
try
{
if (responses.Length == 0)
{
_logger.LogWarning($"任务 {Id} 接收到空回复");
return;
}
_responded.Add(responses.Length);
// 只要有回应就从缓存中删除,即便是异常要重新下载会成 EnqueueRequest 中重新加回缓存
// 此处只需要保证: 发 -> 收 可以一对一删除就可以保证检测机制的正确性
foreach (var response in responses)
{
_enqueuedRequestDict.TryRemove(response.Request.Hash, out _);
}
var agentId = responses.First().AgentId;
var successResponses = responses.Where(x => x.Success).ToList();
// 统计下载成功
if (successResponses.Count > 0)
{
var elapsedMilliseconds = successResponses.Sum(x => x.ElapsedMilliseconds);
await _statisticsService.IncrementDownloadSuccessAsync(agentId, successResponses.Count,
elapsedMilliseconds);
}
// 处理下载成功的请求
Parallel.ForEach(successResponses, async response =>
{
_logger.LogInformation($"任务 {Id} 下载 {response.Request.Url} 成功");
try
{
var context = new DataFlowContext(response, _services.CreateScope().ServiceProvider);
foreach (var dataFlow in _dataFlows)
{
var dataFlowResult = await dataFlow.HandleAsync(context);
var @break = false;
switch (dataFlowResult)
{
case DataFlowResult.Success:
{
continue;
}
case DataFlowResult.Failed:
{
// 如果处理失败,则直接返回
_logger.LogInformation($"任务 {Id} 处理 {response.Request.Url} 失败: {context.Result}");
await _statisticsService.IncrementFailedAsync(Id);
return;
}
case DataFlowResult.Terminated:
{
@break = true;
break;
}
}
if (@break)
{
break;
}
}
var resultIsEmpty = !context.HasItems && !context.HasParseItems;
// 如果解析结果为空,重试
if (resultIsEmpty && RetryWhenResultIsEmpty)
{
if (response.Request.RetriedTimes < RetryDownloadTimes)
{
response.Request.RetriedTimes++;
await EnqueueRequests(response.Request);
// 即然是重试这个请求,则解析必然还会再执行一遍,所以解析到的目标链接、成功状态都应该到最后来处理。
_logger.LogInformation($"任务 {Id} 处理 {response.Request.Url} 解析结果为空,尝试重试");
return;
}
}
// 解析的目标请求
if (context.FollowRequests != null && context.FollowRequests.Count > 0)
{
var requests = new List<Request>();
foreach (var followRequest in context.FollowRequests)
{
followRequest.Depth = response.Request.Depth + 1;
if (followRequest.Depth <= Depth)
{
requests.Add(followRequest);
}
}
var count = _scheduler.Enqueue(requests);
if (count > 0)
{
await _statisticsService.IncrementTotalAsync(Id, count);
}
}
if (!resultIsEmpty)
{
await _statisticsService.IncrementSuccessAsync(Id);
_logger.LogInformation($"任务 {Id} 处理 {response.Request.Url} 成功");
}
else
{
if (RetryWhenResultIsEmpty)
{
await _statisticsService.IncrementFailedAsync(Id);
_logger.LogInformation($"任务 {Id} 处理 {response.Request.Url} 失败,解析结果为空");
}
else
{
await _statisticsService.IncrementSuccessAsync(Id);
_logger.LogInformation($"任务 {Id} 处理 {response.Request.Url} 成功,解析结果为空");
}
}
}
catch (Exception e)
{
await _statisticsService.IncrementFailedAsync(Id);
_logger.LogInformation($"任务 {Id} 处理 {response.Request.Url} 失败: {e}");
}
});
// TODO: 此处需要优化
var retryResponses =
responses.Where(x => !x.Success && x.Request.RetriedTimes < RetryDownloadTimes)
.ToList();
var downloadFailedResponses =
responses.Where(x => !x.Success)
.ToList();
var failedResponses =
responses.Where(x => !x.Success && x.Request.RetriedTimes >= RetryDownloadTimes)
.ToList();
if (retryResponses.Count > 0)
{
retryResponses.ForEach(x =>
{
x.Request.RetriedTimes++;
_logger.LogInformation($"任务 {Id} 下载 {x.Request.Url} 失败: {x.Exception}");
});
await EnqueueRequests(retryResponses.Select(x => x.Request).ToArray());
}
// 统计下载失败
if (downloadFailedResponses.Count > 0)
{
var elapsedMilliseconds = downloadFailedResponses.Sum(x => x.ElapsedMilliseconds);
await _statisticsService.IncrementDownloadFailedAsync(agentId,
downloadFailedResponses.Count, elapsedMilliseconds);
}
// 统计失败
if (failedResponses.Count > 0)
{
await _statisticsService.IncrementFailedAsync(Id, failedResponses.Count);
}
}
catch (Exception ex)
{
_logger.LogError($"任务 {Id} 处理消息 {message} 失败: {ex}");
}
}
/// <summary>
/// 阻塞等待直到爬虫结束
/// </summary>
/// <returns></returns>
private async Task WaitForExiting()
{
int waited = 0;
while (Status != Status.Exiting)
{
if ((DateTime.Now - _lastRequestedTime).Seconds > EmptySleepTime)
{
break;
}
else
{
Thread.Sleep(1000);
}
waited += 1;
if (waited > StatisticsInterval)
{
waited = 0;
await _statisticsService.PrintStatisticsAsync(Id);
}
}
}
/// <summary>
/// 判断爬虫是否正在运行
/// </summary>
private void CheckIfRunning()
{
if (Status == Status.Running || Status == Status.Paused)
{
throw new SpiderException("任务 {Id} 正在运行");
}
}
private void ConsoleCancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
Exit();
while (Status != Status.Exited)
{
Thread.Sleep(100);
}
}
/// <summary>
/// 把当前缓存的所有 Request 入队
/// </summary>
[MethodImpl(MethodImplOptions.Synchronized)]
private void EnqueueRequests()
{
if (_requests.Count <= 0) return;
_scheduler = _scheduler ?? new QueueDistinctBfsScheduler();
var count = _scheduler.Enqueue(_requests);
_statisticsService.IncrementTotalAsync(Id, count).ConfigureAwait(false).GetAwaiter();
_logger.LogInformation($"任务 {Id} 推送请求到调度器,数量 {_requests.Count}");
_requests.Clear();
}
private async Task EnqueueRequests(params Request[] requests)
{
if (requests.Length > 0)
{
foreach (var request in requests)
{
request.CreationTime = DateTime.Now;
}
await _mq.PublishAsync(Framework.DownloaderCenterTopic,
$"|{Framework.DownloadCommand}|{JsonConvert.SerializeObject(requests)}");
foreach (var request in requests)
{
_enqueuedRequestDict.TryAdd(request.Hash, request);
}
_enqueued.Add(requests.Length);
}
}
}
} | 23.739651 | 109 | 0.615381 | [
"MIT"
] | lenwen/DotnetSpider | src/DotnetSpider/Spider.cs | 24,307 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace baggage_handling_system
{
public class Passenger
{
private string ID;
private string FlightNo;
private bool transfer;
private bool ExtraBaggageAllowance = false;
private List<Baggage> baggages = new List<Baggage>();
/**
* @brief : This method set ID value and also return ID value.
*/
public string ID1 { get => ID; set => ID = value; }
public string FlightNo1 { get => FlightNo; set => FlightNo = value; }
public bool ExtraBaggageAllowance1 { get => ExtraBaggageAllowance; set => ExtraBaggageAllowance = value; }
public List<Baggage> Baggages { get => baggages; set => baggages = value; }
public bool Transfer { get => transfer; set => transfer = value; }
public Passenger(string _ID, string flightNo, bool extraBaggageAllowence, bool transfer, List<Baggage> _baggages)
{
ID = _ID;
FlightNo = flightNo;
ExtraBaggageAllowance = extraBaggageAllowence;
Transfer = transfer;
baggages = _baggages;
}
public bool IsValid(string ID , string flightNo)
{
return (this.ID.Equals(ID) && this.FlightNo1.Equals(flightNo));
}
}
} | 34.7 | 121 | 0.620317 | [
"MIT"
] | ardasdasdas/baggage-handling-system | baggage-handling-system/baggage-handling-system/passenger.cs | 1,390 | C# |
using System.Collections.Generic;
using NetDevPL.Infrastructure.Services;
namespace NetDevPLWeb.Features.WebCasts
{
public class WebcastsSource
{
private readonly IJsonReader _jsonReader;
public WebcastsSource(IJsonReader jsonReader)
{
_jsonReader = jsonReader;
}
public ICollection<Webcast> GetWebcast()
{
return _jsonReader.ReadAll<Webcast>("Features/Webcasts/webcastsList.json");
}
}
} | 24.2 | 87 | 0.663223 | [
"MIT"
] | NetDevelopersPoland/NetDevPLWebsite | src/Apps/NetDevPL.Apps.WebApp/Features/WebCasts/WebcastsSource.cs | 486 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using InternshipER.App_Code;
namespace InternshipER
{
public partial class login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Session.Clear();
Session["loginPage"] = true;
if (!IsPostBack)
{
Session["loginPage"] = true;
Page.Title = "Giriş Ekranı";
}
}
protected void loginClick_Event(object sender, EventArgs e)
{
if (Database.loginAttempt(loginUsername.Value, loginPassword.Value) == true)
{
Session["id"] = Database.getUserId(loginUsername.Value, loginPassword.Value);
Session["loginPage"] = false;
Response.Redirect("home.aspx");
}
else
{
Response.Write("<script>alert('Giriş Bilgilerini kontrol ediniz!')</script>");
}
}
}
} | 28.175 | 94 | 0.563443 | [
"MIT"
] | EnesAltinisik/Inter | InternshipER/login.aspx.cs | 1,132 | C# |
using MelonLoader;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CacheRemover.Internals
{
class Logger
{
public static void Msg(string text)
{
MelonLogger.Msg(text);
Struct.DebugText = Struct.DebugText + "\n [Log] " + text + "\n";
}
public static void Warning(string text)
{
MelonLogger.Warning(text);
Struct.DebugText = Struct.DebugText + "\n [Warning] " + text + "\n";
}
public static void Error(string text)
{
MelonLogger.Error(text);
Struct.DebugText = Struct.DebugText + "\n [Error] " + text + "\n";
}
}
}
| 24.258065 | 80 | 0.569149 | [
"Unlicense"
] | not90Hz/CacheRemover | CacheRemover/Internals/Logger.cs | 754 | C# |
public class ProduceDialogVO
{
/// <summary>
/// 描述文本
/// </summary>
public string TextDescribe;
/// <summary>
/// icon 图标
/// </summary>
public int ImageIcon;
/// <summary>
/// icon 图标
/// </summary>
public int ImageBaseIcon;
/// <summary>
/// 类型名字
/// </summary>
public string TypeName;
/// <summary>
/// 按钮索引
/// </summary>
public int Index;
}
| 14.965517 | 31 | 0.502304 | [
"Apache-2.0"
] | fqkw6/RewriteFrame | other/Scripts/Model/VO/ProduceDialogVO.cs | 468 | C# |
namespace More.Collections.Generic
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
/// <summary>
/// Represents a debugging class used to visualize an instance of the <see cref="IStack{T}"/> interface.
/// </summary>
/// <typeparam name="T">The <see cref="Type">type</see> of items in the <see cref="IStack{T}">stack</see>.</typeparam>
public sealed class StackDebugView<T>
{
private readonly IStack<T> stack;
/// <summary>
/// Initializes a new instance of the <see cref="StackDebugView{T}"/> class.
/// </summary>
/// <param name="stack">The <see cref="IStack{T}"/> instance to debug.</param>
public StackDebugView( IStack<T> stack )
{
Arg.NotNull( stack, nameof( stack ) );
this.stack = stack;
}
/// <summary>
/// Gets the debugger view of a specific <see cref="IStack{T}"/> instance.
/// </summary>
/// <value>The debugger view of a specific <see cref="IStack{T}"/> instance.</value>
[DebuggerBrowsable( DebuggerBrowsableState.RootHidden )]
[SuppressMessage( "Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "This is the convention for the debugger visualization system." )]
public T[] Items
{
get
{
Contract.Ensures( stack != null );
return stack.ToArray();
}
}
}
}
| 36.613636 | 175 | 0.596524 | [
"MIT"
] | pashcovich/More | src/Core/Core/More/Collections.Generic/StackDebugViewT.cs | 1,613 | C# |
using System;
using System.IO;
using Amazon.Lambda.Core;
namespace LambdaNative.Internal
{
internal class StreamSerializer : ILambdaSerializer
{
public T Deserialize<T>(Stream requestStream)
{
return (T)Convert.ChangeType(requestStream, typeof(T));
}
public void Serialize<T>(T response, Stream responseStream)
{
((Stream)(object)response).CopyTo(responseStream);
}
}
} | 24 | 67 | 0.638158 | [
"MIT"
] | ifew/lambda-native | src/Internal/StreamSerializer.cs | 458 | C# |
using System;
using System.Linq;
namespace _02.Rotate_and_Sum
{
class Program
{
static void Main(string[] args)
{
var numArray = Console.ReadLine()
.Split(' ')
.Select(int.Parse)
.ToArray();
int countRotations = int.Parse(Console.ReadLine());
int[] sum = new int[numArray.Length];
for (int i = 0; i < countRotations; i++)
{
int[] rotateArray = new int[numArray.Length];
rotateArray[0] = numArray[numArray.Length -1];
for (int iRotate = 0; iRotate < numArray.Length -1; iRotate++)
{
rotateArray[iRotate +1] = numArray[iRotate];
}
for (int iSum = 0; iSum < sum.Length; iSum++)
{
sum[iSum] += rotateArray[iSum];
}
numArray = rotateArray;
}
foreach (var item in sum)
{
Console.Write(item + " ");
}
}
}
}
| 27.425 | 78 | 0.437557 | [
"MIT"
] | LuchezarVelkov/C-Sharp-Course | 02 Programming Fundamentals/14 ARRAYS - EXERCISES/02. Rotate and Sum/02. Rotate and Sum.cs | 1,099 | 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.AzureNextGen.Network.V20181001.Outputs
{
[OutputType]
public sealed class ApplicationGatewayAutoscaleConfigurationResponse
{
/// <summary>
/// Lower bound on number of Application Gateway instances
/// </summary>
public readonly int MinCapacity;
[OutputConstructor]
private ApplicationGatewayAutoscaleConfigurationResponse(int minCapacity)
{
MinCapacity = minCapacity;
}
}
}
| 28.035714 | 81 | 0.696815 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Network/V20181001/Outputs/ApplicationGatewayAutoscaleConfigurationResponse.cs | 785 | C# |
using System;
using Bing.Datas.Sql;
using Bing.Datas.Sql.Builders;
using Bing.Datas.Sql.Builders.Clauses;
using Bing.Datas.Sql.Builders.Core;
using Bing.Datas.Sql.Matedatas;
namespace Bing.Datas.Dapper.Sqlite
{
/// <summary>
/// Sqlite 表连接子句
/// </summary>
public class SqliteJoinClause : JoinClause
{
/// <summary>
/// 初始化一个<see cref="JoinClause"/>类型的实例
/// </summary>
/// <param name="sqlBuilder">Sql生成器</param>
/// <param name="dialect">Sql方言</param>
/// <param name="resolver">实体解析器</param>
/// <param name="register">实体别名注册器</param>
/// <param name="parameterManager">参数管理器</param>
/// <param name="tableDatabase">表数据库</param>
public SqliteJoinClause(ISqlBuilder sqlBuilder
, IDialect dialect
, IEntityResolver resolver
, IEntityAliasRegister register
, IParameterManager parameterManager
, ITableDatabase tableDatabase)
: base(sqlBuilder, dialect, resolver, register, parameterManager, tableDatabase)
{
}
/// <summary>
/// 创建连接项
/// </summary>
/// <param name="joinType">连接类型</param>
/// <param name="table">表名</param>
/// <param name="schema">架构名</param>
/// <param name="alias">别名</param>
/// <param name="type">类型</param>
protected override JoinItem CreateJoinItem(string joinType, string table, string schema, string alias,
Type type = null) => new JoinItem(joinType, table, schema, alias, false, false, type);
}
}
| 34.869565 | 110 | 0.600998 | [
"MIT"
] | brucehu123/Bing.NetCore | framework/src/Bing.Datas.Dapper/Sqlite/SqliteJoinClause.cs | 1,724 | C# |
// <auto-generated />
using CarRentalClient.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using System;
namespace CarRentalClient.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("00000000000000_CreateIdentitySchema")]
partial class CreateIdentitySchema
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<string>("NormalizedEmail")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderDisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("RoleId")
.HasColumnType("nvarchar(450)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Name")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 37.705036 | 125 | 0.471475 | [
"MIT"
] | YotakaUMi/CarRental | CarRentalClient/CarRentalClient/Data/Migrations/00000000000000_CreateIdentitySchema.Designer.cs | 10,482 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;
using System.CodeDom;
using System.Reflection;
using DotaHIT.Jass.Types;
using DotaHIT.Jass.Operations;
using DotaHIT.Jass.Native.Types;
using DotaHIT.Core;
using DotaHIT.Core.Resources;
using DotaHIT.Jass.Native.Events;
using DotaHIT.Jass.Native.Constants;
using System.Collections.Specialized;
namespace DotaHIT.Jass.Commands
{
public abstract class DHJassCommand
{
public abstract DHJassValue GetResult();
public virtual string GetDebugString()
{
return null;
}
}
public enum AnyOperation
{
Less = 0,
LessOrEqual = 1,
Equal = 2,
GreaterOrEqual = 3,
Greater = 4,
NotEqual = 5,
Add,
Subtract,
Multiply,
Divide,
AND,
OR,
Not
}
public class DHJassGetValueCommand : DHJassCommand
{
protected DHJassCommand command = null;
protected DHJassGetValueCommand() { }
public DHJassGetValueCommand(string code)
{
if (!TryParseCode(code, out command))
command = new DHJassPassValueCommand(new DHJassUnusedType());
}
public override DHJassValue GetResult()
{
return command.GetResult();
}
public bool TryParseCode(string code, out DHJassCommand command)
{
if (String.IsNullOrEmpty(code))
{
command = null;
return false;
}
string name;
string param;
List<string> operands;
List<string> operators;
bool isDirectValue;
object parsedValue;
unsafe
{
fixed (char* pStr = code)
{
char* ptr = DHJassSyntax.removeWsRbRecursive(pStr, pStr + code.Length);
code = new string(ptr);
if (isDirectValue = DHJassSyntax.checkDirectValueSyntaxFast(*ptr))
{
foreach (DHJassValue parser in DbJassTypeValueKnowledge.TypeValuePairs.Values)
if (parser.TryParseDirect(code, out parsedValue))
{
DHJassValue value = parser.GetNew();
value.Value = parsedValue;
command = new DHJassPassValueCommand(value);
return true;
}
}
else
switch (code)
{
case "null":
command = new DHJassPassValueCommand(new DHJassUnusedType());
return true;
case "true":
command = new DHJassPassValueCommand(new DHJassBoolean(null, true));
return true;
case "false":
command = new DHJassPassValueCommand(new DHJassBoolean(null, false));
return true;
}
if (DHJassSyntax.checkLogicalExpressionsSyntaxFast(ptr, out operands, out operators))//code, out match))
return TryGetLogicalExpressionCommandFast(operands, operators, out command);
else
if (DHJassSyntax.checkRelationalExpressionsSyntaxFast(ptr, out operands, out operators))// out match))
return TryGetRelationalExpressionCommandFast(operands, operators, out command);//match, out command);
else
if (DHJassSyntax.checkArithmeticExpressionsSyntaxFast(ptr, out operands, out operators))// out match))
return TryGetArithmeticExpressionCommandFast(operands, operators, out command); //match, out command);
else
if (!isDirectValue)
{
if (DHJassSyntax.checkNegativeOperatorUsageSyntaxFast(ptr, out name))
return TryGetNegativeOperatorCommand(name, out command);
else
if (DHJassSyntax.checkTypeVariableUsageSyntaxFast(ptr, out name))
return TryGetVariableCommand(name, out command);
else
if (DHJassSyntax.checkArrayVariableUsageSyntaxFast(ptr, out name, out param))
return TryGetArrayElementCommand(name, param, out command);
else
if (DHJassSyntax.checkFunctionUsageSyntaxFast(ptr, out name, out operands))// out match))
return TryGetCallFunctionCommandFast(name, operands, out command);
else
if (DHJassSyntax.checkFunctionPointerUsageSyntaxFast(ptr, out name))
return TryGetFunctionPointerCommand(name, out command);
}
}
}
command = null;
return false;
}
public static bool TryGetNegativeOperatorCommand(string operand, out DHJassCommand command)
{
command = new DHJassOperationCommand(new DHJassGetValueOnDemandCommand(operand), AnyOperation.Not);
return true;
}
public static bool TryGetVariableCommand(string name, out DHJassCommand variable)
{
variable = new DHJassPassVariableCommand(name);
return true;
}
public static bool TryGetArrayElementCommand(string name, string indexCode, out DHJassCommand element)
{
element = new DHJassGetArrayElementCommand(name, indexCode);
return true;
}
public static bool TryGetFunctionPointerCommand(string name, out DHJassCommand functionPointer)
{
DHJassFunction function;
if (DHJassExecutor.Functions.TryGetValue(name, out function))
{
functionPointer = new DHJassPassValueCommand(new DHJassCode(null, function));
return true;
}
functionPointer = new DHJassPassValueCommand(null);
return false;
}
public static bool TryGetLogicalExpressionCommandFast(List<string> sOperands, List<string> operators, out DHJassCommand value)
{
List<DHJassCommand> operands = new List<DHJassCommand>(sOperands.Count);
//////////////////////////////////
// collect operands
//////////////////////////////////
foreach (string ccOperand in sOperands)
{
//DHJassBoolean operand = new DHJassBoolean();
//operand.SetValue(ccOperand.Value);
DHJassCommand operand = new DHJassGetValueCommand(ccOperand);
operands.Add(operand);
}
//////////////////////////////////////
// process expression
//////////////////////////////////////
if (operands.Count == 0)
{
value = null;
return false;
}
DHJassCommand operand2;
DHJassCommand result;
result = operands[0];
for (int i = 0; i < operators.Count; i++)
{
string Operator = operators[i];
if (Operator == "and")
{
operand2 = operands[i + 1];
result = new DHJassOperationCommand(result, operand2, AnyOperation.AND);
}
else
if (Operator == "or")
{
operand2 = operands[i + 1];
result = new DHJassOperationCommand(result, operand2, AnyOperation.OR);
}
else
continue;
}
value = result;
return true;
}
public static bool TryGetArithmeticExpressionCommandFast(List<string> sOperands, List<string> operators, out DHJassCommand value)
{
List<DHJassCommand> operands = new List<DHJassCommand>(sOperands.Count);
//////////////////////////////////
// collect operands
//////////////////////////////////
foreach (string ccOperand in sOperands)
{
DHJassCommand operand = new DHJassGetValueCommand(ccOperand);
operands.Add(operand);
}
//////////////////////////////////////
// process expression
//////////////////////////////////////
if (operands.Count == 0)
{
value = null;
return false;
}
DHJassCommand operand1;
DHJassCommand operand2;
DHJassCommand result;
// process '*' and '/' first
for (int i = 0; i < operators.Count; i++)
{
string Operator = operators[i];
if (Operator == "*")
{
operand1 = operands[i];
operand2 = operands[i + 1];
result = new DHJassOperationCommand(operand1, operand2, AnyOperation.Multiply);
}
else
if (Operator == "/")
{
operand1 = operands[i];
operand2 = operands[i + 1];
result = new DHJassOperationCommand(operand1, operand2, AnyOperation.Divide);
}
else
continue;
operands[i] = result;
operands.RemoveAt(i + 1);
operators.RemoveAt(i);
i--;
}
// now '+' and '-'
result = operands[0];
for (int i = 0; i < operators.Count; i++)
{
string Operator = operators[i];
if (Operator == "+")
{
operand2 = operands[i + 1];
result = new DHJassOperationCommand(result, operand2, AnyOperation.Add);
}
else
if (Operator == "-")
{
operand2 = operands[i + 1];
result = new DHJassOperationCommand(result, operand2, AnyOperation.Subtract);
}
else
continue;
}
value = result;
return true;
}
public static bool TryGetRelationalExpressionCommandFast(List<string> sOperands, List<string> operators, out DHJassCommand value)
{
List<DHJassCommand> operands = new List<DHJassCommand>(sOperands.Count);
//////////////////////////////////
// collect operands
//////////////////////////////////
foreach (string ccOperand in sOperands)
{
//DHJassValue operand = DHJassValue.CreateValueFromCode(ccOperand.Value);
DHJassCommand operand = new DHJassGetValueCommand(ccOperand);
operands.Add(operand);
}
//////////////////////////////////////
// process expression
//////////////////////////////////////
if (operands.Count == 0)
{
value = null;
return false;
}
//DHJassBoolean operand1;
DHJassCommand operand2;
DHJassCommand result;
result = operands[0];
for (int i = 0; i < operators.Count; i++)
{
string Operator = operators[i];
operand2 = operands[i + 1];
switch (Operator)
{
case ">":
result = new DHJassOperationCommand(result, operand2, AnyOperation.Greater);
break;
case ">=":
result = new DHJassOperationCommand(result, operand2, AnyOperation.GreaterOrEqual);
break;
case "<":
result = new DHJassOperationCommand(result, operand2, AnyOperation.Less);
break;
case "<=":
result = new DHJassOperationCommand(result, operand2, AnyOperation.LessOrEqual);
break;
case "==":
result = new DHJassOperationCommand(result, operand2, AnyOperation.Equal);
break;
case "!=":
result = new DHJassOperationCommand(result, operand2, AnyOperation.NotEqual);
break;
}
}
value = result;
return true;
}
public static bool TryGetCallFunctionCommandFast(string name, List<string> args, out DHJassCommand functionCall)
{
functionCall = new DHJassCallFunctionCommand(name, args);
return true;
}
}
public class DHJassGetValueOnDemandCommand : DHJassGetValueCommand
{
string code;
public DHJassGetValueOnDemandCommand(string code)
{
this.code = code;
}
public override DHJassValue GetResult()
{
if (command == null)
{
if (!TryParseCode(code, out command))
command = new DHJassPassValueCommand(new DHJassUnusedType());
}
return command.GetResult();
}
public override string GetDebugString()
{
return code;
}
}
public class DHJassSetValueOnDemandCommand : DHJassCommand
{
DHJassCommand command = null;
DHJassCommand index = null;
DHJassCommand value = null;
#if DEBUG
string _name_usage = null;
string _valueToSet = null;
#endif
public DHJassSetValueOnDemandCommand(string name_usage, string valueToSet)
{
#if DEBUG
_name_usage = name_usage;
_valueToSet = valueToSet;
#endif
TryParseCode(name_usage, valueToSet, out command);
}
public override DHJassValue GetResult()
{
if (command != null)
{
if (index == null)
{
DHJassValue variable = command.GetResult();
variable.SetValue(value.GetResult());
if (DHJassExecutor.IsTracing && variable.Name.StartsWith(DHJassExecutor.TraceName))
{
string strValue = "";
if (variable is DHJassInt && variable.IntValue != 0)
strValue = (variable as DHJassInt).IDValue + "/";
strValue += variable.Value;
Console.WriteLine("Called Set " + variable.Name + "=" + strValue);
}
}
else
{
DHJassArray array = command.GetResult() as DHJassArray;
DHJassValue jIndex = index.GetResult();
DHJassValue jValue = value.GetResult();
if (DHJassExecutor.IsTracing && array.Name.StartsWith(DHJassExecutor.TraceName))
{
string strValue = "";
if (jValue is DHJassInt && jValue.IntValue != 0)
strValue = (jValue as DHJassInt).IDValue + "/";
strValue += jValue.Value;
Console.WriteLine("Called Set " + array.Name + "[" + jIndex.IntValue + "]=" + strValue);
}
array.SetElementValue(jIndex.IntValue, jValue);
}
}
return null;
}
public bool TryParseCode(string name_usage, string valueToSet, out DHJassCommand command)
{
string name;
string param;
if (DHJassSyntax.checkTypeVariableUsageSyntaxFast(name_usage, out name))
{
command = new DHJassPassVariableCommand(name);
value = new DHJassGetValueOnDemandCommand(valueToSet);
return true;
}
else
if (DHJassSyntax.checkArrayVariableUsageSyntaxFast(name_usage, out name, out param))
{
command = new DHJassPassVariableCommand(name);
index = new DHJassGetValueOnDemandCommand(param);
value = new DHJassGetValueOnDemandCommand(valueToSet);
return true;
}
command = null;
return false;
}
#if DEBUG
public override string GetDebugString()
{
return "set " + _name_usage + "=" + _valueToSet;
}
#endif
}
public class DHJassPassValueCommand : DHJassCommand
{
DHJassValue value;
public DHJassPassValueCommand(DHJassValue value)
{
this.value = value;
}
public override DHJassValue GetResult()
{
return value;
}
}
public class DHJassPassValueCopyCommand : DHJassCommand
{
string name;
DHJassValue variable = null;
DHJassCommand value = null;
public DHJassPassValueCopyCommand(DHJassValue value, string copyName, DHJassCommand copyValue)
{
this.variable = value;
this.name = copyName;
this.value = copyValue;
}
public override DHJassValue GetResult()
{
DHJassValue copy = variable.GetNew();
copy.Name = name;
copy.SetValue(value.GetResult());
return copy;
}
public override string GetDebugString()
{
return name;
}
}
public class DHJassPassVariableCommand : DHJassCommand
{
string name;
public DHJassPassVariableCommand(string name)
{
this.name = name;
}
public override DHJassValue GetResult()
{
DHJassValue variable;
DHJassExecutor.TryGetVariable(name, out variable);
return variable;
}
public override string GetDebugString()
{
return name;
}
}
public class DHJassGetArrayElementCommand : DHJassCommand
{
string name;
DHJassCommand index;
public DHJassGetArrayElementCommand(string name, string indexCode)
{
this.name = name;
this.index = new DHJassGetValueCommand(indexCode);
}
public override DHJassValue GetResult()
{
DHJassValue array;
if (DHJassExecutor.TryGetVariable(name, out array) && array is DHJassArray)
{
int index = this.index.GetResult().IntValue;
if (DHJassExecutor.IsTracing && name.StartsWith(DHJassExecutor.TraceName))
{
string strValue = "";
DHJassValue jValue = (array as DHJassArray)[index];
if (jValue is DHJassInt && jValue.IntValue != 0)
strValue = (jValue as DHJassInt).IDValue + "/";
strValue += jValue.Value;
Console.WriteLine("Called Get " + name + "[" + index + "]==" + strValue);
}
if (DHJassExecutor.CatchArrayReference && !DHJassExecutor.CaughtReferences.Contains(name))
DHJassExecutor.CaughtReferences.Add(name);
return (array as DHJassArray)[index];
}
return new DHJassUnusedType();
}
}
public class DHJassCallFunctionCommand : DHJassCommand
{
DHJassFunction function;
DHJassCommand[] args;
public DHJassCallFunctionCommand(string code)
{
//Match match;
string name;
List<string> args;
if (DHJassSyntax.checkFunctionUsageSyntaxFast(code, out name, out args)) //out match))
parse(name, args);//match);
else
function = null;
}
public DHJassCallFunctionCommand(string name, List<string> argList)
{
function = null;
parse(name, argList);
}
void parse(string name, List<string> argList)
{
DHJassExecutor.Functions.TryGetValue(name, out this.function);
if (function == null && DHJassExecutor.ShowMissingFunctions)
DHJassExecutor.ReportMissingFunction(name);
//CaptureCollection cc = match.Groups["arg"].Captures;
args = new DHJassCommand[argList.Count];
for (int i = 0; i < argList.Count; i++)
args[i] = new DHJassGetValueOnDemandCommand(argList[i]);
}
public override DHJassValue GetResult()
{
if (function == null)
return new DHJassUnusedType();
else
if (DHJassExecutor.IsTracing && function.Name.StartsWith(DHJassExecutor.TraceName))
{
Console.Write("Called:" + function.Name);
Console.Write(" Parameters:");
string pars = "";
foreach (DHJassCommand cmd in args)
pars += "'" + cmd.GetDebugString() + "',";
pars = pars.TrimEnd(',');
Console.Write(pars);
Console.Write("\n");
}
return function.Execute(args);
}
}
public class DHJassOperationCommand : DHJassCommand
{
DHJassCommand a;
DHJassCommand b;
AnyOperation operation;
public DHJassOperationCommand(DHJassCommand a, DHJassCommand b, AnyOperation operation)
{
this.a = a;
this.b = b;
this.operation = operation;
}
public DHJassOperationCommand(DHJassCommand a, AnyOperation operation)
{
this.a = a;
this.operation = operation;
}
public override DHJassValue GetResult()
{
DHJassValue operand1 = a.GetResult();
switch (operation)
{
case AnyOperation.AND:
if (operand1.BoolValue == false)
return new DHJassBoolean(null, false);
break;
case AnyOperation.OR:
if (operand1.BoolValue == true)
return new DHJassBoolean(null, true);
break;
}
DHJassValue operand2 = (b != null) ? b.GetResult() : null;
switch (operation)
{
case AnyOperation.Add:
return operand1.Add(operand2);
case AnyOperation.Subtract:
return operand1.Subtract(operand2);
case AnyOperation.Multiply:
return operand1.Multiply(operand2);
case AnyOperation.Divide:
return operand1.Divide(operand2);
case AnyOperation.AND:
return operand1.And(operand2);
case AnyOperation.OR:
return operand1.Or(operand2);
case AnyOperation.Less:
return operand1.Less(operand2);
case AnyOperation.LessOrEqual:
return operand1.LessOrEqual(operand2);
case AnyOperation.Greater:
return operand1.Greater(operand2);
case AnyOperation.GreaterOrEqual:
return operand1.GreaterOrEqual(operand2);
case AnyOperation.Equal:
return operand1.Equals(operand2);
case AnyOperation.NotEqual:
return operand1.NotEquals(operand2);
case AnyOperation.Not:
return operand1.Not();
default:
return new DHJassUnusedType();
}
}
}
public class DHJassDeclarationOnDemandCommand : DHJassCommand
{
string code;
DHJassCommand command = null;
public DHJassDeclarationOnDemandCommand(string code)
{
this.code = code;
}
public override DHJassValue GetResult()
{
if (command == null)
{
if (!TryParseCode(code, out command))
command = new DHJassPassValueCommand(new DHJassUnusedType());
}
return command.GetResult();
}
public bool TryParseCode(string code, out DHJassCommand command)
{
if (code != "nothing")
{
string name = null;
DHJassGetValueOnDemandCommand value = null;
DHJassValue variable;
List<string> args;
if (DHJassValue.TryParseDeclaration(code, out variable, out args))
{
name = args[0];
value = new DHJassGetValueOnDemandCommand(args.Count > 1 ? args[1] : string.Empty);
}
else
{
variable = new DHJassUnusedType();
name = "error!";
value = null;
}
command = new DHJassPassValueCopyCommand(variable, name, value);
return true;
}
command = null;
return false;
}
}
public class DHJassGetGameStateCommand : DHJassCommand
{
string stateName;
public DHJassGetGameStateCommand(string stateName)
{
this.stateName = stateName;
}
public override DHJassValue GetResult()
{
switch (stateName)
{
case "GAME_STATE_TIME_OF_DAY":
break;
}
return new DHJassReal(null, 0);
}
}
}
| 33.296341 | 174 | 0.486064 | [
"Unlicense"
] | UnrealKaraulov/w3gReplayEditor | dotahittest/DotaHAB/Jass/_Commands.cs | 27,303 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Gamma.Entities
{
using System;
using System.Collections.Generic;
public partial class DocMaterialTankRemainders
{
public System.Guid DocMaterialTankRemainderID { get; set; }
public System.Guid DocID { get; set; }
public int DocMaterialTankID { get; set; }
public decimal Concentration { get; set; }
public int Level { get; set; }
public string Comment { get; set; }
public virtual DocMaterialTanks DocMaterialTanks { get; set; }
public virtual Docs Docs { get; set; }
}
}
| 35.714286 | 85 | 0.554 | [
"Unlicense"
] | Polimat/Gamma | Entities/DocMaterialTankRemainders.cs | 1,000 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace BastetFTMAPI.Authentication
{
public interface IUserService
{
Task<User> AuthenticateAsync(string username, string userNameHash, string password);
Task CreateUserAsync(User user);
Task<User> GetUserAsync(Guid id);
Task<List<User>> GetUsersAsync();
}
}
| 25.733333 | 92 | 0.715026 | [
"Apache-2.0"
] | Eng-RedWolf/Bastet-FTM-API | Authentication/IUserService.cs | 388 | C# |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
using UnityEngine;
using System.Collections;
using HUX.Utility;
using HUX;
// Updates gamepad from network source (most likely a controller connected to a pc)
public class InputSourceNetGamepad : InputSourceGamepadBase
{
public bool debugPrint;
public int messageCount;
LLNetwork network = new LLNetwork();
public int port = 9006;
void Start()
{
network.OnReceivedBytes += Network_OnReceivedBytes;
network.StartHost(port);
}
public override bool IsPresent()
{
return Connected();
}
public bool Connected()
{
return messageCount > 0;
}
public override void _Update()
{
network.Update();
base._Update();
}
private void Network_OnReceivedBytes(byte[] bytes)
{
if (debugPrint)
{
Debug.Log("Received: " + bytes.Length);
}
// Expecting 1 byte
if (bytes.Length == 17)
{
++messageCount;
// Print out the bytes if enabled
if (debugPrint)
{
string bstr = "";
for (int i = 0; i < bytes.Length; ++i)
{
bstr += bytes[i] + " ";
}
Debug.Log(bstr);
}
// Read out button states
int idx = 0;
byte buttonState = bytes[idx++];
bool aButtonPressed = (buttonState & 1) != 0 ? true : false;
bool bButtonPressed = (buttonState & 2) != 0 ? true : false;
bool startButtonPressed = (buttonState & 4) != 0 ? true : false;
idx += readNormalizedFloat(out leftJoyVector.x, bytes, idx);
idx += readNormalizedFloat(out leftJoyVector.y, bytes, idx);
idx += readNormalizedFloat(out rightJoyVector.x, bytes, idx);
idx += readNormalizedFloat(out rightJoyVector.y, bytes, idx);
idx += readNormalizedFloat(out trigVector.x, bytes, idx);
idx += readNormalizedFloat(out trigVector.y, bytes, idx);
idx += readNormalizedFloat(out padVector.x, bytes, idx);
idx += readNormalizedFloat(out padVector.y, bytes, idx);
aButtonState.ApplyState(aButtonPressed);
bButtonState.ApplyState(bButtonPressed);
startButtonState.ApplyState(startButtonPressed);
}
else
{
Debug.Log("Bytes: " + (bytes != null ? bytes.Length.ToString() : "null"));
}
}
}
| 25.043478 | 92 | 0.653212 | [
"MIT"
] | AhmedAldahshoury/HololensApp | DesignLabs_Unity/Assets/MRDesignLab/HUX/Scripts/Input/InputSourceNetGamepad.cs | 2,306 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Utilities;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.EntityFrameworkCore.Query
{
/// <summary>
/// <para>
/// Service dependencies parameter class for <see cref="CompiledQueryCacheKeyGenerator" />
/// </para>
/// <para>
/// This type is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// <para>
/// Do not construct instances of this class directly from either provider or application code as the
/// constructor signature may change as new dependencies are added. Instead, use this type in
/// your constructor so that an instance will be created and injected automatically by the
/// dependency injection container. To create an instance with some dependent services replaced,
/// first resolve the object from the dependency injection container, then replace selected
/// services using the 'With...' methods. Do not call the constructor at any point in this process.
/// </para>
/// <para>
/// The service lifetime is <see cref="ServiceLifetime.Scoped" />. This means that each
/// <see cref="DbContext" /> instance will use its own instance of this service.
/// The implementation may depend on other services registered with any lifetime.
/// The implementation does not need to be thread-safe.
/// </para>
/// </summary>
public sealed record CompiledQueryCacheKeyGeneratorDependencies
{
/// <summary>
/// <para>
/// Creates the service dependencies parameter object for a <see cref="CompiledQueryCacheKeyGenerator" />.
/// </para>
/// <para>
/// This type is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// <para>
/// Do not call this constructor directly from either provider or application code as it may change
/// as new dependencies are added. Instead, use this type in your constructor so that an instance
/// will be created and injected automatically by the dependency injection container. To create
/// an instance with some dependent services replaced, first resolve the object from the dependency
/// injection container, then replace selected services using the 'With...' methods. Do not call
/// the constructor at any point in this process.
/// </para>
/// <para>
/// The service lifetime is <see cref="ServiceLifetime.Scoped" />. This means that each
/// <see cref="DbContext" /> instance will use its own instance of this service.
/// The implementation may depend on other services registered with any lifetime.
/// The implementation does not need to be thread-safe.
/// </para>
/// </summary>
[EntityFrameworkInternal]
public CompiledQueryCacheKeyGeneratorDependencies(
IModel model,
ICurrentDbContext currentContext,
IExecutionStrategyFactory executionStrategyFactory)
{
Check.NotNull(model, nameof(model));
Check.NotNull(currentContext, nameof(currentContext));
Check.NotNull(executionStrategyFactory, nameof(executionStrategyFactory));
Model = model;
CurrentContext = currentContext;
IsRetryingExecutionStrategy = executionStrategyFactory.Create().RetriesOnFailure;
}
/// <summary>
/// The model that queries will be written against.
/// </summary>
public IModel Model { get; init; }
/// <summary>
/// The context that queries will be executed for.
/// </summary>
public ICurrentDbContext CurrentContext { get; init; }
/// <summary>
/// Whether the configured execution strategy can retry.
/// </summary>
public bool IsRetryingExecutionStrategy { get; init; }
}
}
| 50.923077 | 122 | 0.629909 | [
"Apache-2.0"
] | 0x0309/efcore | src/EFCore/Query/CompiledQueryCacheKeyGeneratorDependencies.cs | 4,634 | C# |
namespace Restall.Ichnaea.Tests.Unit
{
using ExceptionTest = ExceptionTest<AggregateRootNotBeingTrackedException, AggregateRootNotBeingTrackedExceptionTest.DefaultExceptionProperties>;
public class AggregateRootNotBeingTrackedExceptionTest: ExceptionTest
{
public new class ExceptionProperties: ExceptionTest.ExceptionProperties
{
}
public class DefaultExceptionProperties: ExceptionProperties
{
public DefaultExceptionProperties()
{
this.Message = ExceptionMessage.Default<AggregateRootNotBeingTrackedException>();
}
}
}
}
| 27.8 | 146 | 0.820144 | [
"MIT"
] | pete-restall/Ichnaea | Ichnaea.Tests/Unit/AggregateRootNotBeingTrackedExceptionTest.cs | 558 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum ItemType { Seed, Flower, SunPowerup }
public class ItemSpawner : MonoBehaviour
{
GameController gameController;
public GameObject seed;
public GameObject[] flowers;
public GameObject sunPowerup;
private void Start()
{
gameController = GameObject.FindGameObjectWithTag("GameController").GetComponent<GameController>();
}
public void SpawnItem(Vector2 location, ItemType itemType)
{
if(itemType == ItemType.Seed)
{
Instantiate(seed, location, Quaternion.identity);
gameController.soundManager.PlaySound(location, SoundType.SeedAppears);
}
else if(itemType == ItemType.Flower)
{
int flowerToSpawn = UnityEngine.Random.Range(0, flowers.Length);
Instantiate(flowers[flowerToSpawn], location, Quaternion.identity);
}
else if(itemType == ItemType.SunPowerup)
{
Instantiate(sunPowerup, location, Quaternion.identity);
}
}
}
| 29.513514 | 107 | 0.668498 | [
"MIT"
] | KeithSwanger/a-field-of-flowers | Start From Nothing/Assets/Scripts/ItemSpawner.cs | 1,094 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.Inputs
{
/// <summary>
/// The application gateway private link ip configuration.
/// </summary>
public sealed class ApplicationGatewayPrivateLinkIpConfigurationArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// The name of application gateway private link ip configuration.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// Whether the ip configuration is primary or not.
/// </summary>
[Input("primary")]
public Input<bool>? Primary { get; set; }
/// <summary>
/// The private IP address of the IP configuration.
/// </summary>
[Input("privateIPAddress")]
public Input<string>? PrivateIPAddress { get; set; }
/// <summary>
/// The private IP address allocation method.
/// </summary>
[Input("privateIPAllocationMethod")]
public InputUnion<string, Pulumi.AzureNative.Network.IPAllocationMethod>? PrivateIPAllocationMethod { get; set; }
/// <summary>
/// Reference to the subnet resource.
/// </summary>
[Input("subnet")]
public Input<Inputs.SubResourceArgs>? Subnet { get; set; }
public ApplicationGatewayPrivateLinkIpConfigurationArgs()
{
}
}
}
| 30.728814 | 121 | 0.605626 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/Inputs/ApplicationGatewayPrivateLinkIpConfigurationArgs.cs | 1,813 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
[JsiiByValue(fqn: "aws.Wafv2WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatement")]
public class Wafv2WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatement : aws.IWafv2WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatement
{
/// <summary>byte_match_statement block.</summary>
[JsiiOptional]
[JsiiProperty(name: "byteMatchStatement", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementByteMatchStatement\"},\"kind\":\"array\"}}", isOptional: true, isOverride: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementByteMatchStatement[]? ByteMatchStatement
{
get;
set;
}
/// <summary>geo_match_statement block.</summary>
[JsiiOptional]
[JsiiProperty(name: "geoMatchStatement", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementGeoMatchStatement\"},\"kind\":\"array\"}}", isOptional: true, isOverride: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementGeoMatchStatement[]? GeoMatchStatement
{
get;
set;
}
/// <summary>ip_set_reference_statement block.</summary>
[JsiiOptional]
[JsiiProperty(name: "ipSetReferenceStatement", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementIpSetReferenceStatement\"},\"kind\":\"array\"}}", isOptional: true, isOverride: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementIpSetReferenceStatement[]? IpSetReferenceStatement
{
get;
set;
}
/// <summary>regex_pattern_set_reference_statement block.</summary>
[JsiiOptional]
[JsiiProperty(name: "regexPatternSetReferenceStatement", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementRegexPatternSetReferenceStatement\"},\"kind\":\"array\"}}", isOptional: true, isOverride: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementRegexPatternSetReferenceStatement[]? RegexPatternSetReferenceStatement
{
get;
set;
}
/// <summary>size_constraint_statement block.</summary>
[JsiiOptional]
[JsiiProperty(name: "sizeConstraintStatement", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementSizeConstraintStatement\"},\"kind\":\"array\"}}", isOptional: true, isOverride: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementSizeConstraintStatement[]? SizeConstraintStatement
{
get;
set;
}
/// <summary>sqli_match_statement block.</summary>
[JsiiOptional]
[JsiiProperty(name: "sqliMatchStatement", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementSqliMatchStatement\"},\"kind\":\"array\"}}", isOptional: true, isOverride: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementSqliMatchStatement[]? SqliMatchStatement
{
get;
set;
}
/// <summary>xss_match_statement block.</summary>
[JsiiOptional]
[JsiiProperty(name: "xssMatchStatement", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatement\"},\"kind\":\"array\"}}", isOptional: true, isOverride: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatement[]? XssMatchStatement
{
get;
set;
}
}
}
| 60.405405 | 306 | 0.733557 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/Wafv2WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatement.cs | 4,470 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/propsys.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
[Guid("380F5CAD-1B5E-42F2-805D-637FD392D31E")]
[NativeTypeName("struct IPropertyChangeArray : IUnknown")]
public unsafe partial struct IPropertyChangeArray
{
public void** lpVtbl;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject)
{
return ((delegate* unmanaged<IPropertyChangeArray*, Guid*, void**, int>)(lpVtbl[0]))((IPropertyChangeArray*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("ULONG")]
public uint AddRef()
{
return ((delegate* unmanaged<IPropertyChangeArray*, uint>)(lpVtbl[1]))((IPropertyChangeArray*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("ULONG")]
public uint Release()
{
return ((delegate* unmanaged<IPropertyChangeArray*, uint>)(lpVtbl[2]))((IPropertyChangeArray*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int GetCount([NativeTypeName("UINT *")] uint* pcOperations)
{
return ((delegate* unmanaged<IPropertyChangeArray*, uint*, int>)(lpVtbl[3]))((IPropertyChangeArray*)Unsafe.AsPointer(ref this), pcOperations);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int GetAt([NativeTypeName("UINT")] uint iIndex, [NativeTypeName("const IID &")] Guid* riid, void** ppv)
{
return ((delegate* unmanaged<IPropertyChangeArray*, uint, Guid*, void**, int>)(lpVtbl[4]))((IPropertyChangeArray*)Unsafe.AsPointer(ref this), iIndex, riid, ppv);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int InsertAt([NativeTypeName("UINT")] uint iIndex, IPropertyChange* ppropChange)
{
return ((delegate* unmanaged<IPropertyChangeArray*, uint, IPropertyChange*, int>)(lpVtbl[5]))((IPropertyChangeArray*)Unsafe.AsPointer(ref this), iIndex, ppropChange);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int Append(IPropertyChange* ppropChange)
{
return ((delegate* unmanaged<IPropertyChangeArray*, IPropertyChange*, int>)(lpVtbl[6]))((IPropertyChangeArray*)Unsafe.AsPointer(ref this), ppropChange);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int AppendOrReplace(IPropertyChange* ppropChange)
{
return ((delegate* unmanaged<IPropertyChangeArray*, IPropertyChange*, int>)(lpVtbl[7]))((IPropertyChangeArray*)Unsafe.AsPointer(ref this), ppropChange);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int RemoveAt([NativeTypeName("UINT")] uint iIndex)
{
return ((delegate* unmanaged<IPropertyChangeArray*, uint, int>)(lpVtbl[8]))((IPropertyChangeArray*)Unsafe.AsPointer(ref this), iIndex);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int IsKeyInArray([NativeTypeName("const PROPERTYKEY &")] PROPERTYKEY* key)
{
return ((delegate* unmanaged<IPropertyChangeArray*, PROPERTYKEY*, int>)(lpVtbl[9]))((IPropertyChangeArray*)Unsafe.AsPointer(ref this), key);
}
}
}
| 46.640449 | 178 | 0.676704 | [
"MIT"
] | manju-summoner/terrafx.interop.windows | sources/Interop/Windows/um/propsys/IPropertyChangeArray.cs | 4,153 | C# |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* 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.
*******************************************************************************/
//
// Novell.Directory.Ldap.LdapMatchingRuleUseSchema.cs
//
// Author:
// Sunil Kumar (Sunilk@novell.com)
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System.IO;
using System.Text;
using Microsoft.Extensions.Logging;
using Novell.Directory.Ldap.Utilclass;
namespace Novell.Directory.Ldap
{
/// <summary>
/// Represents the definition of a specific matching rule use in the
/// directory schema.
/// The LdapMatchingRuleUseSchema class represents the definition of a
/// matching rule use. It is used to discover or modify which attributes are
/// suitable for use with an extensible matching rule. It contains the name and
/// identifier of a matching rule, and a list of attributes which
/// it applies to.
/// </summary>
/// <seealso cref="LdapAttributeSchema">
/// </seealso>
/// <seealso cref="LdapSchemaElement">
/// </seealso>
/// <seealso cref="LdapSchema">
/// </seealso>
public class LdapMatchingRuleUseSchema : LdapSchemaElement
{
/// <summary>
/// Returns an array of all the attributes which this matching rule
/// applies to.
/// </summary>
/// <returns>
/// An array of all the attributes which this matching rule applies to.
/// </returns>
public virtual string[] Attributes
{
get { return attributes; }
}
private readonly string[] attributes;
/// <summary>
/// Constructs a matching rule use definition for adding to or deleting
/// from the schema.
/// </summary>
/// <param name="names">
/// Name(s) of the matching rule.
/// </param>
/// <param name="oid">
/// Object Identifier of the the matching rule
/// in dotted-decimal format.
/// </param>
/// <param name="description">
/// Optional description of the matching rule use.
/// </param>
/// <param name="obsolete">
/// True if the matching rule use is obsolete.
/// </param>
/// <param name="attributes">
/// List of attributes that this matching rule
/// applies to. These values may be either the
/// names or numeric oids of the attributes.
/// </param>
public LdapMatchingRuleUseSchema(string[] names, string oid, string description, bool obsolete,
string[] attributes) : base(LdapSchema.schemaTypeNames[LdapSchema.MATCHING_USE])
{
this.names = new string[names.Length];
names.CopyTo(this.names, 0);
this.oid = oid;
this.description = description;
this.obsolete = obsolete;
this.attributes = new string[attributes.Length];
attributes.CopyTo(this.attributes, 0);
Value = formatString();
}
/// <summary>
/// Constructs a matching rule use definition from the raw string value
/// returned on a schema query for matchingRuleUse.
/// </summary>
/// <param name="raw">
/// The raw string value returned on a schema
/// query for matchingRuleUse.
/// </param>
public LdapMatchingRuleUseSchema(string raw) : base(LdapSchema.schemaTypeNames[LdapSchema.MATCHING_USE])
{
try
{
var matchParser = new SchemaParser(raw);
names = new string[matchParser.Names.Length];
matchParser.Names.CopyTo(names, 0);
oid = matchParser.ID;
description = matchParser.Description;
obsolete = matchParser.Obsolete;
attributes = matchParser.Applies;
Value = formatString();
}
catch (IOException ex)
{
Logger.Log.LogWarning("Exception swallowed", ex);
}
}
/// <summary>
/// Returns a string in a format suitable for directly adding to a
/// directory, as a value of the particular schema element attribute.
/// </summary>
/// <returns>
/// A string representation of the attribute's definition.
/// </returns>
protected internal override string formatString()
{
var valueBuffer = new StringBuilder("( ");
string token;
string[] strArray;
if ((object) (token = ID) != null)
{
valueBuffer.Append(token);
}
strArray = Names;
if (strArray != null)
{
valueBuffer.Append(" NAME ");
if (strArray.Length == 1)
{
valueBuffer.Append("'" + strArray[0] + "'");
}
else
{
valueBuffer.Append("( ");
for (var i = 0; i < strArray.Length; i++)
{
valueBuffer.Append(" '" + strArray[i] + "'");
}
valueBuffer.Append(" )");
}
}
if ((object) (token = Description) != null)
{
valueBuffer.Append(" DESC ");
valueBuffer.Append("'" + token + "'");
}
if (Obsolete)
{
valueBuffer.Append(" OBSOLETE");
}
if ((strArray = Attributes) != null)
{
valueBuffer.Append(" APPLIES ");
if (strArray.Length > 1)
valueBuffer.Append("( ");
for (var i = 0; i < strArray.Length; i++)
{
if (i > 0)
valueBuffer.Append(" $ ");
valueBuffer.Append(strArray[i]);
}
if (strArray.Length > 1)
valueBuffer.Append(" )");
}
valueBuffer.Append(" )");
return valueBuffer.ToString();
}
}
} | 37.94898 | 112 | 0.534149 | [
"MIT"
] | DennisGlindhart/Novell.Directory.Ldap.NETStandard | src/Novell.Directory.Ldap.NETStandard/LdapMatchingRuleUseSchema.cs | 7,438 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[Serializable]
public class PlayerStatistics {
public List<MonsterScriptableObject> squad;
public Dictionary<string, Monster> monstersDict = new Dictionary<string, Monster>();
public float playerSpeed;
public List<ItemData> playerItems;
public bool finishedTutorial = false;
public Vector3 playerPosition;
public NPCBattleWrapper enemyData;
public List<string> defeatedEnemyNames;
// counter and last position
// { "oldman" : (0, Vector3(1f, 3.2f, 1.4f)), "girl" : (1, Vector3(1f, 69.69f, 1.4f)) }
public Dictionary<string, Tuple<int, Vector3>> enemyPathCounter = new Dictionary<string, Tuple<int, Vector3>>();
public GameMode currentGameMode = GameMode.Gameplay;
public void FillBaseValues() {
squad.ForEach(m => monstersDict.Add(m.Name, new Monster(m)));
}
}
| 34.185185 | 116 | 0.717226 | [
"MIT"
] | kodalli/Brackeys-Game-Jam-2021 | Assets/Scripts/Save State/PlayerStatistics.cs | 925 | C# |
using System;
using System.Linq;
using System.Collections.Generic;
namespace _02FeedTheAnimals
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
var animals = new Dictionary<string, int>();
var areasWithHungryAnimals = new Dictionary<string, int>();
while (input != "Last Info")
{
var tokens = input
.Split(":", StringSplitOptions.RemoveEmptyEntries)
.ToArray();
string command = tokens[0];
if(command == "Add")
{
string animalName = tokens[1];
int dailyFoodLimit = int.Parse(tokens[2]);
string area = tokens[3];
if (!animals.ContainsKey(animalName))
{
animals.Add(animalName, dailyFoodLimit);
if (!areasWithHungryAnimals.ContainsKey(area))
{
areasWithHungryAnimals[area] = 1;
}
else
{
areasWithHungryAnimals[area]++;
}
}
else
{
animals[animalName] += dailyFoodLimit;
}
}
else if(command == "Feed")
{
string animalName = tokens[1];
int food = int.Parse(tokens[2]);
string area = tokens[3];
if (animals.ContainsKey(animalName) && areasWithHungryAnimals.ContainsKey(area))
{
animals[animalName] -= food;
if (animals[animalName] <= 0)
{
animals.Remove(animalName);
areasWithHungryAnimals[area]--;
Console.WriteLine($"{animalName} was successfully fed");
}
}
}
input = Console.ReadLine();
}
Console.WriteLine("Animals:");
foreach (var animal in animals.OrderByDescending(x => x.Value).ThenBy(x => x.Key))
{
Console.WriteLine($"{animal.Key} -> {animal.Value}g");
}
Console.WriteLine("Areas with hungry animals:");
foreach (var area in areasWithHungryAnimals.OrderByDescending(x => x.Value).Where(x => x.Value > 0))
{
Console.WriteLine($"{area.Key} : {area.Value}");
}
}
}
}
| 32.197674 | 112 | 0.421091 | [
"MIT"
] | kalintsenkov/SoftUni-Software-Engineering | CSharp-Technology-Fundamentals/Final-Exams/Final-Exam-18-April-2019/02FeedTheAnimals/Program.cs | 2,771 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Calabonga.TemplateProcessor.Wpf
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
| 22.517241 | 45 | 0.719755 | [
"MIT"
] | Calabonga/TemplateProcessor | Calabonga.TemplateProcessor.Wpf/MainWindow.xaml.cs | 655 | C# |
using Dahomey.Cbor;
using Dahomey.Cbor.ObjectModel;
using Dahomey.Cbor.Serialization;
using Dahomey.Cbor.Serialization.Converters;
using System;
using System.Collections.Generic;
using System.Text;
namespace DMNet.SpacemanDMM.AST.Converters
{
class PopConverter : CborConverterBase<Pop>
{
public override Pop Read(ref CborReader reader)
{
ICborConverter<CborObject> conv = new CborValueConverter(new CborOptions());
var cborObject = conv.Read(ref reader);
return ParsePop(cborObject);
}
public static Pop ParsePop(CborValue element)
{
if (element.Type == CborValueType.Null)
return null;
CborObject obj;
if (element is CborObject cobj)
obj = cobj;
else
obj = element.Value<CborObject>();
var p = new List<string>();
foreach (var item in (CborArray)obj["path"])
{
p.Add(item.Value<string>());
}
var pop = new Pop()
{
Path = p.ToArray()
};
var vars = (CborArray)obj["vars"];
foreach (var tuple in vars)
{
var arrTuple = (CborArray)tuple;
pop.Vars[arrTuple[0].Value<string>()] = PolymorphicConstantConverter.ParseConstant(arrTuple[1]);
}
return pop;
}
}
}
| 29.588235 | 113 | 0.528827 | [
"MIT"
] | dm-net/DMNet | src/DMNet.SpacemanDMM/AST/Converters/PopConverter.cs | 1,511 | C# |
using UnityEngine;
using System.Collections;
using RootMotion.FinalIK;
namespace RootMotion.FinalIK
{
/// <summary>
/// Simple VRIK LOD level controller based on renderer.isVisible and camera distance.
/// </summary>
public class VRIKLODController : MonoBehaviour
{
public Renderer LODRenderer;
public float LODDistance = 15f;
public bool allowCulled = true;
private VRIK ik;
void Start()
{
ik = GetComponent<VRIK>();
}
void Update()
{
ik.solver.LOD = GetLODLevel();
}
// Setting LOD level to 1 saves approximately 20% of solving time. LOD level 2 means IK is culled, with only root position and rotation updated if locomotion enabled.
private int GetLODLevel()
{
if (allowCulled)
{
if (LODRenderer == null) return 0;
if (!LODRenderer.isVisible) return 2;
}
// Set LOD to 1 if too far from camera
float sqrMag = (ik.transform.position - Camera.main.transform.position).sqrMagnitude;
if (sqrMag > LODDistance * LODDistance) return 1;
return 0;
}
}
}
| 26.276596 | 174 | 0.579757 | [
"MIT"
] | Adv-Dev-Midterm-Shooter-Team-1/Midterm-Shooter | AGD Midterm Shooter/Assets/Plugins/RootMotion/FinalIK/Tools/VRIKLODController.cs | 1,237 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DQuanLyThuVien_Admin_.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.8.1.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=DESKTOP-7C3I4IA\\SQLEXPRESS;Initial Catalog=QuanLyThuVien;Integrated S" +
"ecurity=True")]
public string QuanLyThuVienConnectionString {
get {
return ((string)(this["QuanLyThuVienConnectionString"]));
}
}
}
}
| 44.894737 | 153 | 0.62544 | [
"Apache-2.0"
] | IMD246/LibraryManagement | QLTV(DOaN)/DQuanLyThuVien(Admin)/Properties/Settings.Designer.cs | 1,708 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TypeLess.Tests
{
[Serializable]
public class SomeException : Exception
{
public SomeException() { }
public SomeException(string message) : base(message) { }
public SomeException(string message, Exception inner) : base(message, inner) { }
protected SomeException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
}
| 29 | 88 | 0.688013 | [
"MIT"
] | jansater/TypeLess | TypeLess.Tests/SomeException.cs | 611 | C# |
//--------------------------------------------------------------------------------------------------
// <copyright file="PlatformsResponseExample.cs" company="Traeger Industry Components GmbH">
// This file is protected by Traeger Industry Components GmbH Copyright © 2019-2020.
// </copyright>
// <author>Timo Walter</author>
//--------------------------------------------------------------------------------------------------
using System.Collections.Generic;
using ReleaseServer.WebApi.Models;
using Swashbuckle.AspNetCore.Filters;
namespace ReleaseServer.WebApi.SwaggerDocu
{
internal class PlatformsResponseExample : IExamplesProvider<PlatformsList>
{
public PlatformsList GetExamples()
{
return new PlatformsList(new List<string>(new[]{"debian-amd64", "debian-arm64"}));
}
}
} | 39.809524 | 100 | 0.551435 | [
"MIT"
] | Traeger-GmbH/release-server | sources/ReleaseServer/ReleaseServer.WebApi/SwaggerDocu/PlatformsResponseExample.cs | 837 | C# |
using SlackConnector.Connections.Models;
using SlackConnector.Models;
namespace SlackConnector.Extensions
{
internal static class UserExtensions
{
public static SlackUser ToSlackUser(this User user)
{
var slackUser = new SlackUser
{
Id = user.Id,
Name = user.Name,
Email = user.Profile?.Email,
TimeZoneOffset = user.TimeZoneOffset,
IsBot = user.IsBot,
FirstName = user.Profile?.FirstName,
LastName = user.Profile?.LastName,
Image = user.Profile?.Image,
WhatIDo = user.Profile?.Title,
Deleted = user.Deleted,
IsGuest = user.IsGuest,
StatusText = user.Profile?.StatusText,
IsAdmin = user.IsAdmin
};
if (!string.IsNullOrWhiteSpace(user.Presence))
{
slackUser.Online = user.Presence == "active";
}
return slackUser;
}
}
} | 30.428571 | 61 | 0.519249 | [
"MIT"
] | danieljoos/SlackConnector | src/SlackConnector/Extensions/UserExtensions.cs | 1,067 | 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.ContainerRegistry
{
public static class GetWebhook
{
/// <summary>
/// An object that represents a webhook for a container registry.
/// API Version: 2019-05-01.
/// </summary>
public static Task<GetWebhookResult> InvokeAsync(GetWebhookArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetWebhookResult>("azure-native:containerregistry:getWebhook", args ?? new GetWebhookArgs(), options.WithVersion());
}
public sealed class GetWebhookArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the container registry.
/// </summary>
[Input("registryName", required: true)]
public string RegistryName { get; set; } = null!;
/// <summary>
/// The name of the resource group to which the container registry belongs.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
/// <summary>
/// The name of the webhook.
/// </summary>
[Input("webhookName", required: true)]
public string WebhookName { get; set; } = null!;
public GetWebhookArgs()
{
}
}
[OutputType]
public sealed class GetWebhookResult
{
/// <summary>
/// The list of actions that trigger the webhook to post notifications.
/// </summary>
public readonly ImmutableArray<string> Actions;
/// <summary>
/// The resource ID.
/// </summary>
public readonly string Id;
/// <summary>
/// The location of the resource. This cannot be changed after the resource is created.
/// </summary>
public readonly string Location;
/// <summary>
/// The name of the resource.
/// </summary>
public readonly string Name;
/// <summary>
/// The provisioning state of the webhook at the time the operation was called.
/// </summary>
public readonly string ProvisioningState;
/// <summary>
/// The scope of repositories where the event can be triggered. For example, 'foo:*' means events for all tags under repository 'foo'. 'foo:bar' means events for 'foo:bar' only. 'foo' is equivalent to 'foo:latest'. Empty means all events.
/// </summary>
public readonly string? Scope;
/// <summary>
/// The status of the webhook at the time the operation was called.
/// </summary>
public readonly string? Status;
/// <summary>
/// The tags of the resource.
/// </summary>
public readonly ImmutableDictionary<string, string>? Tags;
/// <summary>
/// The type of the resource.
/// </summary>
public readonly string Type;
[OutputConstructor]
private GetWebhookResult(
ImmutableArray<string> actions,
string id,
string location,
string name,
string provisioningState,
string? scope,
string? status,
ImmutableDictionary<string, string>? tags,
string type)
{
Actions = actions;
Id = id;
Location = location;
Name = name;
ProvisioningState = provisioningState;
Scope = scope;
Status = status;
Tags = tags;
Type = type;
}
}
}
| 31.834711 | 246 | 0.581256 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/ContainerRegistry/GetWebhook.cs | 3,852 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the autoscaling-2011-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AutoScaling.Model
{
/// <summary>
/// This is the response object from the StartInstanceRefresh operation.
/// </summary>
public partial class StartInstanceRefreshResponse : AmazonWebServiceResponse
{
private string _instanceRefreshId;
/// <summary>
/// Gets and sets the property InstanceRefreshId.
/// <para>
/// A unique ID for tracking the progress of the request.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=255)]
public string InstanceRefreshId
{
get { return this._instanceRefreshId; }
set { this._instanceRefreshId = value; }
}
// Check to see if InstanceRefreshId property is set
internal bool IsSetInstanceRefreshId()
{
return this._instanceRefreshId != null;
}
}
} | 30.482759 | 109 | 0.671946 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/AutoScaling/Generated/Model/StartInstanceRefreshResponse.cs | 1,768 | C# |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2020
//
// 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 was automatically generated and should not be edited directly.
using System;
using System.Runtime.InteropServices;
namespace SharpVk.Interop
{
/// <summary>
///
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public unsafe partial struct ImageStencilUsageCreateInfo
{
/// <summary>
/// The type of this structure.
/// </summary>
public SharpVk.StructureType SType;
/// <summary>
/// Null or an extension-specific structure.
/// </summary>
public void* Next;
/// <summary>
///
/// </summary>
public SharpVk.ImageUsageFlags StencilUsage;
}
}
| 35.903846 | 81 | 0.692019 | [
"MIT"
] | FacticiusVir/SharpVk | src/SharpVk/Interop/ImageStencilUsageCreateInfo.gen.cs | 1,867 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace MIConvexHull
{
public static class ConvexHull
{
public static ConvexHull<TVertex, TFace> Create<TVertex, TFace>(IList<TVertex> data, double PlaneDistanceTolerance = 1E-10) where TVertex : IVertex where TFace : ConvexFace<TVertex, TFace>, new()
{
return ConvexHull<TVertex, TFace>.Create(data, PlaneDistanceTolerance);
}
public static ConvexHull<TVertex, DefaultConvexFace<TVertex>> Create<TVertex>(IList<TVertex> data, double PlaneDistanceTolerance = 1E-10) where TVertex : IVertex
{
return ConvexHull<TVertex, DefaultConvexFace<TVertex>>.Create(data, PlaneDistanceTolerance);
}
public static ConvexHull<DefaultVertex, DefaultConvexFace<DefaultVertex>> Create(IList<double[]> data, double PlaneDistanceTolerance = 1E-10)
{
return ConvexHull<DefaultVertex, DefaultConvexFace<DefaultVertex>>.Create(data.Select((double[] p) => new DefaultVertex
{
Position = p
}).ToList(), PlaneDistanceTolerance);
}
}
public class ConvexHull<TVertex, TFace> where TVertex : IVertex where TFace : ConvexFace<TVertex, TFace>, new()
{
public IEnumerable<TVertex> Points { get; internal set; }
public IEnumerable<TFace> Faces { get; internal set; }
internal ConvexHull()
{
}
public static ConvexHull<TVertex, TFace> Create(IList<TVertex> data, double PlaneDistanceTolerance)
{
if (data == null)
{
throw new ArgumentNullException("The supplied data is null.");
}
return ConvexHullAlgorithm.GetConvexHull<TVertex, TFace>(data, PlaneDistanceTolerance);
}
}
}
| 33.87234 | 197 | 0.748744 | [
"MIT"
] | undancer/oni-data | Managed/firstpass/MIConvexHull/ConvexHull.cs | 1,592 | C# |
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace allpet.http.server
{
public interface IController
{
Task ProcessAsync(HttpContext context);
}
}
| 18.428571 | 47 | 0.748062 | [
"MIT"
] | allpet-project/allpet.http | httpserver/IController.cs | 260 | C# |
using PersonalSpendingAnalysis.Repo;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Globalization;
using System;
using System.Diagnostics;
using System.IO;
using PdfSharp;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using PdfSharp.Drawing.Layout;
using System.Threading;
namespace PersonalSpendingAnalysis.Dialogs
{
public partial class Reports : Form
{
public Reports()
{
InitializeComponent();
}
class SortableTreeNode
{
public TreeNode treeNode { get; set; }
public Decimal? value { get; set; }
}
private void runReport()
{
treeView.Nodes.Clear();
var yearList = new List<float>();
for (var loopYear = this.startDate.Value.Year; loopYear <= this.endDate.Value.Year; loopYear++)
yearList.Add(loopYear);
var context = new PersonalSpendingAnalysisRepo();
var transactions = context.Transaction.Include("Category")
.Where(x => (x.transactionDate > this.startDate.Value)
&& (x.transactionDate < this.endDate.Value)
);
var categories = transactions
.GroupBy(x => new { CategoryName = x.Category.Name })
.Select(x => new
{
CategoryName = x.Key.CategoryName,
Amount = x.Sum(y => y.amount)
}).OrderByDescending(x => x.Amount)
.ToList();
var count = 0;
foreach (var category in categories)
{
count++;
decimal percent = (decimal)count / (decimal)transactions.Count();
UpdateProgressBar(percent);
var node = new TreeNode(category.CategoryName + " = " + category.Amount);
foreach (var year in yearList)
{
var value = transactions.Where(x => x.Category.Name == category.CategoryName && x.transactionDate.Year == year).Sum(x => (Decimal?)x.amount);
decimal? permonth = (value / 12.0m);
var yearNode = new TreeNode(year + " = " + value + (permonth==null?"":" (per month = " + ((decimal)permonth).ToString("#.##") + " ) ") );
var searchStrings = context.Categories.First(x => x.Name == category.CategoryName).SearchString + ",manually assigned";
var subCategories = new List<SortableTreeNode>();
foreach (var searchString in searchStrings.Split(',').ToList())
{
var subCatValue = transactions
.Where(x => x.Category.Name == category.CategoryName && x.transactionDate.Year == year && x.SubCategory == searchString)
.Sum(x => (Decimal?)x.amount);
var subCategoryNode = new TreeNode(searchString + " " + subCatValue);
var transactionsInSubcategory = transactions
.Where(x => x.Category.Name == category.CategoryName && x.transactionDate.Year == year && x.SubCategory == searchString).ToArray();
foreach (var transaction in transactionsInSubcategory)
{
var transactionString = transaction.transactionDate.ToShortDateString() + " " + transaction.Notes + " " + transaction.amount;
var transactionNode = new TreeNode(transactionString);
subCategoryNode.Nodes.Add(transactionNode);
}
subCategories.Add(new SortableTreeNode { treeNode = subCategoryNode, value = subCatValue });
}
foreach (var subCategory in subCategories.OrderBy(x => x.value))
{
if (subCategory.treeNode.Nodes.Count > 0)
yearNode.Nodes.Add(subCategory.treeNode);
}
node.Nodes.Add(yearNode);
}
treeView.Nodes.Add(node);
}
buttonReport.Enabled = true;
buttonExportPdf.Enabled = true;
}
private void UpdateProgressBar(decimal percent)
{
progressBar1.Value = (int)percent;
if (percent==100.0m)
{
progressBar1.Visible = false;
}
}
private void buttonReport_Click(object sender, EventArgs e)
{
progressBar1.Visible = true;
buttonReport.Enabled = false;
buttonExportPdf.Enabled = false;
//Thread thread = new Thread(runReport);
//thread.IsBackground = true;
//thread.Start();
//need to separate work from GUI for this.
runReport();
}
private void Reports_Load(object sender, EventArgs e)
{
progressBar1.Visible = false;
var context = new PersonalSpendingAnalysisRepo();
var startDate = context.Transaction.Min(x => x.transactionDate);
this.endDate.Value = DateTime.Today;
this.startDate.Value = startDate;
}
private void buttonExportPdf_Click(object sender, EventArgs e)
{
var exportPdfDlg = new SaveFileDialog();
exportPdfDlg.Filter = "PDF Files | *.pdf";
exportPdfDlg.Title = "Enter name of PDF File to export";
DialogResult result = exportPdfDlg.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
makePdf(treeView.Nodes, exportPdfDlg.FileName);
}
}
private void makePdf(TreeNodeCollection nodes, string filename)
{
List<string> s = new List<string>();
string spaces = "";
int indentLevel = 0;
int maxIndentLevel = 5;
var includeTransactions = this.includeTransactions.Checked;
if (!includeTransactions)
{
maxIndentLevel = 2;
}
walkTree(nodes, spaces, ref s, indentLevel, maxIndentLevel);
var pagesize = 70;
var numberOfPages = (int)(s.Count / pagesize) +1;
PdfDocument document = new PdfDocument();
XFont categoryfont = new XFont("Arial", 8, XFontStyle.Bold);
XFont yearfont = new XFont("Arial", 8, XFontStyle.Underline);
XFont font = new XFont("Arial", 8, XFontStyle.Regular);
for (var pageNum = 0; pageNum < numberOfPages; pageNum++)
{
var numberOfRows = pagesize;
if (((pageNum * pagesize)+ pagesize) > s.Count)
numberOfRows = s.Count % pagesize;
string text = String.Join("\r\n", s.GetRange(pageNum* pagesize, numberOfRows));
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XTextFormatter tf = new XTextFormatter(gfx);
XRect rect = new XRect(20, 50, 550, 850);
gfx.DrawRectangle(XBrushes.White, rect);
tf.Alignment = XParagraphAlignment.Left;
tf.DrawString(text, font, XBrushes.Black, rect, XStringFormats.TopLeft);
}
document.Save(filename);
Process.Start(filename);
}
const String indent = " ";
private void walkTree(TreeNodeCollection nodes, string spaces, ref List<string> s, int indentLevel, int maxIndentLevel)
{
spaces = spaces + indent;
indentLevel++;
foreach(TreeNode node in nodes)
{
s.Add(spaces+node.Text);
if (node.Nodes.Count>0 && indentLevel<=maxIndentLevel)
walkTree(node.Nodes, spaces, ref s, indentLevel, maxIndentLevel);
}
}
}
}
| 36.246753 | 161 | 0.539472 | [
"MIT"
] | hipparchus2000/PersonalSpendingAnalysis | PersonalSpendingAnalysis/Dialogs/Reports.cs | 8,375 | C# |
// Copyright (c) 2022 .NET Foundation and Contributors. All rights reserved.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.
using System;
namespace ReactiveUI.Fody.Helpers;
/// <summary>
/// Attribute that marks a property as a Reactive Dependency.
/// </summary>
/// <seealso cref="System.Attribute" />
[AttributeUsage(AttributeTargets.Property)]
public sealed class ReactiveDependencyAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveDependencyAttribute"/> class.
/// </summary>
/// <param name="targetName">Name of the target.</param>
public ReactiveDependencyAttribute(string targetName) => Target = targetName;
/// <summary>
/// Gets the name of the backing property.
/// </summary>
public string Target { get; }
/// <summary>
/// Gets or sets the target property on the backing property.
/// </summary>
public string? TargetProperty { get; set; }
}
| 34 | 90 | 0.700535 | [
"MIT"
] | Awsmolak/ReactiveUI | src/ReactiveUI.Fody.Helpers/ReactiveDependencyAttribute.cs | 1,124 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using Inedo.Agents;
using Inedo.BuildMaster.Extensibility.Agents;
using Inedo.BuildMaster.Extensibility.IssueTrackerConnections;
using Inedo.BuildMaster.Extensibility.Providers;
using Inedo.BuildMaster.Web;
using Inedo.BuildMasterExtensions.TFS.Providers;
using Inedo.Documentation;
using Inedo.Serialization;
namespace Inedo.BuildMasterExtensions.TFS
{
[DisplayName("Team Foundation Server")]
[Description("Supports TFS 2010-2015.")]
[CustomEditor(typeof(TfsIssueTrackingProviderEditor))]
public sealed partial class TfsIssueTrackingProvider : IssueTrackerConnectionBase, IIssueStatusUpdater, IIssueCloser
{
/// <summary>
/// The base URL of the TFS store, should include collection name, e.g. "http://server:port/tfs"
/// </summary>
[Persistent]
public string BaseUrl { get; set; }
/// <summary>
/// Indicates the full name of the custom field that contains the release number associated with the work item
/// </summary>
[Persistent]
public string CustomReleaseNumberFieldName { get; set; }
/// <summary>
/// The username used to connect to the server
/// </summary>
[Persistent]
public string UserName { get; set; }
/// <summary>
/// The password used to connect to the server
/// </summary>
[Persistent]
public string Password { get; set; }
/// <summary>
/// The domain of the server
/// </summary>
[Persistent]
public string Domain { get; set; }
/// <summary>
/// Returns true if BuildMaster should connect to TFS using its own account, false if the credentials are specified
/// </summary>
[Persistent]
public bool UseSystemCredentials { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to allow HTML issue descriptions.
/// </summary>
[Persistent]
public bool AllowHtmlIssueDescriptions { get; set; }
[Persistent]
public string CustomWiql { get; set; }
[Persistent]
public string[] CustomClosedStates { get; set; }
public override RichDescription GetDescription()
{
return new RichDescription(
"TFS at ",
new Hilite(this.BaseUrl)
);
}
public override IssueTrackerApplicationConfigurationBase GetDefaultApplicationConfiguration(int applicationId)
{
return this.legacyFilter ?? new TfsIssueTrackingApplicationFilter();
}
public override IEnumerable<IIssueTrackerIssue> EnumerateIssues(IssueTrackerConnectionContext context)
{
if (context == null)
throw new ArgumentNullException("context");
var remote = this.GetRemote();
var wiql = this.GetWiql(context);
var remoteAgent = this.Agent.GetService<IRemoteMethodExecuter>();
var filter = (TfsIssueTrackingApplicationFilter)context.ApplicationConfiguration ?? this.legacyFilter;
string iteration = null;
if (string.IsNullOrWhiteSpace(this.CustomReleaseNumberFieldName) && string.IsNullOrWhiteSpace(this.CustomWiql) && string.IsNullOrWhiteSpace(filter.CustomWiql))
iteration = context.ReleaseNumber;
var issues = remoteAgent.InvokeFunc(remote.GetIssues, filter.CollectionId, filter.CollectionName, wiql, iteration);
foreach (var issue in issues)
issue.RenderAsHtml = this.AllowHtmlIssueDescriptions;
return issues;
}
internal TfsCollectionInfo[] GetCollections()
{
var remote = this.GetRemote();
var remoteAgent = this.Agent.GetService<IRemoteMethodExecuter>();
return remoteAgent.InvokeFunc(remote.GetCollections);
}
internal TfsProjectInfo[] GetProjects(Guid collectionId)
{
var remote = this.GetRemote();
var remoteAgent = this.Agent.GetService<IRemoteMethodExecuter>();
return remoteAgent.InvokeFunc(remote.GetProjects, (Guid?)collectionId, (string)null);
}
internal TfsAreaInfo[] GetAreas(Guid collectionId, string projectName)
{
var remote = this.GetRemote();
var remoteAgent = this.Agent.GetService<IRemoteMethodExecuter>();
return remoteAgent.InvokeFunc(remote.GetAreas, (Guid?)collectionId, (string)null, projectName);
}
private string GetWiql(IssueTrackerConnectionContext context)
{
if (!string.IsNullOrWhiteSpace(this.CustomWiql))
return this.CustomWiql;
var filter = (TfsIssueTrackingApplicationFilter)context.ApplicationConfiguration ?? this.legacyFilter;
if (!string.IsNullOrWhiteSpace(filter.CustomWiql))
return filter.CustomWiql;
var buffer = new StringBuilder();
buffer.Append("SELECT [System.ID] FROM WorkItems WHERE [System.TeamProject] = '");
buffer.Append(filter.ProjectName.Replace("'", "''"));
buffer.Append('\'');
if (!string.IsNullOrWhiteSpace(filter.AreaPath))
{
buffer.Append(" AND [System.AreaPath] under '");
buffer.Append(filter.ProjectName.Replace("'", "''"));
buffer.Append('\\');
buffer.Append(filter.AreaPath.Replace("'", "''"));
buffer.Append('\'');
}
if (!string.IsNullOrWhiteSpace(context.ReleaseNumber) && !string.IsNullOrWhiteSpace(this.CustomReleaseNumberFieldName))
{
buffer.Append(" AND [");
buffer.Append(this.CustomReleaseNumberFieldName);
buffer.Append("] = '");
buffer.Append(context.ReleaseNumber.Replace("'", "''"));
buffer.Append('\'');
}
return buffer.ToString();
}
private RemoteTfs GetRemote()
{
return new RemoteTfs
{
BaseUrl = this.BaseUrl,
UserName = this.UserName,
Password = this.Password,
Domain = this.Domain,
UseSystemCredentials = this.UseSystemCredentials,
CustomClosedStates = this.CustomClosedStates
};
}
public override bool IsAvailable()
{
try
{
return this.Agent.GetService<IRemoteMethodExecuter>().InvokeFunc(RemoteTfs.IsAvailable);
}
catch
{
return false;
}
}
public override void ValidateConnection()
{
try
{
var remote = this.GetRemote();
this.Agent.GetService<IRemoteMethodExecuter>().InvokeFunc(remote.GetCollections);
}
catch (Exception ex)
{
throw new NotAvailableException(ex.Message, ex);
}
}
void IIssueStatusUpdater.ChangeIssueStatus(IssueTrackerConnectionContext context, string issueId, string issueStatus)
{
if (context == null)
throw new ArgumentNullException("context");
if (string.IsNullOrWhiteSpace(issueId))
throw new ArgumentNullException("issueId");
var remote = this.GetRemote();
var remoteAgent = this.Agent.GetService<IRemoteMethodExecuter>();
var filter = (TfsIssueTrackingApplicationFilter)context.ApplicationConfiguration ?? this.legacyFilter;
remoteAgent.InvokeAction(remote.ChangeIssueState, filter.CollectionId, filter.CollectionName, int.Parse(issueId), issueStatus);
}
void IIssueStatusUpdater.ChangeStatusForAllIssues(IssueTrackerConnectionContext context, string fromStatus, string toStatus)
{
if (context == null)
throw new ArgumentNullException("context");
var remote = this.GetRemote();
var wiql = this.GetWiql(context);
var remoteAgent = this.Agent.GetService<IRemoteMethodExecuter>();
var filter = (TfsIssueTrackingApplicationFilter)context.ApplicationConfiguration ?? this.legacyFilter;
remoteAgent.InvokeMethod(new Action<Guid?, string, string, string, string>(remote.ChangeIssueStates), filter.CollectionId, filter.CollectionName, wiql, fromStatus, toStatus);
}
void IIssueCloser.CloseIssue(IssueTrackerConnectionContext context, string issueId)
{
((IIssueStatusUpdater)this).ChangeIssueStatus(context, issueId, "Closed");
}
void IIssueCloser.CloseAllIssues(IssueTrackerConnectionContext context)
{
var closer = (IIssueCloser)this;
foreach (var issue in this.EnumerateIssues(context))
{
if (!issue.IsClosed)
{
this.LogDebug("Closing issue {0}...", issue.Id);
closer.CloseIssue(context, issue.Id);
}
}
}
}
}
| 40.845494 | 187 | 0.595251 | [
"Unlicense"
] | eccsolutions/inedox-tfs | TFS/BuildMasterExtension/Legacy/Providers/TfsIssueTrackingProvider.cs | 9,519 | C# |
using System;
using System.Globalization;
using System.Windows.Data;
namespace DrawWiz
{
public class EnumConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (value == null || parameter == null)
return false;
string checkValue = value.ToString();
string targetValue = parameter.ToString();
return checkValue.Equals(targetValue,
StringComparison.InvariantCultureIgnoreCase);
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (value == null || parameter == null)
return null;
bool useValue = (bool)value;
string targetValue = parameter.ToString();
if (useValue)
return Enum.Parse(targetType, targetValue);
return null;
}
}
}
| 30.444444 | 73 | 0.536496 | [
"MIT"
] | sjr213/MathWiz | DrawWiz/EnumConverter.cs | 1,098 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
namespace Editorsk
{
internal class SortLinesCommand : BaseCommand<SortLinesCommand>
{
private delegate void Replacement(Direction direction);
protected override void SetupCommands()
{
var cmdAsc = new CommandID(PackageGuids.guidLinesCmdSet, PackageIds.cmdSortAsc);
RegisterCommand(cmdAsc, () => Execute(Direction.Ascending));
var cmdDesc = new CommandID(PackageGuids.guidLinesCmdSet, PackageIds.cmdSortDesc);
RegisterCommand(cmdDesc, () => Execute(Direction.Descending));
}
private void Execute(Direction direction)
{
ThreadHelper.ThrowIfNotOnUIThread();
try
{
TextDocument document = GetTextDocument();
IEnumerable<string> lines = GetSelectedLines(document);
string result = SortLines(direction, lines);
if (result == document.Selection.Text)
return;
using (UndoContext("Sort Selected Lines"))
{
document.Selection.Insert(result, 0);
}
}
catch (Exception ex)
{
Logger.Log(ex);
}
}
private string SortLines(Direction direction, IEnumerable<string> lines)
{
if (direction == Direction.Ascending)
lines = lines.OrderBy(t => t);
else
lines = lines.OrderByDescending(t => t);
return string.Join(Environment.NewLine, lines);
}
}
public enum Direction
{
Ascending,
Descending
}
}
| 28.107692 | 94 | 0.573071 | [
"Apache-2.0"
] | madskristensen/Editorsk | src/Commands/SortLinesCommand.cs | 1,827 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
namespace Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime
{
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using static Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Extensions;
public class RestException : Exception, IDisposable
{
public System.Net.HttpStatusCode StatusCode { get; set; }
public string Code { get; protected set; }
protected string message;
public HttpRequestMessage RequestMessage { get; protected set; }
public HttpResponseHeaders ResponseHeaders { get; protected set; }
public string ResponseBody { get; protected set; }
public string ClientRequestId { get; protected set; }
public string RequestId { get; protected set; }
public override string Message => message;
public string Action { get; protected set; }
public RestException(System.Net.Http.HttpResponseMessage response)
{
StatusCode = response.StatusCode;
//CloneWithContent will not work here since the content is disposed after sendAsync
//Besides, it seems there is no need for the request content cloned here.
RequestMessage = response.RequestMessage.Clone();
ResponseBody = response.Content.ReadAsStringAsync().Result;
ResponseHeaders = response.Headers;
RequestId = response.GetFirstHeader("x-ms-request-id");
ClientRequestId = response.GetFirstHeader("x-ms-client-request-id");
try
{
// try to parse the body as JSON, and see if a code and message are in there.
var json = Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonObject;
// see if there is an error block in the body
json = json.Property("error") ?? json;
{ Code = If(json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonString>("code"), out var c) ? (string)c : (string)StatusCode.ToString(); }
{ message = If(json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonString>("message"), out var m) ? (string)m : (string)Message; }
{ Action = If(json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json.JsonString>("action"), out var a) ? (string)a : (string)Action; }
}
#if DEBUG
catch (System.Exception E)
{
System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}");
}
#else
catch
{
// couldn't get the code/message from the body response.
// we'll create one below.
}
#endif
if (string.IsNullOrEmpty(message))
{
if (StatusCode >= System.Net.HttpStatusCode.BadRequest && StatusCode < System.Net.HttpStatusCode.InternalServerError)
{
message = $"The server responded with a Request Error, Status: {StatusCode}";
}
else if (StatusCode >= System.Net.HttpStatusCode.InternalServerError)
{
message = $"The server responded with a Server Error, Status: {StatusCode}";
}
else
{
message = $"The server responded with an unrecognized response, Status: {StatusCode}";
}
}
}
public void Dispose()
{
((IDisposable)RequestMessage).Dispose();
}
}
public class RestException<T> : RestException
{
public T Error { get; protected set; }
public RestException(System.Net.Http.HttpResponseMessage response, T error) : base(response)
{
Error = error;
}
}
public class UndeclaredResponseException : RestException
{
public UndeclaredResponseException(System.Net.Http.HttpResponseMessage response) : base(response)
{
}
}
} | 43.980769 | 179 | 0.573459 | [
"MIT"
] | Arsasana/azure-powershell | src/MySql/generated/runtime/UndeclaredResponseException.cs | 4,471 | C# |
/****************************************************************************
*
* Copyright (c) 2020 CRI Middleware Co., Ltd.
*
****************************************************************************/
using UnityEngine;
/**
* \addtogroup CRIATOM_UNITY_COMPONENT
* @{
*/
/**
* <summary>3Dリージョンコンポーネント</summary>
* <remarks>
* <para header='説明'>3D音源、3Dリスナー及びトランシーバーに対して空間によるグループ化を行うコンポーネントです。<br/>
* 任意のGameObjectに付加して使用します。<br/>
* CriAtomSource 、 CriAtomListener 、 CriAtomTransceiver のregion3dの値、<br/>
* または初期のリージョン設定として設定できます。<br/>
* 本コンポーネントは一つのGameObjectに一つのみ取り付けられます。</para>
* </remarks>
* <seealso cref='CriAtomSource'/>
* <seealso cref='CriAtomListener'/>
* <seealso cref='CriAtomTransceiver'/>
*/
[AddComponentMenu("CRIWARE/CRI Atom Region"), DisallowMultipleComponent]
public class CriAtomRegion : CriMonoBehaviour
{
#region Fields & Properties
/**
* <summary>内部で使用している CriAtomEx3dRegion です。</summary>
* <remarks>
* <para header='説明'>CriAtomEx3dRegion を直接制御する場合にはこのプロパティから CriAtomEx3dRegion を取得してください。</para>
* </remarks>
*/
public CriAtomEx3dRegion region3dHn { get; protected set; }
#endregion
#region Methods
private void Awake()
{
this.InternalInitialize();
}
protected override void OnEnable()
{
base.OnEnable();
this.InitializeParameters();
}
private void OnDestroy()
{
this.InternalFinalize();
}
protected virtual void InternalInitialize()
{
CriAtomPlugin.InitializeLibrary();
this.region3dHn = new CriAtomEx3dRegion();
}
protected virtual void InternalFinalize()
{
region3dHn.Dispose();
region3dHn = null;
CriAtomPlugin.FinalizeLibrary();
}
protected virtual void InitializeParameters()
{
if (this.region3dHn == null) {
Debug.LogError("[CRIWARE] Internal: CriAtomEx3dRegion is not created correctly.", this);
return;
}
}
public override void CriInternalUpdate() { }
public override void CriInternalLateUpdate() { }
#endregion
} // end of class
/** @} */
/* end of file */ | 23.590909 | 97 | 0.632948 | [
"MIT"
] | smpny7/VIVACE | Assets/Plugins/CriWare/CriAtom/CriAtomRegion.cs | 2,418 | C# |
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org)
// Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net)
// Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// See the LICENSE.md file in the project root for full license information.
using System.Runtime.CompilerServices;
// Make internals Stride.Framework.visible to all Stride.Framework.assemblies
[assembly: InternalsVisibleTo("Stride.Core.IO" + Stride.PublicKeys.Default)]
[assembly: InternalsVisibleTo("Stride.Core.Assets" + Stride.PublicKeys.Default)]
[assembly: InternalsVisibleTo("Stride" + Stride.PublicKeys.Default)]
[assembly: InternalsVisibleTo("Stride.UI" + Stride.PublicKeys.Default)]
[assembly: InternalsVisibleTo("Stride.Engine" + Stride.PublicKeys.Default)]
[assembly: InternalsVisibleTo("Stride.Rendering" + Stride.PublicKeys.Default)]
[assembly: InternalsVisibleTo("Stride.Graphics" + Stride.PublicKeys.Default)]
[assembly: InternalsVisibleTo("Stride.Games" + Stride.PublicKeys.Default)]
[assembly: InternalsVisibleTo("Stride.Audio" + Stride.PublicKeys.Default)]
[assembly: InternalsVisibleTo("Stride.Video" + Stride.PublicKeys.Default)]
[assembly: InternalsVisibleTo("Stride.Core.Tests" + Stride.PublicKeys.Default)]
| 63.7 | 81 | 0.791994 | [
"MIT"
] | Ethereal77/stride | sources/core/Stride.Core/Properties/AssemblyInfo.cs | 1,274 | C# |
/*
* Signals API
*
* Collection of endpoints for providing Signal Events, Definitions and Metadata
*
* The version of the OpenAPI document: 2.4.0
* Contact: signals.api@factset.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
namespace FactSet.SDK.Signals.Client
{
/// <summary>
/// Http methods supported by swagger
/// </summary>
public enum HttpMethod
{
/// <summary>HTTP GET request.</summary>
Get,
/// <summary>HTTP POST request.</summary>
Post,
/// <summary>HTTP PUT request.</summary>
Put,
/// <summary>HTTP DELETE request.</summary>
Delete,
/// <summary>HTTP HEAD request.</summary>
Head,
/// <summary>HTTP OPTIONS request.</summary>
Options,
/// <summary>HTTP PATCH request.</summary>
Patch
}
}
| 25.085714 | 80 | 0.600228 | [
"Apache-2.0"
] | factset/enterprise-sdk | code/dotnet/Signals/v2/src/FactSet.SDK.Signals/Client/HttpMethod.cs | 878 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Teamer.Models
{
public class Team
{
public string Name { get; set; }
public string Leader { get; set; }
public ICollection<Project> Projects { get; set; }
public ICollection<User> Members { get; set; }
}
}
| 19.05 | 58 | 0.653543 | [
"Apache-2.0"
] | Windows-Applications-Captain-Cold/Mobile-Food-Ordering | EatFast/EatFast/Models/Team.cs | 383 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Analyzer.Utilities
{
internal static class WellKnownTypeNames
{
public const string SystemAppContext = "System.AppContext";
public const string SystemNetSecurityProtocolType = "System.Net.SecurityProtocolType";
public const string SystemWebMvcValidateInputAttribute = "System.Web.Mvc.ValidateInputAttribute";
public const string SystemWebHttpRequest = "System.Web.HttpRequest";
public const string SystemDataIDataAdapter = "System.Data.IDataAdapter";
public const string SystemDataIDbCommand = "System.Data.IDbCommand";
public const string SystemException = "System.Exception";
public const string SystemSystemException = "System.SystemException";
public const string SystemDiagnosticContractsContract = "System.Diagnostics.Contracts.Contract";
public const string SystemIDisposable = "System.IDisposable";
public const string SystemIAsyncDisposable = "System.IAsyncDisposable";
public const string SystemThreadingMonitor = "System.Threading.Monitor";
public const string SystemThreadingTasksTask = "System.Threading.Tasks.Task";
public const string SystemThreadingTasksGenericTask = "System.Threading.Tasks.Task`1";
public const string SystemThreadingTasksValueTask = "System.Threading.Tasks.ValueTask";
public const string SystemCollectionsICollection = "System.Collections.ICollection";
public const string SystemRuntimeSerializationSerializationInfo = "System.Runtime.Serialization.SerializationInfo";
public const string SystemIEquatable1 = "System.IEquatable`1";
public const string SystemWebUIWebControlsSqlDataSource = "System.Web.UI.WebControls.SqlDataSource";
public const string SystemDataSqlClientSqlParameter = "System.Data.SqlClient.SqlParameter";
public const string SystemDataOleDbOleDbParameter = "System.Data.OleDb.OleDbParameter";
public const string SystemDataOdbcOdbcParameter = "System.Data.Odbc.OdbcParameter";
public const string SystemBoolean = "System.Boolean";
public const string SystemByte = "System.Byte";
public const string SystemChar = "System.Char";
public const string SystemDateTime = "System.DateTime";
public const string SystemDecimal = "System.Decimal";
public const string SystemDouble = "System.Double";
public const string SystemGlobalizationTimeSpanParse = "System.Globalization.TimeSpanParse";
public const string SystemGuid = "System.Guid";
public const string SystemInt16 = "System.Int16";
public const string SystemInt32 = "System.Int32";
public const string SystemInt64 = "System.Int64";
public const string SystemNumber = "System.Number";
public const string SystemSingle = "System.Single";
public const string SystemTimeSpan = "System.TimeSpan";
public const string SystemWebHttpCookie = "System.Web.HttpCookie";
public const string SystemWebHttpRequestBase = "System.Web.HttpRequestBase";
public const string SystemWebHttpRequestWrapper = "System.Web.HttpRequestWrapper";
public const string SystemWebUIAdaptersPageAdapter = "System.Web.UI.Adapters.PageAdapter";
public const string SystemWebUIDataBoundLiteralControl = "System.Web.UI.DataBoundLiteralControl";
public const string SystemWebUIDesignerDataBoundLiteralControl = "System.Web.UI.DesignerDataBoundLiteralControl";
public const string SystemWebUIHtmlControlsHtmlInputControl = "System.Web.UI.HtmlControls.HtmlInputControl";
public const string SystemWebUIHtmlControlsHtmlInputFile = "System.Web.UI.HtmlControls.HtmlInputFile";
public const string SystemWebUIHtmlControlsHtmlInputRadioButton = "System.Web.UI.HtmlControls.HtmlInputRadioButton";
public const string SystemWebUIHtmlControlsHtmlInputText = "System.Web.UI.HtmlControls.HtmlInputText";
public const string SystemWebUIHtmlControlsHtmlSelect = "System.Web.UI.HtmlControls.HtmlSelect";
public const string SystemWebUIHtmlControlsHtmlTextArea = "System.Web.UI.HtmlControls.HtmlTextArea";
public const string SystemWebUIHtmlControlsHtmlTitle = "System.Web.UI.HtmlControls.HtmlTitle";
public const string SystemWebUIHtmlTextWriter = "System.Web.UI.HtmlTextWriter";
public const string SystemWebUIIndexedString = "System.Web.UI.IndexedString";
public const string SystemWebUILiteralControl = "System.Web.UI.LiteralControl";
public const string SystemWebUIResourceBasedLiteralControl = "System.Web.UI.ResourceBasedLiteralControl";
public const string SystemWebUISimplePropertyEntry = "System.Web.UI.SimplePropertyEntry";
public const string SystemWebUIStateItem = "System.Web.UI.StateItem";
public const string SystemWebUIStringPropertyBuilder = "System.Web.UI.StringPropertyBuilder";
public const string SystemWebUITemplateBuilder = "System.Web.UI.TemplateBuilder";
public const string SystemWebUITemplateParser = "System.Web.UI.TemplateParser";
public const string SystemWebUIWebControlsBaseValidator = "System.Web.UI.WebControls.BaseValidator";
public const string SystemWebUIWebControlsBulletedList = "System.Web.UI.WebControls.BulletedList";
public const string SystemWebUIWebControlsButton = "System.Web.UI.WebControls.Button";
public const string SystemWebUIWebControlsButtonColumn = "System.Web.UI.WebControls.ButtonColumn";
public const string SystemWebUIWebControlsButtonField = "System.Web.UI.WebControls.ButtonField";
public const string SystemWebUIWebControlsChangePassword = "System.Web.UI.WebControls.ChangePassword";
public const string SystemWebUIWebControlsCheckBox = "System.Web.UI.WebControls.CheckBox";
public const string SystemWebUIWebControlsCheckBoxField = "System.Web.UI.WebControls.CheckBoxField";
public const string SystemWebUIWebControlsCheckBoxList = "System.Web.UI.WebControls.CheckBoxList";
public const string SystemWebUIWebControlsCommandEventArgs = "System.Web.UI.WebControls.CommandEventArgs";
public const string SystemWebUIWebControlsCreateUserWizard = "System.Web.UI.WebControls.CreateUserWizard";
public const string SystemWebUIWebControlsDataKey = "System.Web.UI.WebControls.DataKey";
public const string SystemWebUIWebControlsDataList = "System.Web.UI.WebControls.DataList";
public const string SystemWebUIWebControlsDetailsView = "System.Web.UI.WebControls.DetailsView";
public const string SystemWebUIWebControlsDetailsViewInsertEventArgs = "System.Web.UI.WebControls.DetailsViewInsertEventArgs";
public const string SystemWebUIWebControlsDetailsViewUpdateEventArgs = "System.Web.UI.WebControls.DetailsViewUpdateEventArgs";
public const string SystemWebUIWebControlsFormView = "System.Web.UI.WebControls.FormView";
public const string SystemWebUIWebControlsFormViewInsertEventArgs = "System.Web.UI.WebControls.FormViewInsertEventArgs";
public const string SystemWebUIWebControlsFormViewUpdateEventArgs = "System.Web.UI.WebControls.FormViewUpdateEventArgs";
public const string SystemWebUIWebControlsGridView = "System.Web.UI.WebControls.GridView";
public const string SystemWebUIWebControlsHiddenField = "System.Web.UI.WebControls.HiddenField";
public const string SystemWebUIWebControlsHyperLink = "System.Web.UI.WebControls.HyperLink";
public const string SystemWebUIWebControlsHyperLinkColumn = "System.Web.UI.WebControls.HyperLinkColumn";
public const string SystemWebUIWebControlsHyperLinkField = "System.Web.UI.WebControls.HyperLinkField";
public const string SystemWebUIWebControlsImageButton = "System.Web.UI.WebControls.ImageButton";
public const string SystemWebUIWebControlsLabel = "System.Web.UI.WebControls.Label";
public const string SystemWebUIWebControlsLinkButton = "System.Web.UI.WebControls.LinkButton";
public const string SystemWebUIWebControlsListControl = "System.Web.UI.WebControls.ListControl";
public const string SystemWebUIWebControlsListItem = "System.Web.UI.WebControls.ListItem";
public const string SystemWebUIWebControlsLiteral = "System.Web.UI.WebControls.Literal";
public const string SystemWebUIWebControlsLogin = "System.Web.UI.WebControls.Login";
public const string SystemWebUIWebControlsMenu = "System.Web.UI.WebControls.Menu";
public const string SystemWebUIWebControlsMenuItem = "System.Web.UI.WebControls.MenuItem";
public const string SystemWebUIWebControlsMenuItemBinding = "System.Web.UI.WebControls.MenuItemBinding";
public const string SystemWebUIWebControlsPasswordRecovery = "System.Web.UI.WebControls.PasswordRecovery";
public const string SystemWebUIWebControlsQueryStringParameter = "System.Web.UI.WebControls.QueryStringParameter";
public const string SystemWebUIWebControlsRadioButtonList = "System.Web.UI.WebControls.RadioButtonList";
public const string SystemWebUIWebControlsServerValidateEventArgs = "System.Web.UI.WebControls.ServerValidateEventArgs";
public const string SystemWebUIWebControlsTableCell = "System.Web.UI.WebControls.TableCell";
public const string SystemWebUIWebControlsTextBox = "System.Web.UI.WebControls.TextBox";
public const string SystemWebUIWebControlsTreeNode = "System.Web.UI.WebControls.TreeNode";
public const string SystemWebUIWebControlsTreeNodeBinding = "System.Web.UI.WebControls.TreeNodeBinding";
public const string SystemWebUIWebControlsTreeView = "System.Web.UI.WebControls.TreeView";
public const string SystemWebUIWebControlsUnit = "System.Web.UI.WebControls.Unit";
public const string SystemWebUIWebControlsWebPartsAppearanceEditorPart = "System.Web.UI.WebControls.WebParts.AppearanceEditorPart";
public const string SystemWebUIWebControlsWebPartsPersonalizationEntry = "System.Web.UI.WebControls.WebParts.PersonalizationEntry";
public const string SystemWebUIWebControlsWebPartsWebPartCatalogAddVerb = "System.Web.UI.WebControls.WebParts.WebPartCatalogAddVerb";
public const string SystemWebUIWebControlsWebPartsWebPartCatalogCloseVerb = "System.Web.UI.WebControls.WebParts.WebPartCatalogCloseVerb";
public const string SystemWebUIWebControlsWebPartsWebPartCloseVerb = "System.Web.UI.WebControls.WebParts.WebPartCloseVerb";
public const string SystemWebUIWebControlsWebPartsWebPartConnectionsCancelVerb = "System.Web.UI.WebControls.WebParts.WebPartConnectionsCancelVerb";
public const string SystemWebUIWebControlsWebPartsWebPartConnectionsCloseVerb = "System.Web.UI.WebControls.WebParts.WebPartConnectionsCloseVerb";
public const string SystemWebUIWebControlsWebPartsWebPartConnectionsConfigureVerb = "System.Web.UI.WebControls.WebParts.WebPartConnectionsConfigureVerb";
public const string SystemWebUIWebControlsWebPartsWebPartConnectionsConnectVerb = "System.Web.UI.WebControls.WebParts.WebPartConnectionsConnectVerb";
public const string SystemWebUIWebControlsWebPartsWebPartConnectionsDisconnectVerb = "System.Web.UI.WebControls.WebParts.WebPartConnectionsDisconnectVerb";
public const string SystemWebUIWebControlsWebPartsWebPartConnectVerb = "System.Web.UI.WebControls.WebParts.WebPartConnectVerb";
public const string SystemWebUIWebControlsWebPartsWebPartDeleteVerb = "System.Web.UI.WebControls.WebParts.WebPartDeleteVerb";
public const string SystemWebUIWebControlsWebPartsWebPartEditorApplyVerb = "System.Web.UI.WebControls.WebParts.WebPartEditorApplyVerb";
public const string SystemWebUIWebControlsWebPartsWebPartEditorCancelVerb = "System.Web.UI.WebControls.WebParts.WebPartEditorCancelVerb";
public const string SystemWebUIWebControlsWebPartsWebPartEditorOKVerb = "System.Web.UI.WebControls.WebParts.WebPartEditorOKVerb";
public const string SystemWebUIWebControlsWebPartsWebPartEditVerb = "System.Web.UI.WebControls.WebParts.WebPartEditVerb";
public const string SystemWebUIWebControlsWebPartsWebPartExportVerb = "System.Web.UI.WebControls.WebParts.WebPartExportVerb";
public const string SystemWebUIWebControlsWebPartsWebPartHeaderCloseVerb = "System.Web.UI.WebControls.WebParts.WebPartHeaderCloseVerb";
public const string SystemWebUIWebControlsWebPartsWebPartHelpVerb = "System.Web.UI.WebControls.WebParts.WebPartHelpVerb";
public const string SystemWebUIWebControlsWebPartsWebPartMinimizeVerb = "System.Web.UI.WebControls.WebParts.WebPartMinimizeVerb";
public const string SystemWebUIWebControlsWebPartsWebPartRestoreVerb = "System.Web.UI.WebControls.WebParts.WebPartRestoreVerb";
public const string SystemWebUIWebControlsWebPartsWebPartVerb = "System.Web.UI.WebControls.WebParts.WebPartVerb";
public const string SystemWebUIITextControl = "System.Web.UI.ITextControl";
public const string SystemCollectionsGenericICollection1 = "System.Collections.Generic.ICollection`1";
public const string SystemCollectionsGenericIReadOnlyCollection1 = "System.Collections.Generic.IReadOnlyCollection`1";
public const string SystemCollectionsIEnumerable = "System.Collections.IEnumerable";
public const string SystemCollectionsGenericIEnumerable1 = "System.Collections.Generic.IEnumerable`1";
public const string SystemCollectionsIEnumerator = "System.Collections.IEnumerator";
public const string SystemCollectionsGenericIEnumerator1 = "System.Collections.Generic.IEnumerator`1";
public const string SystemLinqEnumerable = "System.Linq.Enumerable";
public const string SystemLinqQueryable = "System.Linq.Queryable";
public const string SystemCollectionsIList = "System.Collections.IList";
public const string SystemCollectionsGenericIList1 = "System.Collections.Generic.IList`1";
public const string SystemCollectionsSpecializedNameValueCollection = "System.Collections.Specialized.NameValueCollection";
public const string SystemCollectionsImmutableImmutableArray = "System.Collections.Immutable.ImmutableArray`1";
public const string SystemCollectionsImmutableImmutableList = "System.Collections.Immutable.ImmutableList`1";
public const string SystemCollectionsImmutableImmutableHashSet = "System.Collections.Immutable.ImmutableHashSet`1";
public const string SystemCollectionsImmutableImmutableSortedSet = "System.Collections.Immutable.ImmutableSortedSet`1";
public const string SystemCollectionsImmutableImmutableDictionary = "System.Collections.Immutable.ImmutableDictionary`2";
public const string SystemCollectionsImmutableImmutableSortedDictionary = "System.Collections.Immutable.ImmutableSortedDictionary`2";
public const string SystemCollectionsImmutableIImmutableDictionary = "System.Collections.Immutable.IImmutableDictionary`2";
public const string SystemCollectionsImmutableIImmutableList = "System.Collections.Immutable.IImmutableList`1";
public const string SystemCollectionsImmutableIImmutableQueue = "System.Collections.Immutable.IImmutableQueue`1";
public const string SystemCollectionsImmutableIImmutableSet = "System.Collections.Immutable.IImmutableSet`1";
public const string SystemCollectionsImmutableIImmutableStack = "System.Collections.Immutable.IImmutableStack`1";
public const string SystemRuntimeSerializationFormattersBinaryBinaryFormatter = "System.Runtime.Serialization.Formatters.Binary.BinaryFormatter";
public const string SystemWebUILosFormatter = "System.Web.UI.LosFormatter";
public const string SystemReflectionAssemblyFullName = "System.Reflection.Assembly";
public const string SystemAppDomain = "System.AppDomain";
public const string SystemWindowsAssemblyPart = "System.Windows.AssemblyPart";
public const string SystemWebUIHtmlControlsHtmlContainerControl = "System.Web.UI.HtmlControls.HtmlContainerControl";
public const string SystemWebUIHtmlControlsHtmlTable = "System.Web.UI.HtmlControls.HtmlTable";
public const string SystemWebUIHtmlControlsHtmlTableRow = "System.Web.UI.HtmlControls.HtmlTableRow";
public const string SystemWebUIWebControlsBaseDataList = "System.Web.UI.WebControls.BaseDataList";
public const string SystemWebUIWebControlsCalendar = "System.Web.UI.WebControls.Calendar";
public const string SystemWebUIWebControlsRepeatInfo = "System.Web.UI.WebControls.RepeatInfo";
public const string SystemWebUIWebControlsTable = "System.Web.UI.WebControls.Table";
public const string SystemWebHttpResponse = "System.Web.HttpResponse";
public const string SystemWebHttpResponseBase = "System.Web.HttpResponseBase";
public const string SystemIODirectory = "System.IO.Directory";
public const string SystemIOFileFullName = "System.IO.File";
public const string SystemIOFileInfo = "System.IO.FileInfo";
public const string SystemSecurityCryptographyCipherMode = "System.Security.Cryptography.CipherMode";
public const string SystemNetSecurityRemoteCertificateValidationCallback = "System.Net.Security.RemoteCertificateValidationCallback";
public const string SystemDiagnosticsProcess = "System.Diagnostics.Process";
public const string SystemDiagnosticsProcessStartInfo = "System.Diagnostics.ProcessStartInfo";
public const string SystemTextRegularExpressionsRegex = "System.Text.RegularExpressions.Regex";
public const string SystemRuntimeSerializationNetDataContractSerializer = "System.Runtime.Serialization.NetDataContractSerializer";
public const string SystemWebUIObjectStateFormatter = "System.Web.UI.ObjectStateFormatter";
public const string MicrosoftSecurityApplicationAntiXss = "Microsoft.Security.Application.AntiXss";
public const string MicrosoftSecurityApplicationAntiXssEncoder = "Microsoft.Security.Application.AntiXssEncoder";
public const string MicrosoftSecurityApplicationEncoder = "Microsoft.Security.Application.Encoder";
public const string MicrosoftSecurityApplicationUnicodeCharacterEncoder = "Microsoft.Security.Application.UnicodeCharacterEncoder";
public const string SystemWebHttpServerUtility = "System.Web.HttpServerUtility";
public const string SystemWebHttpServerUtilityBase = "System.Web.HttpServerUtilityBase";
public const string SystemWebHttpServerUtilityWrapper = "System.Web.HttpServerUtilityWrapper";
public const string SystemWebHttpUtility = "System.Web.HttpUtility";
public const string SystemWebSecurityAntiXssAntiXssEncoder = "System.Web.Security.AntiXss.AntiXssEncoder";
public const string SystemWebSecurityAntiXssUnicodeCharacterEncoder = "System.Web.Security.AntiXss.UnicodeCharacterEncoder";
public const string SystemWebUIAttributeCollection = "System.Web.UI.AttributeCollection";
public const string SystemWebUIClientScriptManager = "System.Web.UI.ClientScriptManager";
public const string SystemWebUIControl = "System.Web.UI.Control";
public const string SystemWebUIControlBuilder = "System.Web.UI.ControlBuilder";
public const string SystemWebUIPage = "System.Web.UI.Page";
public const string SystemWebUIWebControlsAdCreatedEventArgs = "System.Web.UI.WebControls.AdCreatedEventArgs";
public const string SystemWebUIWebControlsBoundField = "System.Web.UI.WebControls.BoundField";
public const string SystemWebUIWebControlsCommandField = "System.Web.UI.WebControls.CommandField";
public const string SystemWebUIWebControlsDataControlField = "System.Web.UI.WebControls.DataControlField";
public const string SystemWebUIWebControlsDataGrid = "System.Web.UI.WebControls.DataGrid";
public const string SystemWebUIWebControlsDataGridColumn = "System.Web.UI.WebControls.DataGridColumn";
public const string SystemWebUIWebControlsHotSpot = "System.Web.UI.WebControls.HotSpot";
public const string SystemWebUIWebControlsHtmlForm = "System.Web.UI.WebControls.HtmlForm";
public const string SystemWebUIWebControlsImage = "System.Web.UI.WebControls.Image";
public const string SystemWebUIWebControlsImageField = "System.Web.UI.WebControls.ImageField";
public const string SystemWebUIWebControlsLoginStatus = "System.Web.UI.WebControls.LoginStatus";
public const string SystemWebUIWebControlsPagerSettings = "System.Web.UI.WebControls.PagerSettings";
public const string SystemWebUIWebControlsPanel = "System.Web.UI.WebControls.Panel";
public const string SystemWebUIWebControlsPanelStyle = "System.Web.UI.WebControls.PanelStyle";
public const string SystemWebUIWebControlsRadioButton = "System.Web.UI.WebControls.RadioButton";
public const string SystemWebUIWebControlsSiteMapDataSource = "System.Web.UI.WebControls.SiteMapDataSource";
public const string SystemWebUIWebControlsTableStyle = "System.Web.UI.WebControls.TableStyle";
public const string SystemWebUIWebControlsTreeNodeStyle = "System.Web.UI.WebControls.TreeNodeStyle";
public const string SystemWebUIWebControlsWebControl = "System.Web.UI.WebControls.WebControl";
public const string SystemWebUIWebControlsWebPartsDeclarativeCatalogPart = "System.Web.UI.WebControls.WebParts.DeclarativeCatalogPart";
public const string SystemWebUIWebControlsWebPartsGenericWebPart = "System.Web.UI.WebControls.WebParts.GenericWebPart";
public const string SystemWebUIWebControlsWebPartsPageCatalogPart = "System.Web.UI.WebControls.WebParts.PageCatalogPart";
public const string SystemWebUIWebControlsWebPartsWebPart = "System.Web.UI.WebControls.WebParts.WebPart";
public const string SystemWebUIWebControlsWebPartsWebPartZoneBase = "System.Web.UI.WebControls.WebParts.WebPartZoneBase";
public const string SystemWebUIWebControlsWebPartsWebZone = "System.Web.UI.WebControls.WebParts.WebZone";
public const string SystemWebUIWebControlsWebPartsZoneLinkButton = "System.Web.UI.WebControls.WebParts.ZoneLinkButton";
public const string SystemWebUIWebControlsWizard = "System.Web.UI.WebControls.Wizard";
public const string SystemWebUtilHttpEncoder = "System.Web.Util.HttpEncoder";
public const string SystemWebServicesWebMethodAttribute = "System.Web.Services.WebMethodAttribute";
public const string SystemWebMvcController = "System.Web.Mvc.Controller";
public const string SystemWebMvcControllerBase = "System.Web.Mvc.ControllerBase";
public const string SystemWebMvcActionResult = "System.Web.Mvc.ActionResult";
public const string SystemWebMvcValidateAntiForgeryTokenAttribute = "System.Web.Mvc.ValidateAntiForgeryTokenAttribute";
public const string SystemWebMvcHttpGetAttribute = "System.Web.Mvc.HttpGetAttribute";
public const string SystemWebMvcHttpPostAttribute = "System.Web.Mvc.HttpPostAttribute";
public const string SystemWebMvcHttpPutAttribute = "System.Web.Mvc.HttpPutAttribute";
public const string SystemWebMvcHttpDeleteAttribute = "System.Web.Mvc.HttpDeleteAttribute";
public const string SystemWebMvcHttpPatchAttribute = "System.Web.Mvc.HttpPatchAttribute";
public const string SystemWebMvcAcceptVerbsAttribute = "System.Web.Mvc.AcceptVerbsAttribute";
public const string SystemWebMvcNonActionAttribute = "System.Web.Mvc.NonActionAttribute";
public const string SystemWebMvcChildActionOnlyAttribute = "System.Web.Mvc.ChildActionOnlyAttribute";
public const string SystemWebMvcHttpVerbs = "System.Web.Mvc.HttpVerbs";
public const string SystemMarshalByRefObject = "System.MarshalByRefObject";
public const string SystemExecutionEngineException = "System.ExecutionEngineException";
public const string SystemStackOverflowException = "System.StackOverflowException";
public const string SystemThreadingThread = "System.Threading.Thread";
public const string SystemWindowsFormsControl = "System.Windows.Forms.Control";
public const string SystemRuntimeSerializationIDeserializationCallback = "System.Runtime.Serialization.IDeserializationCallback";
public const string SystemRuntimeSerializationISerializable = "System.Runtime.Serialization.ISerializable";
public const string SystemRuntimeSerializationStreamingContext = "System.Runtime.Serialization.StreamingContext";
public const string SystemRuntimeSerializationOnDeserializingAttribute = "System.Runtime.Serialization.OnDeserializingAttribute";
public const string SystemRuntimeSerializationOnDeserializedAttribute = "System.Runtime.Serialization.OnDeserializedAttribute";
public const string SystemCollectionsIHashCodeProvider = "System.Collections.IHashCodeProvider";
public const string SystemRuntimeInteropServicesHandleRef = "System.Runtime.InteropServices.HandleRef";
public const string SystemRuntimeSerializationDataMemberAttribute = "System.Runtime.Serialization.DataMemberAttribute";
public const string SystemComponentModelCompositionExportAttribute = "System.ComponentModel.Composition.ExportAttribute";
public const string SystemComponentModelCompositionInheritedExportAttribute = "System.ComponentModel.Composition.InheritedExportAttribute";
public const string SystemComponentModelCompositionImportingConstructorAttribute = "System.ComponentModel.Composition.ImportingConstructorAttribute";
public const string SystemCompositionExportAttribute = "System.Composition.ExportAttribute";
public const string SystemCompositionImportingConstructorAttribute = "System.Composition.ImportingConstructorAttribute";
public const string SystemDiagnosticsContractsPureAttribute = "System.Diagnostics.Contracts.PureAttribute";
public const string SystemComponentModelLocalizableAttribute = "System.ComponentModel.LocalizableAttribute";
public const string SystemRuntimeSerializationOnSerializingAttribute = "System.Runtime.Serialization.OnSerializingAttribute";
public const string SystemRuntimeSerializationOnSerializedAttribute = "System.Runtime.Serialization.OnSerializedAttribute";
public const string SystemSerializableAttribute = "System.SerializableAttribute";
public const string SystemNonSerializedAttribute = "System.NonSerializedAttribute";
public const string MicrosoftVisualStudioTestToolsUnitTestingTestCleanupAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute";
public const string MicrosoftVisualStudioTestToolsUnitTestingTestInitializeAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute";
public const string MicrosoftVisualStudioTestToolsUnitTestingTestMethodAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute";
public const string MicrosoftVisualStudioTestToolsUnitTestingDataTestMethodAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.DataTestMethodAttribute";
public const string MicrosoftVisualStudioTestToolsUnitTestingExpectedExceptionAttribute = "Microsoft.VisualStudio.TestTools.UnitTesting.ExpectedExceptionAttribute";
public const string MicrosoftVisualStudioTestToolsUnitTestingAssert = "Microsoft.VisualStudio.TestTools.UnitTesting.Assert";
public const string MicrosoftVisualStudioTestToolsUnitTestingCollectionAssert = "Microsoft.VisualStudio.TestTools.UnitTesting.CollectionAssert";
public const string MicrosoftVisualStudioTestToolsUnitTestingStringAssert = "Microsoft.VisualStudio.TestTools.UnitTesting.StringAssert";
public const string XunitAssert = "Xunit.Assert";
public const string XunitFactAttribute = "Xunit.FactAttribute";
public const string XunitTheoryAttribute = "Xunit.TheoryAttribute";
public const string NUnitFrameworkAssert = "NUnit.Framework.Assert";
public const string NUnitFrameworkOneTimeSetUpAttribute = "NUnit.Framework.OneTimeSetUpAttribute";
public const string NUnitFrameworkOneTimeTearDownAttribute = "NUnit.Framework.OneTimeTearDownAttribute";
public const string NUnitFrameworkSetUpAttribute = "NUnit.Framework.SetUpAttribute";
public const string NUnitFrameworkSetUpFixtureAttribute = "NUnit.Framework.SetUpFixtureAttribute";
public const string NUnitFrameworkTearDownAttribute = "NUnit.Framework.TearDownAttribute";
public const string NUnitFrameworkTestAttribute = "NUnit.Framework.TestAttribute";
public const string NUnitFrameworkTestCaseAttribute = "NUnit.Framework.TestCaseAttribute";
public const string NUnitFrameworkTestCaseSourceAttribute = "NUnit.Framework.TestCaseSourceAttribute";
public const string NUnitFrameworkTheoryAttribute = "NUnit.Framework.TheoryAttribute";
public const string SystemXmlXmlWriter = "System.Xml.XmlWriter";
public const string MicrosoftSecurityApplicationLdapEncoder = "Microsoft.Security.Application.LdapEncoder";
public const string SystemDirectoryServicesActiveDirectoryADSearcher = "System.DirectoryServices.ActiveDirectory.ADSearcher";
public const string SystemDirectoryServicesDirectorySearcher = "System.DirectoryServices.DirectorySearcher";
public const string SystemDirectoryDirectoryEntry = "System.DirectoryServices.DirectoryEntry";
public const string SystemWebScriptSerializationJavaScriptSerializer = "System.Web.Script.Serialization.JavaScriptSerializer";
public const string SystemWebScriptSerializationJavaScriptTypeResolver = "System.Web.Script.Serialization.JavaScriptTypeResolver";
public const string SystemWebScriptSerializationSimpleTypeResolver = "System.Web.Script.Serialization.SimpleTypeResolver";
public const string SystemWebUIPageTheme = "System.Web.UI.PageTheme";
public const string SystemWebUITemplateControl = "System.Web.UI.TemplateControl";
public const string SystemWebUIWebControlsXmlDataSource = "System.Web.UI.WebControls.XmlDataSource";
public const string SystemWebUIXPathBinder = "System.Web.UI.XPathBinder";
public const string SystemXmlSchemaXmlSchemaXPath = "System.Xml.Schema.XmlSchemaXPath";
public const string SystemXmlXmlNode = "System.Xml.XmlNode";
public const string SystemXmlXPathXPathExpression = "System.Xml.XPath.XPathExpression";
public const string SystemXmlXPathXPathNavigator = "System.Xml.XPath.XPathNavigator";
public const string SystemXmlXmlAttribute = "System.Xml.XmlAttribute";
public const string SystemXmlXmlDocument = "System.Xml.XmlDocument";
public const string SystemXmlXmlDocumentFragment = "System.Xml.XmlDocumentFragment";
public const string SystemXmlXmlElement = "System.Xml.XmlElement";
public const string SystemXmlXmlEntity = "System.Xml.XmlEntity";
public const string SystemXmlXmlNotation = "System.Xml.XmlNotation";
public const string SystemXmlXmlTextWriter = "System.Xml.XmlTextWriter";
public const string SystemWindowsMarkupXamlReader = "System.Windows.Markup.XamlReader";
public const string SystemWebConfigurationHttpRuntimeSection = "System.Web.Configuration.HttpRuntimeSection";
public const string SystemEventArgs = "System.EventArgs";
public const string SystemXmlSchemaXmlSchemaCollection = "System.Xml.Schema.XmlSchemaCollection";
public const string SystemDataDataSet = "System.Data.DataSet";
public const string SystemXmlXmlReader = "System.Xml.XmlReader";
public const string SystemXmlSerializationXmlSerializer = "System.Xml.Serialization.XmlSerializer";
public const string SystemXmlXmlValidatingReader = "System.Xml.XmlValidatingReader";
public const string SystemXmlSchemaXmlSchema = "System.Xml.Schema.XmlSchema";
public const string SystemXmlXPathXPathDocument = "System.Xml.XPath.XPathDocument";
public const string SystemIODirectoryInfo = "System.IO.DirectoryInfo";
public const string SystemIOLogLogStore = "System.IO.Log.LogStore";
public const string SystemSecurityCryptographyPasswordDeriveBytes = "System.Security.Cryptography.PasswordDeriveBytes";
public const string SystemSecurityCryptographyRfc2898DeriveBytes = "System.Security.Cryptography.Rfc2898DeriveBytes";
public const string SystemXmlXslXslTransform = "System.Xml.Xsl.XslTransform";
public const string MicrosoftWindowsAzureStorageCloudStorageAccount = "Microsoft.WindowsAzure.Storage.CloudStorageAccount";
public const string NewtonsoftJsonJsonConvert = "Newtonsoft.Json.JsonConvert";
public const string NewtonsoftJsonJsonSerializer = "Newtonsoft.Json.JsonSerializer";
public const string NewtonsoftJsonJsonSerializerSettings = "Newtonsoft.Json.JsonSerializerSettings";
public const string SystemNullable1 = "System.Nullable`1";
public const string MicrosoftWindowsAzureStorageSharedAccessProtocol = "Microsoft.WindowsAzure.Storage.SharedAccessProtocol";
public const string SystemSecurityCryptographyHashAlgorithmName = "System.Security.Cryptography.HashAlgorithmName";
public const string MicrosoftAspNetCoreHttpIResponseCookies = "Microsoft.AspNetCore.Http.IResponseCookies";
public const string MicrosoftAspNetCoreHttpInternalResponseCookies = "Microsoft.AspNetCore.Http.Internal.ResponseCookies";
public const string MicrosoftAspNetCoreHttpCookieOptions = "Microsoft.AspNetCore.Http.CookieOptions";
public const string SystemSecurityCryptographyX509CertificatesX509Store = "System.Security.Cryptography.X509Certificates.X509Store";
public const string SystemSecurityCryptographyX509CertificatesStoreName = "System.Security.Cryptography.X509Certificates.StoreName";
public const string SystemSecurityCryptographyX509CertificatesX509Certificate = "System.Security.Cryptography.X509Certificates.X509Certificate";
public const string SystemSecurityCryptographyX509CertificatesX509Certificate2 = "System.Security.Cryptography.X509Certificates.X509Certificate2";
public const string SystemSecurityCryptographyRSA = "System.Security.Cryptography.RSA";
public const string SystemSecurityCryptographyDSA = "System.Security.Cryptography.DSA";
public const string SystemSecurityCryptographyAsymmetricAlgorithm = "System.Security.Cryptography.AsymmetricAlgorithm";
public const string SystemSecurityCryptographyCryptoConfig = "System.Security.Cryptography.CryptoConfig";
public const string SystemIOCompressionZipArchiveEntry = "System.IO.Compression.ZipArchiveEntry";
public const string SystemIOCompressionZipFileExtensions = "System.IO.Compression.ZipFileExtensions";
public const string SystemIOFileStream = "System.IO.FileStream";
public const string SystemIOPath = "System.IO.Path";
public const string SystemString = "System.String";
public const string SystemRuntimeInteropServicesDllImportAttribute = "System.Runtime.InteropServices.DllImportAttribute";
public const string SystemRuntimeInteropServicesDefaultDllImportSearchPathsAttribute = "System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute";
public const string MicrosoftAspNetCoreMvcFiltersFilterCollection = "Microsoft.AspNetCore.Mvc.Filters.FilterCollection";
public const string MicrosoftAspNetCoreMvcController = "Microsoft.AspNetCore.Mvc.Controller";
public const string MicrosoftAspNetCoreMvcControllerBase = "Microsoft.AspNetCore.Mvc.ControllerBase";
public const string MicrosoftAspNetCoreMvcNonActionAttribute = "Microsoft.AspNetCore.Mvc.NonActionAttribute";
public const string MicrosoftAspNetCoreMvcRoutingHttpMethodAttribute = "Microsoft.AspNetCore.Mvc.Routing.HttpMethodAttribute";
public const string MicrosoftAspNetCoreMvcHttpPostAttribute = "Microsoft.AspNetCore.Mvc.HttpPostAttribute";
public const string MicrosoftAspNetCoreMvcHttpPutAttribute = "Microsoft.AspNetCore.Mvc.HttpPutAttribute";
public const string MicrosoftAspNetCoreMvcHttpDeleteAttribute = "Microsoft.AspNetCore.Mvc.HttpDeleteAttribute";
public const string MicrosoftAspNetCoreMvcHttpPatchAttribute = "Microsoft.AspNetCore.Mvc.HttpPatchAttribute";
public const string MicrosoftAspNetCoreMvcFiltersIFilterMetadata = "Microsoft.AspNetCore.Mvc.Filters.IFilterMetadata";
public const string MicrosoftAspNetCoreAntiforgeryIAntiforgery = "Microsoft.AspNetCore.Antiforgery.IAntiforgery";
public const string MicrosoftAspNetCoreMvcFiltersIAsyncAuthorizationFilter = "Microsoft.AspNetCore.Mvc.Filters.IAsyncAuthorizationFilter";
public const string MicrosoftAspNetCoreMvcFiltersIAuthorizationFilter = "Microsoft.AspNetCore.Mvc.Filters.IAuthorizationFilter";
public const string MicrosoftAspNetCoreMvcFiltersAuthorizationFilterContext = "Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext";
public const string SystemConvert = "System.Convert";
public const string SystemSecurityCryptographySymmetricAlgorithm = "System.Security.Cryptography.SymmetricAlgorithm";
public const string NewtonsoftJsonTypeNameHandling = "Newtonsoft.Json.TypeNameHandling";
public const string SystemNetHttpHttpClient = "System.Net.Http.HttpClient";
public const string SystemNetHttpHttpClientHandler = "System.Net.Http.HttpClientHandler";
public const string SystemNetHttpWinHttpHandler = "System.Net.Http.WinHttpHandler";
public const string SystemNetServicePointManager = "System.Net.ServicePointManager";
public const string SystemRandom = "System.Random";
public const string SystemSecurityAuthenticationSslProtocols = "System.Security.Authentication.SslProtocols";
public const string MicrosoftAspNetCoreRazorHostingRazorCompiledItemAttribute = "Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute";
public const string SystemTextEncoding = "System.Text.Encoding";
public const string SystemSecurityCryptographyAesGcm = "System.Security.Cryptography.AesGcm";
public const string SystemSecurityCryptographyAesCcm = "System.Security.Cryptography.AesCcm";
public const string SystemThreadingInterlocked = "System.Threading.Interlocked";
public const string SystemAttributeUsageAttribute = "System.AttributeUsageAttribute";
public const string SystemInvalidOperationException = "System.InvalidOperationException";
public const string SystemArgumentException = "System.ArgumentException";
public const string SystemNotSupportedException = "System.NotSupportedException";
public const string SystemCollectionsGenericKeyNotFoundException = "System.Collections.Generic.KeyNotFoundException";
public const string SystemCollectionsGenericIEqualityComparer1 = "System.Collections.Generic.IEqualityComparer`1";
public const string SystemUri = "System.Uri";
public const string SystemNotImplementedException = "System.NotImplementedException";
public const string SystemAttribute = "System.Attribute";
public const string SystemCodeDomCompilerGeneratedCodeAttribute = "System.CodeDom.Compiler.GeneratedCodeAttribute";
public const string SystemResourcesNeutralResourcesLanguageAttribute = "System.Resources.NeutralResourcesLanguageAttribute";
public const string SystemConsole = "System.Console";
public const string SystemSecurityCryptographyX509CertificatesX509Chain = "System.Security.Cryptography.X509Certificates.X509Chain";
public const string SystemNetSecuritySslPolicyErrors = "System.Net.Security.SslPolicyErrors";
public const string SystemRuntimeCompilerServicesRestrictedInternalsVisibleToAttribute = "System.Runtime.CompilerServices.RestrictedInternalsVisibleToAttribute";
public const string SystemDiagnosticsTraceListener = "System.Diagnostics.TraceListener";
public const string SystemRuntimeInteropServicesSafeHandle = "System.Runtime.InteropServices.SafeHandle";
public const string SystemConfigurationConfigurationSection = "System.Configuration.ConfigurationSection";
public const string SystemConfigurationIConfigurationSectionHandler = "System.Configuration.IConfigurationSectionHandler";
public const string SystemRuntimeCompilerServicesInternalsVisibleToAttribute = "System.Runtime.CompilerServices.InternalsVisibleToAttribute";
public const string SystemRuntimeInteropServicesUnmanagedType = "System.Runtime.InteropServices.UnmanagedType";
public const string SystemStringComparison = "System.StringComparison";
public const string SystemThreadingTasksTaskFactory = "System.Threading.Tasks.TaskFactory";
public const string SystemThreadingTasksTaskScheduler = "System.Threading.Tasks.TaskScheduler";
public const string SystemGlobalizationCultureInfo = "System.Globalization.CultureInfo";
public const string SystemRuntimeInteropServicesMarshalAsAttribute = "System.Runtime.InteropServices.MarshalAsAttribute";
public const string SystemThreadingCancellationToken = "System.Threading.CancellationToken";
public const string SystemSecurityCryptographyMD5 = "System.Security.Cryptography.MD5";
public const string SystemSecurityCryptographySHA1 = "System.Security.Cryptography.SHA1";
public const string SystemSecurityCryptographyHMACSHA1 = "System.Security.Cryptography.HMACSHA1";
public const string SystemSecurityCryptographyDES = "System.Security.Cryptography.DES";
public const string SystemSecurityCryptographyDSASignatureFormatter = "System.Security.Cryptography.DSASignatureFormatter";
public const string SystemSecurityCryptographyHMACMD5 = "System.Security.Cryptography.HMACMD5";
public const string SystemSecurityCryptographyRC2 = "System.Security.Cryptography.RC2";
public const string SystemSecurityCryptographyTripleDES = "System.Security.Cryptography.TripleDES";
public const string SystemSecurityCryptographyRIPEMD160 = "System.Security.Cryptography.RIPEMD160";
public const string SystemSecurityCryptographyHMACRIPEMD160 = "System.Security.Cryptography.HMACRIPEMD160";
public const string SystemRuntimeExceptionServicesHandleProcessCorruptedStateExceptionsAttribute = "System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptionsAttribute";
public const string SystemDataDataTable = "System.Data.DataTable";
public const string SystemDataDataViewManager = "System.Data.DataViewManager";
public const string SystemXmlXmlTextReader = "System.Xml.XmlTextReader";
public const string SystemXmlDtdProcessing = "System.Xml.DtdProcessing";
public const string SystemXmlXmlReaderSettings = "System.Xml.XmlReaderSettings";
public const string SystemXmlXslXslCompiledTransform = "System.Xml.Xsl.XslCompiledTransform";
public const string SystemXmlXmlResolver = "System.Xml.XmlResolver";
public const string SystemXmlXmlSecureResolver = "System.Xml.XmlSecureResolver";
public const string SystemXmlXslXsltSettings = "System.Xml.Xsl.XsltSettings";
public const string SystemDataDataRow = "System.Data.DataRow";
public const string SystemObsoleteAttribute = "System.ObsoleteAttribute";
public const string SystemComponentModelComponent = "System.ComponentModel.Component";
public const string SystemRuntimeInteropServicesPreserveSigAttribute = "System.Runtime.InteropServices.PreserveSigAttribute";
public const string SystemTextStringBuilder = "System.Text.StringBuilder";
public const string SystemRuntimeInteropServicesCharSet = "System.Runtime.InteropServices.CharSet";
public const string SystemDataEntityQueryableExtensions = "System.Data.Entity.QueryableExtensions";
public const string MicrosoftEntityFrameworkCoreEntityFrameworkQueryableExtensions = "Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions";
public const string SystemGC = "System.GC";
public const string SystemOutOfMemoryException = "System.OutOfMemoryException";
public const string SystemReflectionMemberInfo = "System.Reflection.MemberInfo";
public const string SystemReflectionParameterInfo = "System.Reflection.ParameterInfo";
public const string SystemIFormatProvider = "System.IFormatProvider";
public const string SystemActivator = "System.Activator";
public const string SystemResourcesResourceManager = "System.Resources.ResourceManager";
public const string MicrosoftVisualBasicDevicesComputerInfo = "Microsoft.VisualBasic.Devices.ComputerInfo";
public const string SystemIOUnmanagedMemoryStream = "System.IO.UnmanagedMemoryStream";
public const string SystemDiagnosticsTracingEventSource = "System.Diagnostics.Tracing.EventSource";
public const string SystemRuntimeCompilerServicesTypeForwardedToAttribute = "System.Runtime.CompilerServices.TypeForwardedToAttribute";
public const string MicrosoftCodeAnalysisHostMefMefConstruction = "Microsoft.CodeAnalysis.Host.Mef.MefConstruction";
public const string SystemFlagsAttribute = "System.FlagsAttribute";
public const string SystemDiagnosticsConditionalAttribute = "System.Diagnostics.ConditionalAttribute";
public const string SystemReflectionAssemblyVersionAttribute = "System.Reflection.AssemblyVersionAttribute";
public const string SystemCLSCompliantAttribute = "System.CLSCompliantAttribute";
public const string SystemIComparable = "System.IComparable";
public const string SystemIComparable1 = "System.IComparable`1";
public const string SystemEventHandler1 = "System.EventHandler`1";
public const string SystemRuntimeInteropServicesComVisibleAttribute = "System.Runtime.InteropServices.ComVisibleAttribute";
public const string SystemRuntimeInteropServicesFieldOffsetAttribute = "System.Runtime.InteropServices.FieldOffsetAttribute";
public const string SystemRuntimeInteropServicesStructLayoutAttribute = "System.Runtime.InteropServices.StructLayoutAttribute";
public const string SystemRuntimeInteropServicesComSourceInterfacesAttribute = "System.Runtime.InteropServices.ComSourceInterfacesAttribute";
public const string MicrosoftCodeAnalysisDiagnosticsGeneratedCodeAnalysisFlags = "Microsoft.CodeAnalysis.Diagnostics.GeneratedCodeAnalysisFlags";
public const string MicrosoftCodeAnalysisCSharpCSharpCompilation = "Microsoft.CodeAnalysis.CSharp.CSharpCompilation";
public const string SystemRuntimeInteropServicesCoClassAttribute = "System.Runtime.InteropServices.CoClassAttribute";
public const string SystemIProgress1 = "System.IProgress`1";
public const string SystemComponentModelDesignerAttribute = "System.ComponentModel.DesignerAttribute";
public const string SystemWebHttpRouteAttribute = "System.Web.Http.RouteAttribute";
public const string SystemWebMvcHttpHeadAttribute = "System.Web.Mvc.HttpHeadAttribute";
public const string SystemWebMvcHttpOptionsAttribute = "System.Web.Mvc.HttpOptionsAttribute";
public const string MicrosoftAspNetCoreMvcHttpGetAttribute = "Microsoft.AspNetCore.Mvc.HttpGetAttribute";
public const string MicrosoftAspNetCoreMvcHttpHeadAttribute = "Microsoft.AspNetCore.Mvc.HttpHeadAttribute";
public const string MicrosoftAspNetCoreMvcHttpOptionsAttribute = "Microsoft.AspNetCore.Mvc.HttpOptionsAttribute";
public const string MicrosoftAspNetCoreMvcRouteAttribute = "Microsoft.AspNetCore.Mvc.RouteAttribute";
public const string SystemWebHttpApplication = "System.Web.HttpApplication";
public const string MicrosoftCodeAnalysisCompilation = "Microsoft.CodeAnalysis.Compilation";
public const string MicrosoftCodeAnalysisVisualBasicVisualBasicCompilation = "Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation";
public const string SystemRuntimeInteropServicesOutAttribute = "System.Runtime.InteropServices.OutAttribute";
public const string MicrosoftCodeAnalysisDiagnosticsDiagnosticAnalyzer = "Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzer";
public const string MicrosoftCodeAnalysisDiagnosticsDiagnosticAnalyzerAttribute = "Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzerAttribute";
public const string MicrosoftCodeAnalysisDiagnostic = "Microsoft.CodeAnalysis.Diagnostic";
public const string MicrosoftCodeAnalysisDiagnosticDescriptor = "Microsoft.CodeAnalysis.DiagnosticDescriptor";
public const string MicrosoftCodeAnalysisLocalizableString = "Microsoft.CodeAnalysis.LocalizableString";
public const string MicrosoftCodeAnalysisDiagnosticsAnalysisContext = "Microsoft.CodeAnalysis.Diagnostics.AnalysisContext";
public const string MicrosoftCodeAnalysisDiagnosticsCompilationStartAnalysisContext = "Microsoft.CodeAnalysis.Diagnostics.CompilationStartAnalysisContext";
public const string MicrosoftCodeAnalysisDiagnosticsCompilationEndAnalysisContext = "Microsoft.CodeAnalysis.Diagnostics.CompilationAnalysisContext";
public const string MicrosoftCodeAnalysisDiagnosticsSemanticModelAnalysisContext = "Microsoft.CodeAnalysis.Diagnostics.SemanticModelAnalysisContext";
public const string MicrosoftCodeAnalysisDiagnosticsSymbolAnalysisContext = "Microsoft.CodeAnalysis.Diagnostics.SymbolAnalysisContext";
public const string MicrosoftCodeAnalysisDiagnosticsSyntaxNodeAnalysisContext = "Microsoft.CodeAnalysis.Diagnostics.SyntaxNodeAnalysisContext";
public const string MicrosoftCodeAnalysisDiagnosticsSyntaxTreeAnalysisContext = "Microsoft.CodeAnalysis.Diagnostics.SyntaxTreeAnalysisContext";
public const string MicrosoftCodeAnalysisDiagnosticsCodeBlockStartAnalysisContext = "Microsoft.CodeAnalysis.Diagnostics.CodeBlockStartAnalysisContext`1";
public const string MicrosoftCodeAnalysisDiagnosticsCodeBlockAnalysisContext = "Microsoft.CodeAnalysis.Diagnostics.CodeBlockAnalysisContext";
public const string MicrosoftCodeAnalysisDiagnosticsOperationBlockStartAnalysisContext = "Microsoft.CodeAnalysis.Diagnostics.OperationBlockStartAnalysisContext";
public const string MicrosoftCodeAnalysisDiagnosticsOperationBlockAnalysisContext = "Microsoft.CodeAnalysis.Diagnostics.OperationBlockAnalysisContext";
public const string MicrosoftCodeAnalysisDiagnosticsOperationAnalysisContext = "Microsoft.CodeAnalysis.Diagnostics.OperationAnalysisContext";
public const string MicrosoftCodeAnalysisSymbolKind = "Microsoft.CodeAnalysis.SymbolKind";
}
}
| 105.616495 | 189 | 0.803783 | [
"Apache-2.0"
] | lostmsu/roslyn-analyzers | src/Utilities/Compiler/WellKnownTypeNames.cs | 51,226 | C# |
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
namespace FormFlow
{
public static class RedirectToActionResultExtensions
{
public static RedirectToActionResult WithJourneyInstanceUniqueKey(
this RedirectToActionResult result,
JourneyInstance instance)
{
return WithJourneyInstanceUniqueKey(result, instance.InstanceId);
}
public static RedirectToActionResult WithJourneyInstanceUniqueKey(
this RedirectToActionResult result,
JourneyInstanceId instanceId)
{
if (instanceId.UniqueKey == null)
{
throw new ArgumentException(
"Specified instance does not have a unique key.",
nameof(instanceId));
}
result.RouteValues ??= new RouteValueDictionary();
result.RouteValues["ffiid"] = instanceId.UniqueKey;
return result;
}
}
}
| 29.617647 | 77 | 0.623635 | [
"MIT"
] | gunndabad/formflow | src/FormFlow/RedirectToActionResultExtensions.cs | 1,009 | C# |
using Windows.UI.Xaml.Controls;
namespace Dota2Handbook.Views
{
public sealed partial class Leaderboards : Page
{
public Leaderboards()
{
InitializeComponent();
}
}
} | 18 | 51 | 0.601852 | [
"MIT"
] | firatesmer/dota2-handbook | Dota2Handbook/Views/Leaderboards.xaml.cs | 218 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.