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
//------------------------------------------------------------------------------ // <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 Movies.WPF.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Movies.WPF.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
38.569444
176
0.602089
[ "MIT" ]
DevZest/RDO.Net
samples/Tutorial/Movies.WPF/Properties/Resources.Designer.cs
2,779
C#
using System; using TrueCraft.API.Logic; namespace TrueCraft.Core.Logic.Items { public class GlowstoneDustItem : ItemProvider { public static readonly short ItemID = 0x15C; public override short ID { get { return 0x15C; } } public override Tuple<int, int> GetIconTexture(byte metadata) { return new Tuple<int, int>(9, 4); } public override string DisplayName { get { return "Glowstone Dust"; } } } }
25
79
0.635789
[ "MIT" ]
BinaryGears/TrueCraft
TrueCraft.Core/Logic/Items/GlowstoneDustItem.cs
475
C#
// <auto-generated /> namespace GigHub.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")] public sealed partial class AddFollowing : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(AddFollowing)); string IMigrationMetadata.Id { get { return "201711061235427_AddFollowing"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
27.133333
95
0.619165
[ "Apache-2.0" ]
antcalatayud/GigHub
GigHub/Persistence/Migrations/201711061235427_AddFollowing.Designer.cs
814
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FoodCalculator.FoodApi.EntityModel; public class IngredientNotFoundException : Exception { public IngredientNotFoundException(string ingredientQueryString) : base($"could not find nutrition data for ingredient query: '{ingredientQueryString}'") { } }
25
96
0.7775
[ "MIT" ]
GuyBukys/FoodCalculator.FoodApi
FoodCalculator.FoodApi.EntityModel/IngredientNotFoundException.cs
402
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using Xunit.Sdk; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; namespace GraphLinqQL.TestFramework { internal class YamlScenariosAttribute : DataAttribute { private readonly string prefix; public YamlScenariosAttribute(string prefix) { this.prefix = prefix; } public override IEnumerable<object[]> GetData(MethodInfo testMethod) { var parameters = testMethod.GetParameters(); var scenarioType = typeof(ScenarioData<,,>) .MakeGenericType(parameters.Single().ParameterType.GetGenericArguments()); var deserializer = new DeserializerBuilder() .IgnoreUnmatchedProperties() .WithNamingConvention(HyphenatedNamingConvention.Instance) .Build(); var asm = this.GetType().Assembly; foreach (var name in asm.GetManifestResourceNames().Where(n => n.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase))) { using var stream = asm.GetManifestResourceStream(name); if (stream == null) { continue; } using var reader = new StreamReader(stream); var scenario = (IScenarioData)deserializer.Deserialize(reader, scenarioType)!; var len = scenario.Tests.Length.ToString().Length; for (var i = 0; i < scenario.Tests.Length; i++) { scenario.Tests[i].Name = $"{scenario.Scenario} - {(i + 1).ToString().PadLeft(len, '0')} {scenario.Tests[i].Name}"; yield return new[] { scenario.Tests[i] }; } } } } }
34.690909
142
0.593816
[ "MIT" ]
mdekrey/GraphLinQL
GraphLinqQL.EFCore.Test/TestFramework/YamlScenariosAttribute.cs
1,910
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the rds-2014-10-31.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.RDS.Model { /// <summary> /// Container for the parameters to the RebootDBInstance operation. /// You might need to reboot your DB instance, usually for maintenance reasons. For example, /// if you make certain modifications, or if you change the DB parameter group associated /// with the DB instance, you must reboot the instance for the changes to take effect. /// /// /// /// <para> /// Rebooting a DB instance restarts the database engine service. Rebooting a DB instance /// results in a momentary outage, during which the DB instance status is set to rebooting. /// /// </para> /// /// <para> /// For more information about rebooting, see <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_RebootInstance.html">Rebooting /// a DB Instance</a> in the <i>Amazon RDS User Guide.</i> /// </para> /// </summary> public partial class RebootDBInstanceRequest : AmazonRDSRequest { private string _dbInstanceIdentifier; private bool? _forceFailover; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public RebootDBInstanceRequest() { } /// <summary> /// Instantiates RebootDBInstanceRequest with the parameterized properties /// </summary> /// <param name="dbInstanceIdentifier">The DB instance identifier. This parameter is stored as a lowercase string. Constraints: <ul> <li> Must match the identifier of an existing DBInstance. </li> </ul></param> public RebootDBInstanceRequest(string dbInstanceIdentifier) { _dbInstanceIdentifier = dbInstanceIdentifier; } /// <summary> /// Gets and sets the property DBInstanceIdentifier. /// <para> /// The DB instance identifier. This parameter is stored as a lowercase string. /// </para> /// /// <para> /// Constraints: /// </para> /// <ul> <li> /// <para> /// Must match the identifier of an existing DBInstance. /// </para> /// </li> </ul> /// </summary> [AWSProperty(Required=true)] public string DBInstanceIdentifier { get { return this._dbInstanceIdentifier; } set { this._dbInstanceIdentifier = value; } } // Check to see if DBInstanceIdentifier property is set internal bool IsSetDBInstanceIdentifier() { return this._dbInstanceIdentifier != null; } /// <summary> /// Gets and sets the property ForceFailover. /// <para> /// A value that indicates whether the reboot is conducted through a Multi-AZ failover. /// /// </para> /// /// <para> /// Constraint: You can't enable force failover if the instance isn't configured for Multi-AZ. /// </para> /// </summary> public bool ForceFailover { get { return this._forceFailover.GetValueOrDefault(); } set { this._forceFailover = value; } } // Check to see if ForceFailover property is set internal bool IsSetForceFailover() { return this._forceFailover.HasValue; } } }
35.438017
218
0.626866
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/RDS/Generated/Model/RebootDBInstanceRequest.cs
4,288
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die einer Assembly zugeordnet sind. [assembly: AssemblyTitle("HelloGUI_VL")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HelloGUI_VL")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly // für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von // COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. [assembly: ComVisible(false)] //Um mit dem Erstellen lokalisierbarer Anwendungen zu beginnen, legen Sie //<UICulture>ImCodeVerwendeteKultur</UICulture> in der .csproj-Datei //in einer <PropertyGroup> fest. Wenn Sie in den Quelldateien beispielsweise Deutsch //(Deutschland) verwenden, legen Sie <UICulture> auf \"de-DE\" fest. Heben Sie dann die Auskommentierung //des nachstehenden NeutralResourceLanguage-Attributs auf. Aktualisieren Sie "en-US" in der nachstehenden Zeile, //sodass es mit der UICulture-Einstellung in der Projektdatei übereinstimmt. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //Speicherort der designspezifischen Ressourcenwörterbücher //(wird verwendet, wenn eine Ressource auf der Seite nicht gefunden wird, // oder in den Anwendungsressourcen-Wörterbüchern nicht gefunden werden kann.) ResourceDictionaryLocation.SourceAssembly //Speicherort des generischen Ressourcenwörterbuchs //(wird verwendet, wenn eine Ressource auf der Seite nicht gefunden wird, // designspezifischen Ressourcenwörterbuch nicht gefunden werden kann.) )] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden, // indem Sie "*" wie unten gezeigt eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
48.125
119
0.737291
[ "MIT" ]
MeckeJadeHS/VorlesungsDemos
HelloGUI_Demo/HelloGUI_VL/Properties/AssemblyInfo.cs
2,715
C#
using System; using System.Collections.Generic; using System.Windows.Forms; using System.Xml.Serialization; using taskt.UI.CustomControls; using taskt.UI.Forms; using taskt.Properties; using taskt.Core.Automation.Commands; namespace taskt.Core.Automation.Commands_cn { [Serializable] [Attributes.ClassAttributes.Group("(Web Browser Commands)Web浏览器命令")] [Attributes.ClassAttributes.Description("此命令允许您将Selenium Web浏览器会话导航到给定的URL或资源。")] [Attributes.ClassAttributes.UsesDescription("如果要将现有Selenium实例导航到已知URL或Web资源,请使用此命令")] [Attributes.ClassAttributes.ImplementationDescription("此命令实现Selenium以实现自动化。")] public class SeleniumBrowserNavigateURLCommand_cn : ScriptCommand { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("请输入实例名称")] [Attributes.PropertyAttributes.InputSpecification("输入** Create Browser **命令中指定的唯一实例名称")] [Attributes.PropertyAttributes.SampleUsage("**myInstance** or **seleniumInstance**")] [Attributes.PropertyAttributes.Remarks("未能输入正确的实例名称或未能首先调用** Create Browser **命令将导致错误")] [Attributes.PropertyAttributes.PropertyUIHelper(Attributes.PropertyAttributes.PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] public string v_InstanceName { get; set; } [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("请输入要导航到的URL")] [Attributes.PropertyAttributes.InputSpecification("输入您希望selenium实例导航到的目标URL")] [Attributes.PropertyAttributes.SampleUsage("https://mycompany.com/orders")] [Attributes.PropertyAttributes.Remarks("")] [Attributes.PropertyAttributes.PropertyUIHelper(Attributes.PropertyAttributes.PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] public string v_URL { get; set; } public SeleniumBrowserNavigateURLCommand_cn() { this.CommandName = "SeleniumBrowserNavigateURLCommand"; // this.SelectionName = "Navigate to URL"; this.SelectionName = Settings.Default.Navigate_to_Web_URL_cn; this.v_InstanceName = "default"; this.CommandEnabled = true; this.CustomRendering = true; } public override void RunCommand(object sender) { var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; var vInstance = v_InstanceName.ConvertToUserVariable(engine); var browserObject = engine.GetAppInstance(vInstance); var seleniumInstance = (OpenQA.Selenium.IWebDriver)browserObject; seleniumInstance.Navigate().GoToUrl(v_URL.ConvertToUserVariable(sender)); } public override List<Control> Render(frmCommandEditor editor) { base.Render(editor); RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_InstanceName", this, editor)); RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_URL", this, editor)); return RenderedControls; } public override string GetDisplayValue() { return base.GetDisplayValue() + " [URL: '" + v_URL + "', Instance Name: '" + v_InstanceName + "']"; } private void WaitForReadyState(SHDocVw.InternetExplorer ieInstance) { DateTime waitExpires = DateTime.Now.AddSeconds(15); do { System.Threading.Thread.Sleep(500); } while ((ieInstance.ReadyState != SHDocVw.tagREADYSTATE.READYSTATE_COMPLETE) && (waitExpires > DateTime.Now)); } } }
41.034091
146
0.70036
[ "Apache-2.0" ]
Stanley29/Iron_Man
taskt/Core/Automation/Commands_cn/SeleniumBrowserNavigateURLCommand_cn.cs
3,871
C#
//------------------------------------------------------------------------------ // // Copyright (c) 2002-2012 CodeSmith Tools, LLC. All rights reserved. // // The terms of use for this software are contained in the file // named sourcelicense.txt, which can be found in the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // You must not remove this notice, or any other, from this software. // //------------------------------------------------------------------------------ using System.Reflection; [assembly: AssemblyTitle("SchemaExplorer.MySQLSchemaProvider.dll")] [assembly: AssemblyDescription("MySql Schema Provider.")]
42.235294
80
0.58078
[ "BSD-3-Clause" ]
a156845044/MySQLSchemaProvider
Properties/AssemblyInfo.cs
718
C#
using System; namespace _11_Constructores { class Program { static void Main(string[] args) { Alumno a= new Alumno (); a.Id=1; a.PrimerNombre="ANTONIO"; a.SegundoNombre="VILLATORO"; Alumno b= new Alumno (); b.Id=2; b.PrimerNombre= "DAVID"; b.SegundoNombre= "BENITEZ"; Alumno c= new Alumno (3); b.PrimerNombre= "PEDRO"; Alumno d= new Alumno ("JUAN", "JIMENEZ"); Console.WriteLine(a.Id); Console.WriteLine(b.Id); Console.WriteLine(c.Id); Console.WriteLine(d.PrimerNombre + " " + d.SegundoNombre); } } }
23.709677
70
0.485714
[ "MIT" ]
AntonioVillatoro/c-sharp
EJERCICIOS/11_Constructores/Program.cs
737
C#
using Iced.Intel; using StringReloads.Hook.Base; using System; namespace MwareHook { unsafe class KeyInterceptor : Intercept { int Register; public KeyInterceptor(void* Address, Register Register) : base(Address) { this.Register = Register switch { Register.EDI => 0, Register.ESI => 1, Register.EBP => 2, Register.ESP => 3, Register.EBX => 4, Register.EDX => 5, Register.ECX => 6, Register.EAX => 7, _ => throw new NotSupportedException("Invalid Key Handler Register") }; } public override InterceptDelegate HookFunction => new InterceptDelegate(OnKeyExpanderBegin); public Action<byte[]> OnKeyIntercepted; void OnKeyExpanderBegin(void* ESP) { uint* Stack = (uint*)ESP; byte* KeyBuffer = (byte*)*(Stack + Register); byte[] Key = new byte[0x20]; for (int i = 0; i < Key.Length; i++) Key[i] = KeyBuffer[i]; OnKeyIntercepted?.Invoke(Key); } } }
30.526316
100
0.528448
[ "Unlicense" ]
AyamiKaze/MwareStuff
MwareHook/KeyInterceptor.cs
1,162
C#
using PKISharp.WACS.Configuration; using PKISharp.WACS.DomainObjects; using PKISharp.WACS.Services; using System.Threading.Tasks; namespace PKISharp.WACS.Plugins.ValidationPlugins.Http { internal class WebDavOptionsFactory : HttpValidationOptionsFactory<WebDav, WebDavOptions> { public WebDavOptionsFactory(IArgumentsService arguments) : base(arguments) { } public override bool PathIsValid(string webRoot) { return webRoot.StartsWith("\\\\") || webRoot.StartsWith("dav://") || webRoot.StartsWith("webdav://") || webRoot.StartsWith("https://") || webRoot.StartsWith("http://"); } public override string[] WebrootHint(bool allowEmtpy) { return new[] { "Enter a webdav path that leads to the web root of the host for http authentication", " Example, \\\\domain.com:80\\", " Example, \\\\domain.com:443\\" }; } public override Task<WebDavOptions> Default(Target target) { return Task.FromResult(new WebDavOptions(BaseDefault(target)) { Credential = new NetworkCredentialOptions(_arguments) }); } public override async Task<WebDavOptions> Aquire(Target target, IInputService inputService, RunLevel runLevel) { return new WebDavOptions(await BaseAquire(target, inputService)) { Credential = new NetworkCredentialOptions(_arguments, inputService) }; } } }
34.166667
118
0.592683
[ "Apache-2.0" ]
SparebankenVest/win-acme
src/main.lib/Plugins/ValidationPlugins/Http/WebDav/WebDavOptionsFactory.cs
1,642
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GwApiNET; using GwApiNET.Gw2Stats.ResponseObjects; using GwApiNET.ResponseObjects; namespace GwApiNETTest.Gw2StatsTest { public class Temp { /// <summary> /// Default Constructor /// </summary> public Temp() { } public static Gw2StatsMatchEntry MatchEntryExpected = new Gw2StatsMatchEntry { RetriveTime = DateTime.Parse("2013-07-27 19:53:53"), Region = new EntryDictionary<string, IList<MatchRegion>> { { "na", new List<MatchRegion> { new MatchRegion { StartDate = DateTime.Parse("2013-07-27 01:00:00"), EndDate = DateTime.Parse("2013-08-03 01:00:00"), LastUpdate = DateTime.Parse("2013-07-27 19:53:18"), MatchId = "1-8", UniqueId = new Guid("cb6a06d46962b5f05b059126bd178e78"), Worlds = new Dictionary<int, MatchWorld> { { 1024, new MatchWorld { Id = 1024, Name = "Eredon Terrace", Color = OwnerColor.Red, Score = 17709, PPT = 215, Objectives = new MatchObjectives { Camps = 9, Towers = 7, Keeps = 4, Castles = 0 }, Rating = new Gw2StatsRatingsData { StartRank = 24, CurrentRank = 23, StartRating = 972.9781, StartDeviation = 172.66, CurrentDeviation = 173.53140625056, Volatility = 0.7139, CurrentRating = 997.37440857386, Evolution = 24.39630857386 } } }, }, } } }, { "eu", new List<MatchRegion> { new MatchRegion { StartDate = DateTime.Parse("2013-07-26 18:00:00"), EndDate = DateTime.Parse("2013-08-02 18:00:00"), LastUpdate = DateTime.Parse("2013-07-27 19:53:46"), MatchId = "2-1", UniqueId = new Guid("69bb8feec3ccc63da2849aac4b670eb7"), Worlds = new Dictionary<int, MatchWorld> { { 2104, new MatchWorld { Id = 2104, Name = "Vizunah Square [FR]", Color = OwnerColor.Red, Score = 41959, PPT = 225, Objectives = { Camps = 9, Towers = 8, Keeps = 4, Castles = 0 }, Rating = new Gw2StatsRatingsData { StartRank = 1, CurrentRank = 1, StartRating = 1981.7072, StartDeviation = 177.0751, CurrentDeviation = 170.62313431175, Volatility = 0.7243, CurrentRating = 1995.7396155154, Evolution = 14.0324155154 } } } } } } } } }; } }
59.770492
107
0.203099
[ "MIT" ]
prbarcelon/GwApiNET
GwApiNET/GwApiNETTest/Gw2StatsTest/Temp.cs
7,294
C#
namespace MovieInfo.Services.Messaging { using System.Threading.Tasks; public interface ISmsSender { Task SendSmsAsync(string number, string message); } }
18.1
57
0.696133
[ "MIT" ]
borisbotev/SoftUni
C#Web Advanced/MovieInfo/Services/MovieInfo.Services.Messaging/ISmsSender.cs
183
C#
using System.Collections.Generic; using System.Linq; using System.Security.Claims; using Abp.Extensions; namespace CallOfShare.Identity { public class ExternalLoginInfoHelper { public static (string name, string surname) GetNameAndSurnameFromClaims(List<Claim> claims) { string name = null; string surname = null; var givennameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName); if (givennameClaim != null && !givennameClaim.Value.IsNullOrEmpty()) { name = givennameClaim.Value; } var surnameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname); if (surnameClaim != null && !surnameClaim.Value.IsNullOrEmpty()) { surname = surnameClaim.Value; } if (name == null || surname == null) { var nameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.Name); if (nameClaim != null) { var nameSurName = nameClaim.Value; if (!nameSurName.IsNullOrEmpty()) { var lastSpaceIndex = nameSurName.LastIndexOf(' '); if (lastSpaceIndex < 1 || lastSpaceIndex > (nameSurName.Length - 2)) { name = surname = nameSurName; } else { name = nameSurName.Substring(0, lastSpaceIndex); surname = nameSurName.Substring(lastSpaceIndex); } } } } return (name, surname); } } }
34.226415
99
0.483462
[ "MIT" ]
nguyendiennghia/CallOfShare
aspnet-core/src/CallOfShare.Web.Core/Identity/ExternalLoginInfoHelper.cs
1,816
C#
// Copyright 2021 Google LLC // // 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 // // https://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. // Generated code. DO NOT EDIT! namespace Google.Cloud.Monitoring.V3.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.Cloud.Monitoring.V3; using System; using System.Linq; using System.Threading.Tasks; public sealed partial class GeneratedNotificationChannelServiceClientStandaloneSnippets { /// <summary>Snippet for ListNotificationChannelDescriptorsAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task ListNotificationChannelDescriptorsResourceNames2Async() { // Create client NotificationChannelServiceClient notificationChannelServiceClient = await NotificationChannelServiceClient.CreateAsync(); // Initialize request argument(s) OrganizationName name = OrganizationName.FromOrganization("[ORGANIZATION]"); // Make the request PagedAsyncEnumerable<ListNotificationChannelDescriptorsResponse, NotificationChannelDescriptor> response = notificationChannelServiceClient.ListNotificationChannelDescriptorsAsync(name); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((NotificationChannelDescriptor item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListNotificationChannelDescriptorsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (NotificationChannelDescriptor item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<NotificationChannelDescriptor> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (NotificationChannelDescriptor item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; } } }
45.026316
198
0.662478
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/monitoring/v3/google-cloud-monitoring-v3-csharp/Google.Cloud.Monitoring.V3.StandaloneSnippets/NotificationChannelServiceClient.ListNotificationChannelDescriptorsResourceNames2AsyncSnippet.g.cs
3,422
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Windows.Forms; using v2rayN.Handler; using v2rayN.Mode; namespace v2rayN.Forms { public partial class MainForm : BaseForm { private V2rayHandler v2rayHandler; #region Window 事件 public MainForm() { InitializeComponent(); this.ShowInTaskbar = false; this.WindowState = FormWindowState.Minimized; this.Text = Utils.GetVersion(); } private void MainForm_Load(object sender, EventArgs e) { ConfigHandler.LoadConfig(ref config); v2rayHandler = new V2rayHandler(); v2rayHandler.ProcessEvent += v2rayHandler_ProcessEvent; } private void MainForm_Shown(object sender, EventArgs e) { InitServersView(); RefreshServers(); LoadV2ray(); //自动从网络同步本地时间 if (config.autoSyncTime) { CDateTime.SetLocalTime(); } } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing) { e.Cancel = true; HideForm(); return; } } private void MainForm_Resize(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized) { HideForm(); } } #endregion #region 显示服务器 listview 和 menu /// <summary> /// 刷新服务器 /// </summary> private void RefreshServers() { RefreshServersView(); RefreshServersMenu(); } /// <summary> /// 初始化服务器列表 /// </summary> private void InitServersView() { lvServers.Items.Clear(); lvServers.GridLines = true; lvServers.FullRowSelect = true; lvServers.View = View.Details; lvServers.Scrollable = true; lvServers.MultiSelect = false; lvServers.HeaderStyle = ColumnHeaderStyle.Nonclickable; lvServers.Columns.Add("活动", 40, HorizontalAlignment.Center); lvServers.Columns.Add("别名(remarks)", 120, HorizontalAlignment.Left); lvServers.Columns.Add("地址(address)", 110, HorizontalAlignment.Left); lvServers.Columns.Add("端口(port)", 80, HorizontalAlignment.Left); lvServers.Columns.Add("用户ID(id)", 110, HorizontalAlignment.Left); lvServers.Columns.Add("额外ID(alterId)", 110, HorizontalAlignment.Left); lvServers.Columns.Add("加密方式(security)", 120, HorizontalAlignment.Left); lvServers.Columns.Add("传输协议(network)", 120, HorizontalAlignment.Left); lvServers.Columns.Add("延迟(Latency)", 100, HorizontalAlignment.Left); } /// <summary> /// 刷新服务器列表 /// </summary> private void RefreshServersView() { lvServers.Items.Clear(); for (int k = 0; k < config.vmess.Count; k++) { string def = string.Empty; if (config.index.Equals(k)) { def = "√"; } VmessItem item = config.vmess[k]; ListViewItem lvItem = new ListViewItem(new string[] { def, item.remarks, item.address, item.port.ToString(), item.id, item.alterId.ToString(), item.security, item.network, ""}); lvServers.Items.Add(lvItem); } } /// <summary> /// 刷新托盘服务器菜单 /// </summary> private void RefreshServersMenu() { menuServers.DropDownItems.Clear(); for (int k = 0; k < config.vmess.Count; k++) { VmessItem item = config.vmess[k]; string name = string.Format("{0}({1}:{2})", item.remarks, item.address, item.port); ToolStripMenuItem ts = new ToolStripMenuItem(name); ts.Tag = k; if (config.index.Equals(k)) { ts.Checked = true; } ts.Click += new EventHandler(ts_Click); menuServers.DropDownItems.Add(ts); } } private void ts_Click(object sender, EventArgs e) { try { ToolStripItem ts = (ToolStripItem)sender; int index = Convert.ToInt32(ts.Tag); SetDefaultServer(index); } catch { } } #endregion #region v2ray 操作 /// <summary> /// 载入V2ray /// </summary> private void LoadV2ray() { if (Global.reloadV2ray) { ClearMsg(); } v2rayHandler.LoadV2ray(config); Global.reloadV2ray = false; } /// <summary> /// 关闭V2ray /// </summary> private void CloseV2ray() { ConfigHandler.ToJsonFile(config); v2rayHandler.V2rayStop(); } #endregion #region 功能按钮 private void lvServers_DoubleClick(object sender, EventArgs e) { int index = GetLvSelectedIndex(); if (index < 0) { return; } AddServerForm fm = new AddServerForm(); fm.EditIndex = index; if (fm.ShowDialog() == DialogResult.OK) { //刷新 RefreshServers(); LoadV2ray(); } } private void menuAddServer_Click(object sender, EventArgs e) { AddServerForm fm = new AddServerForm(); fm.EditIndex = -1; if (fm.ShowDialog() == DialogResult.OK) { //刷新 RefreshServers(); LoadV2ray(); } } private void menuRemoveServer_Click(object sender, EventArgs e) { int index = GetLvSelectedIndex(); if (index < 0) { return; } if (UI.ShowYesNo("是否确定移除服务器?") == DialogResult.No) { return; } if (ConfigHandler.RemoveServer(ref config, index) == 0) { //刷新 RefreshServers(); LoadV2ray(); } } private void menuCopyServer_Click(object sender, EventArgs e) { int index = GetLvSelectedIndex(); if (index < 0) { return; } if (ConfigHandler.CopyServer(ref config, index) == 0) { //刷新 RefreshServers(); } } private void menuSetDefaultServer_Click(object sender, EventArgs e) { int index = GetLvSelectedIndex(); if (index < 0) { return; } SetDefaultServer(index); } private void menuPingServer_Click(object sender, EventArgs e) { bgwPing.RunWorkerAsync(); } private void menuExport2ClientConfig_Click(object sender, EventArgs e) { int index = GetLvSelectedIndex(); if (index < 0) { return; } SaveFileDialog fileDialog = new SaveFileDialog(); fileDialog.Filter = "Config|*.json"; fileDialog.FilterIndex = 2; fileDialog.RestoreDirectory = true; if (fileDialog.ShowDialog() != DialogResult.OK) { return; } string fileName = fileDialog.FileName; if (Utils.IsNullOrEmpty(fileName)) { return; } Config configCopy = Utils.DeepCopy<Config>(config); configCopy.index = index; string msg; if (V2rayConfigHandler.Export2ClientConfig(configCopy, fileName, out msg) != 0) { UI.Show(msg); } else { UI.Show(string.Format("客户端配置文件保存在:{0}", fileName)); } } private void menuExport2ServerConfig_Click(object sender, EventArgs e) { int index = GetLvSelectedIndex(); if (index < 0) { return; } SaveFileDialog fileDialog = new SaveFileDialog(); fileDialog.Filter = "Config|*.json"; fileDialog.FilterIndex = 2; fileDialog.RestoreDirectory = true; if (fileDialog.ShowDialog() != DialogResult.OK) { return; } string fileName = fileDialog.FileName; if (Utils.IsNullOrEmpty(fileName)) { return; } Config configCopy = Utils.DeepCopy<Config>(config); configCopy.index = index; string msg; if (V2rayConfigHandler.Export2ServerConfig(configCopy, fileName, out msg) != 0) { UI.Show(msg); } else { UI.Show(string.Format("服务端配置文件保存在:{0}", fileName)); } } private void menuShareQRCode_Click(object sender, EventArgs e) { int index = GetLvSelectedIndex(); if (index < 0) { return; } QRCodeForm fm = new QRCodeForm(); fm.Index = index; fm.ShowDialog(); } private void tsbOptionSetting_Click(object sender, EventArgs e) { OptionSettingForm fm = new OptionSettingForm(); if (fm.ShowDialog() == DialogResult.OK) { //刷新 RefreshServers(); LoadV2ray(); } } private void tsbReload_Click(object sender, EventArgs e) { Global.reloadV2ray = true; LoadV2ray(); } private void tsbClose_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } /// <summary> /// 设置活动服务器 /// </summary> /// <param name="index"></param> /// <returns></returns> private int SetDefaultServer(int index) { if (index < 0) { UI.Show("请先选择服务器"); return -1; } if (ConfigHandler.SetDefaultServer(ref config, index) == 0) { //刷新 RefreshServers(); LoadV2ray(); } return 0; } /// <summary> /// 取得ListView选中的行 /// </summary> /// <returns></returns> private int GetLvSelectedIndex() { int index = -1; try { if (lvServers.SelectedIndices.Count <= 0) { UI.Show("请先选择服务器"); return index; } index = lvServers.SelectedIndices[0]; return index; } catch { return index; } } #endregion #region 提示信息 /// <summary> /// 消息委托 /// </summary> /// <param name="notify"></param> /// <param name="msg"></param> void v2rayHandler_ProcessEvent(bool notify, string msg) { try { AppendText(msg); if (notify) { notifyMsg(msg); } } catch { } } delegate void AppendTextDelegate(string text); void AppendText(string text) { if (this.txtMsgBox.InvokeRequired) { Invoke(new AppendTextDelegate(AppendText), new object[] { text }); } else { //this.txtMsgBox.AppendText(text); ShowMsg(text); } } /// <summary> /// 提示信息 /// </summary> /// <param name="msg"></param> private void ShowMsg(string msg) { this.txtMsgBox.AppendText(msg); if (!msg.EndsWith("\r\n")) { this.txtMsgBox.AppendText("\r\n"); } } /// <summary> /// 清除信息 /// </summary> private void ClearMsg() { this.txtMsgBox.Clear(); } /// <summary> /// 托盘信息 /// </summary> /// <param name="msg"></param> private void notifyMsg(string msg) { notifyMain.Text = msg; } #endregion #region 托盘事件 private void notifyMain_MouseClick(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { ShowForm(); } } private void menuOpenMain_Click(object sender, EventArgs e) { ShowForm(); } private void menuExit_Click(object sender, EventArgs e) { CloseV2ray(); this.Visible = false; this.Close(); //this.Dispose(); System.Environment.Exit(System.Environment.ExitCode); } private void menuUpdate_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start(Global.UpdateUrl); } private void menuAbout_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start(Global.AboutUrl); } private void ShowForm() { this.Show(); this.WindowState = FormWindowState.Normal; this.Activate(); //this.notifyIcon1.Visible = false; } private void HideForm() { this.WindowState = FormWindowState.Minimized; this.Hide(); this.notifyMain.Visible = true; } #endregion #region 后台测速 private void bgwPing_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { try { for (int k = 0; k < config.vmess.Count; k++) { long time = Utils.Ping(config.vmess[k].address); bgwPing.ReportProgress(k, string.Format("{0}ms", time)); } } catch { } } private void bgwPing_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e) { try { int k = e.ProgressPercentage; string time = Convert.ToString(e.UserState); lvServers.Items[k].SubItems[lvServers.Items[k].SubItems.Count - 1].Text = time; } catch { } } #endregion #region 移动服务器 private void menuMoveTop_Click(object sender, EventArgs e) { MoveServer(EMove.Top); } private void menuMoveUp_Click(object sender, EventArgs e) { MoveServer(EMove.Up); } private void menuMoveDown_Click(object sender, EventArgs e) { MoveServer(EMove.Down); } private void menuMoveBottom_Click(object sender, EventArgs e) { MoveServer(EMove.Bottom); } private void MoveServer(EMove eMove) { int index = GetLvSelectedIndex(); if (index < 0) { UI.Show("请先选择服务器"); return; } if (ConfigHandler.MoveServer(ref config, index, eMove) == 0) { //刷新 RefreshServers(); LoadV2ray(); } } #endregion } }
26.905751
109
0.456629
[ "MIT" ]
bluekk935/v2rayN
v2rayN/v2rayN/Forms/MainForm.cs
17,227
C#
/* Copyright (c) 2012 DEVSENSE The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.IO; using PHP.Core.Text; namespace PHP.Core { /// <summary> /// Structuralized representation of PHPDoc DocBlock. /// </summary> /// <remarks>define() statements, functions, classes, class methods, and class vars, include() statements, and global variables can all be documented. /// See http://en.wikipedia.org/wiki/PHPDoc for specifications.</remarks> public sealed class PHPDocBlock : AST.LangElement { #region Nested classes: Element public abstract class Element { #region Constants /// <summary> /// String sequence starting the PHPDoc block on the first line. /// </summary> private const string PhpDocStartString = "/**"; /// <summary> /// Every PHPDoc line not starting with this character is ignored. /// </summary> private const char PHPDocFirstChar = '*'; /// <summary> /// Every PHPDoc tag starts with this character. /// </summary> private const char PHPDocTagChar = '@'; /// <summary> /// String representing new line between PHPDoc comment lines. /// </summary> protected const string NewLineString = "\n"; #endregion #region Properties /// <summary> /// Element position within the source code. /// </summary> public Span Span { get; internal set; } #endregion #region Tags /// <summary> /// Tag elements initialized using reflection. /// </summary> private static Dictionary<string, Func<string, string, Element>>/*!!*/elementFactories; static Element() { // initilize dictionary of known tags and their factories: elementFactories = new Dictionary<string, Func<string, string, Element>>(20, StringComparer.OrdinalIgnoreCase); var types = typeof(PHPDocBlock).GetNestedTypes(System.Reflection.BindingFlags.Public); foreach (var t in types) { if (t.IsSealed && !t.IsAbstract && typeof(Element).IsAssignableFrom(t)) { // add to the dictionary according to its Name: var fld = t.GetField("Name"); if (fld != null) { var factory = CreateElementFactory(t); elementFactories.Add(TagNameHelper(fld), factory); } else { var f1 = t.GetField("Name1"); var f2 = t.GetField("Name2"); var f3 = t.GetField("Name3"); if (f1 != null && f2 != null) { var factory = CreateElementFactory(t); elementFactories.Add(TagNameHelper(f1), factory); elementFactories.Add(TagNameHelper(f2), factory); if (f3 != null) elementFactories.Add(TagNameHelper(f3), factory); } else { // only these Elements do not represent a tag: Debug.Assert( t.Name == typeof(ShortDescriptionElement).Name || t.Name == typeof(LongDescriptionElement).Name || t.Name == typeof(UnknownTextTag).Name); } } } } // ensure we have some tags: Debug.Assert(elementFactories.ContainsKey("@param")); Debug.Assert(elementFactories.ContainsKey("@ignore")); Debug.Assert(elementFactories.ContainsKey("@var")); // ... } private static Func<string, string, Element>/*!*/CreateElementFactory(Type/*!*/elementType) { Debug.Assert(elementType != null && typeof(Element).IsAssignableFrom(elementType)); var ctors = elementType.GetConstructors(); Debug.Assert(ctors != null && ctors.Length == 1); var ctor = ctors[0]; var args = ctor.GetParameters(); Debug.Assert(args != null && args.Length <= 2); // create function that creates the Element 't': if (args.Length == 0) { return (tagName, line) => (Element)ctor.Invoke(null); } else if (args.Length == 1) { Debug.Assert(args[0].Name == "line"); return (tagName, line) => (Element)ctor.Invoke(new object[] { line }); } else { Debug.Assert(args[0].Name == "tagName"); Debug.Assert(args[1].Name == "line"); return (tagName, line) => (Element)ctor.Invoke(new object[] { tagName, line }); } } /// <summary> /// Reads value of given field, assuming it is string constant, which value starts with <see cref="PHPDocTagChar"/>. /// </summary> private static string TagNameHelper(System.Reflection.FieldInfo fld) { Debug.Assert(fld != null); var tagname = fld.GetValue(null) as string; Debug.Assert(!string.IsNullOrEmpty(tagname)); Debug.Assert(tagname[0] == PHPDocTagChar); return tagname; } private static KeyValuePair<string, Func<string, string, Element>> FindTagInfo(string/*!*/line) { Debug.Assert(!string.IsNullOrEmpty(line)); Debug.Assert(line[0] == PHPDocTagChar); int endIndex = 1; char c; while (endIndex < line.Length && !char.IsWhiteSpace(c = line[endIndex]) && c != ':' && c != '(' && c != ';' && c != '.') endIndex++; string tagName = (endIndex < line.Length) ? line.Remove(endIndex) : line; Func<string,string,Element> tmp; if (elementFactories.TryGetValue(tagName, out tmp)) return new KeyValuePair<string, Func<string, string, Element>>(tagName, tmp); else return new KeyValuePair<string, Func<string, string, Element>>(tagName, (_name, _line) => new UnknownTextTag(_name, _line)); } #endregion #region Parsing /// <summary> /// Prepares given <paramref name="line"/>. /// /// If the line creates new PHPDoc element, new <see cref="Element"/> /// is instantiated and returned in <paramref name="next"/>. /// </summary> /// <param name="line">Line to parse. Cannot be <c>null</c> reference.</param> /// <param name="next">Outputs new element that will follow current element. Parsing will continue using this element.</param> /// <param name="lineIndex">Index of the line within PHPDoc token.</param> /// <param name="startCharIndex">Gets index of first content character within <paramref name="line"/>.</param> /// <param name="endCharIndex">Gets index of last content character within <paramref name="line"/>.</param> /// <returns>If the line can be parsed, method returns <c>true</c>.</returns> internal static bool TryParseLine(ref string/*!*/line, out Element next, int lineIndex, out int startCharIndex, out int endCharIndex) { if (line == null) throw new ArgumentNullException("line"); next = null; startCharIndex = endCharIndex = 0; int startIndex = 0; while (startIndex < line.Length && char.IsWhiteSpace(line[startIndex])) startIndex++; // skip whitespaces // we souhldn't, but we allow first line to contain text after the /** sequence: if (lineIndex == 0 && line.StartsWith(PhpDocStartString, StringComparison.Ordinal)) { startIndex = PhpDocStartString.Length - 1; // jump to the '*' character Debug.Assert(line[startIndex] == PHPDocFirstChar); } // invalid PHPDoc line (not starting with '*'): if (startIndex == line.Length || line[startIndex] != PHPDocFirstChar) return false; // trim starting '*' and whitespaces startIndex++; // skip '*' while (startIndex < line.Length && char.IsWhiteSpace(line[startIndex])) startIndex++; // skip whitespaces if (startIndex == line.Length) { line = string.Empty; } else { // trim end int endIndex = line.Length; while (endIndex > startIndex && char.IsWhiteSpace(line[endIndex - 1])) endIndex--; // skip whitespaces from end line = line.Substring(startIndex, endIndex - startIndex).Replace("{@*}", "*/"); } // check "*/" at the end if (line.Length == 1 && line[0] == '/') return false; // empty line if (line.Length >= 2 && line[line.Length - 1] == '/' && line[line.Length - 2] == '*') // "*/" found at the end line = line.Remove(line.Length - 2); // TODO: any whitespace sequence is converted into single space, but only outside <pre> and {} blocks // TODO: handle "{@tag ...}" for @link, @see etc... // check tags: next = CreateElement(line); startCharIndex = startIndex; endCharIndex = startIndex + line.Length; // return true; } /// <summary> /// Parses given <paramref name="line"/> and updates current content. /// </summary> /// <param name="line">Line to parse. Line is trimmed and does not start with '*'. Cannot be <c>null</c> reference.</param> /// <param name="next">Next element to continue parsing with.</param> internal abstract void ParseLine(string/*!*/line, out Element next); /// <summary> /// Reads tag at the beginning of line and tries to create corresponding <see cref="Element"/> instance. /// </summary> /// <param name="line">PHPDoc comment line. Assuming the line starts with a PHPDoc tag. Otherwise, or if tag is not recognized, <c>null</c> is returned..</param> private static Element CreateElement(string/*!*/line) { Debug.Assert(line != null); if (line.Length == 0 || line[0] != PHPDocTagChar) return null; // try to match known tags: var tagInfo = FindTagInfo(line); if (tagInfo.Key != null) { Debug.Assert(tagInfo.Value != null); // initialize new tag element return tagInfo.Value(tagInfo.Key, line); } // unrecognized tag: return null; } /// <summary> /// Returns <c>true</c> if current element does not contain any information and can be ignored. /// </summary> internal virtual bool IsEmpty { get { return false; } } /// <summary> /// Called when parsing of this element ended. /// </summary> internal virtual void OnEndParsing() { } #endregion } /// <summary> /// Short description. /// </summary> public sealed class ShortDescriptionElement : Element { /// <summary> /// Character defining the end of PHPDoc short description. /// </summary> private const char EndChar = '.'; public string Text { get; private set; } public ShortDescriptionElement() { } internal override void ParseLine(string/*!*/line, out Element next) { next = null; // ignore first line of length 0 (empty space after /**) if (this.Text == null && string.IsNullOrWhiteSpace(line)) return; // Short Description can be followed by Long Description. // It can be only 3 lines long, otherwise only the first line is taken // It is terminated by empty line or a dot. if (this.Text != null && (this.Text.LastCharacter() == (int)EndChar)) { next = new LongDescriptionElement(line); } else if (line.Length == 0) { next = new LongDescriptionElement(null); } else if (this.Text.CharsCount('\n') >= 2) { // short description has already 3 lines, // only first line is taken, the rest is for LongDescriptionElement int firstLineEndIndex = this.Text.IndexOf('\n'); Debug.Assert(firstLineEndIndex != -1); next = new LongDescriptionElement(this.Text.Substring(firstLineEndIndex + 1) + NewLineString + line); this.Text = this.Text.Remove(firstLineEndIndex); } else { this.Text = (this.Text != null) ? (this.Text + NewLineString + line) : line; } } internal override bool IsEmpty { get { return string.IsNullOrWhiteSpace(this.Text); } } internal override void OnEndParsing() { base.OnEndParsing(); if (this.Text != null) this.Text = this.Text.Trim(); } public override string ToString() { return this.Text ?? string.Empty; } } /// <summary> /// Long description. /// </summary> public sealed class LongDescriptionElement : Element { public string Text { get; private set; } public LongDescriptionElement(string initialText) { this.Text = string.IsNullOrWhiteSpace(initialText) ? null : initialText; } internal override void ParseLine(string line, out Element next) { // Long Description can only be followed by PHPDoc tag (handled in TryParseLine) next = null; this.Text = (this.Text != null) ? (this.Text + NewLineString + line) : line; } internal override bool IsEmpty { get { return string.IsNullOrWhiteSpace(this.Text); } } internal override void OnEndParsing() { base.OnEndParsing(); if (this.Text != null) this.Text = this.Text.Trim(); } public override string ToString() { return this.Text ?? string.Empty; } } public abstract class EmptyTag : Element { internal override void ParseLine(string line, out Element next) { next = null; // ignored } } /// <summary> /// Documents an abstract class, class variable or method. /// </summary> public sealed class AbstractTag : EmptyTag { public const string Name = "@abstract"; public override string ToString() { return Name; } } /// <summary> /// Documents access control for an element. @access private indicates that documentation of element be prevented. /// </summary> public sealed class AccessTag : Element { public const string Name1 = "@access"; public const string Name2 = "@private"; private const string IsPublic = "public"; private const string IsPrivate = "private"; private const string IsProtected = "protected"; /// <summary> /// Resolved access modifier. (public, private or protected) /// </summary> public PhpMemberAttributes Access { get { return attributes & PhpMemberAttributes.VisibilityMask; } } private readonly PhpMemberAttributes attributes; private string AccessString { get { switch (Access) { case PhpMemberAttributes.Private: return IsPrivate; case PhpMemberAttributes.Protected: return IsProtected; default: return IsPublic; } } } public AccessTag(string/*!*/line) { if (line.StartsWith(Name1)) { if (line.Length > Name1.Length) { var access = line.Substring(Name1.Length + 1).Trim().ToLowerInvariant(); // public, private or protected switch (access) { case IsPublic: attributes = PhpMemberAttributes.Public; break; case IsPrivate: attributes = PhpMemberAttributes.Private; break; case IsProtected: attributes = PhpMemberAttributes.Protected; break; default: Debug.WriteLine("Unexpected access modifier in PHPDoc @access tag, line:" + line); break; } } else { attributes = PhpMemberAttributes.Public; } } else if (line.StartsWith(Name2)) { attributes = PhpMemberAttributes.Private; } else { Debug.Fail("Unexpected " + line); } } internal override void ParseLine(string line, out Element next) { next = null; // ignored } public override string ToString() { return Name1 + " " + AccessString; } } public abstract class SingleLineTag : Element { protected readonly string text; internal SingleLineTag(string/*!*/tagName, string/*!*/line) { Debug.Assert(line.StartsWith(tagName)); if (line.Length > tagName.Length) this.text = line.Substring(tagName.Length + 1).Trim(); } internal override void ParseLine(string line, out Element next) { next = null; // other lines are ignored } internal override bool IsEmpty { get { return string.IsNullOrWhiteSpace(text); } } } /// <summary> /// Documents the author of the current element. /// </summary> public sealed class AuthorTag : SingleLineTag { public const string Name = "@author"; /// <summary> /// author name &lt;author@email&gt; /// </summary> public string Author { get { return text; } } public AuthorTag(string/*!*/line) :base(Name, line) { } public override string ToString() { return Name + " " + Author; } } /// <summary> /// Documents copyright information. /// </summary> public sealed class CopyrightTag : SingleLineTag { public const string Name = "@copyright"; /// <summary> /// name date /// </summary> public string Copyright { get { return text; } } public CopyrightTag(string/*!*/line) : base(Name, line) { } public override string ToString() { return Name + " " + Copyright; } } /// <summary> /// Documents a method as deprecated. /// </summary> public sealed class DeprecatedTag : SingleLineTag { public const string Name1 = "@deprecated"; public const string Name2 = "@deprec"; /// <summary> /// version /// </summary> public string Version { get { return text; } } public DeprecatedTag(string tagName, string/*!*/line) : base(tagName, line) { } public override string ToString() { return Name1 + " " + Version; } } /// <summary> /// Documents the location of an external saved example file. /// </summary> public sealed class ExampleTag : SingleLineTag { public const string Name = "@example"; /// <summary> /// /path/to/example /// </summary> public string Example { get { return text; } } public ExampleTag(string/*!*/line) : base(Name, line) { } public override string ToString() { return Name + " " + Example; } } /// <summary> /// Documents an exception thrown by a method. /// </summary> public sealed class ExceptionTag : TypeVarDescTag { public const string Name1 = "@exception"; public const string Name2 = "@throws"; /// <summary> /// version /// </summary> public string Exception { get { return this.TypeNames; } } public ExceptionTag(string tagName, string/*!*/line) : base(tagName, line, false) { } public override string ToString() { return Name2 + " " + this.Exception; } } /// <summary> /// Documents any tag in a form of "type [$varname] [multilined-description]". /// </summary> public abstract class TypeVarDescTag : Element { /// <summary> /// Character separating type names within <see cref="TypeNames"/> property. /// </summary> public const char TypeNamesSeparator = '|'; /// <summary> /// Optional. Type names separated by '|'. /// </summary> public string TypeNames { get { var names = _typeNames; if (names == null || names.Length == 0) return null; return string.Join(TypeNamesSeparator.ToString(), names); } } /// <summary> /// Position of the <see cref="TypeNames"/> information. /// </summary> public Span TypeNamesSpan { get { var positions = _typeNamesPos; if (positions == null || positions.Length == 0) return Span.Invalid; var names = _typeNames; var offset = this.Span.Start; return Span.FromBounds(offset + positions[0], offset + positions[positions.Length - 1] + names[names.Length - 1].Length); } } /// <summary> /// Array of type names. Cannot be <c>null</c>. Can be an empty array. /// </summary> public string[]/*!!*/TypeNamesArray { get { return _typeNames; } } private readonly string[]/*!!*/_typeNames; /// <summary> /// Array of type names span within the source code. /// </summary> public Span[]/*!*/TypeNameSpans { get { var positions = _typeNamesPos; var names = _typeNames; Debug.Assert(names.Length == positions.Length); Span[] spans = new Span[positions.Length]; var offset = this.Span.Start; for (int i = 0; i < spans.Length; i++) spans[i] = new Span(offset + positions[i], names[i].Length); return spans; } } private readonly int[]/*!!*/_typeNamesPos; /// <summary> /// Optional. Variable name, starts with '$'. /// </summary> public readonly string VariableName; /// <summary> /// Starting column of the <see cref="VariableName"/> within the element. /// </summary> private readonly int _variableNameOffset = -1; /// <summary> /// Position of the <see cref="VariableName"/> information. /// </summary> public Span VariableNameSpan { get { if (this._variableNameOffset < 0) return Span.Invalid; Debug.Assert(this.VariableName != null); return new Span(this.Span.Start + this._variableNameOffset, this.VariableName.Length); } } /// <summary> /// Optional. Element description. /// </summary> public string Description { get; private set; } protected TypeVarDescTag(string/*!*/tagName, string/*!*/line, bool allowVariableName) { Debug.Assert(line.StartsWith(tagName)); // [type] [$varname] [type] [description] int index = tagName.Length; // current index within line // try to find [type] TryReadTypeName(line, ref index, out _typeNames, out _typeNamesPos); if (allowVariableName) { // try to find [$varname] if (TryReadVariableName(line, ref index, out this.VariableName, out this._variableNameOffset)) { // try to find [type] if it was not found yet, user may specified it after variable name if (_typeNames == null || _typeNames.Length == 0) { TryReadTypeName(line, ref index, out _typeNames, out _typeNamesPos); } } } if (index < line.Length) { this.Description = line.Substring(index).TrimStart(null/*default whitespace characters*/); if (string.IsNullOrEmpty(this.Description)) this.Description = string.Empty; } } #region Helpers private static string NextWord(string/*!*/text, ref int index) { // skip whitespaces: while (index < text.Length && char.IsWhiteSpace(text[index])) index++; // read word: int startIndex = index; while (index < text.Length && !char.IsWhiteSpace(text[index])) index++; // cut off the word: if (startIndex < index) return text.Substring(startIndex, index - startIndex); else return null; } /// <summary> /// Tries to recognize a type name starting at given <paramref name="index"/>. /// </summary> /// <param name="text">Source text.</param> /// <param name="index">Index within <paramref name="text"/> to start read.</param> /// <param name="typenames">Resulting type name(s) separated by <c>|</c>.</param> /// <param name="typenamesPos">Type names span or invalid span.</param> /// <returns>Whether the type name was parsed.</returns> internal static bool TryReadTypeName(string/*!*/text, ref int index, out string[] typenames, out int[] typenamesPos) { // [type] var typenameend = index; var typename = NextWord(text, ref typenameend); if (IsTypeName(typename)) { List<int> positions = new List<int>(1); List<string> names = new List<string>(1); int typenameOffset = typenameend - typename.Length; index = typenameend; var split = typename.Split(new char[] { TypeNamesSeparator }); int splitat = typenameOffset; foreach (var s in split) { if (!string.IsNullOrEmpty(s)) { names.Add(s); positions.Add(splitat); splitat += s.Length; // type name length } splitat++; // separator } // [type] or [type] var orend = typenameend; var or = NextWord(text, ref orend); if (or == "or") { var nextend = orend; var next = NextWord(text, ref nextend); if (IsTypeName(next) && next.IndexOf(TypeNamesSeparator) == -1) { index = nextend; names.Add(next); positions.Add(nextend - next.Length); } } typenames = names.ToArray(); typenamesPos = positions.ToArray(); return true; } // typenames = EmptyArray<string>.Instance; typenamesPos = EmptyArray<int>.Instance; return false; } /// <summary> /// tries to read a variable name starting at given <paramref name="index"/>. /// </summary> /// <param name="text">Source text.</param> /// <param name="index">Index within <paramref name="text"/> to start read.</param> /// <param name="variableName">Result variable name.</param> /// <param name="variableNameOffset">Variable name start index within text.</param> /// <returns>Whether the variable name was parsed.</returns> private static bool TryReadVariableName(string/*!*/text, ref int index, out string variableName, out int variableNameOffset) { var wordend = index; var word = NextWord(text, ref wordend); if (word != null /* => word.Length != 0 */ && word[0] == '$') { index = wordend; variableName = word; variableNameOffset = wordend - word.Length; return true; } variableName = null; variableNameOffset = -1; return false; } /// <summary> /// Checks whether given <paramref name="str"/> may be a type name. /// </summary> /// <param name="str">String to check.</param> /// <returns>Whether given string may be a PHP type name.</returns> internal static bool IsTypeName(string str) { if (string.IsNullOrEmpty(str)) return false; if (str[0] != '_' && !char.IsLetter(str[0]) && str[0] != QualifiedName.Separator) return false; for (int i = 1; i < str.Length; i++) { char c = str[i]; if (c != '_' && !char.IsLetterOrDigit(c) && c != '[' && c != ']' && c != TypeNamesSeparator && c != QualifiedName.Separator) return false; } // ok return true; } #endregion internal override void ParseLine(string line, out Element next) { next = null; // add the line into description: Description = string.IsNullOrWhiteSpace(Description) ? line : (Description + NewLineString + line); } internal override void OnEndParsing() { base.OnEndParsing(); if (string.IsNullOrWhiteSpace(this.Description)) this.Description = null; else this.Description = this.Description.Trim(); // TODO: compress TypeNames, VariableName, Description } internal override bool IsEmpty { get { return _typeNames.Length == 0 && string.IsNullOrEmpty(this.VariableName) && string.IsNullOrWhiteSpace(this.Description); } } } /// <summary> /// Documents a global variable or its use in a function or method. /// @global type $globalvarname /// </summary> public sealed class GlobalTag : TypeVarDescTag { public const string Name = "@global"; public GlobalTag(string/*!*/line) :base(Name, line, true) { } public override string ToString() { string result = Name; var type = this.TypeNames; if (type != null) result += " " + type; var varname = this.VariableName; if (varname != null) result += " " + varname; return result; } } /// <summary> /// Prevents the documentation of an element. /// </summary> public sealed class IgnoreTag : EmptyTag { public const string Name = "@ignore"; public override string ToString() { return Name; } } public abstract class TextTag : Element { /// <summary> /// Tag text information. /// </summary> public string Text { get; private set; } public TextTag(string/*!*/tagName, string/*!*/line) { Debug.Assert(line.StartsWith(tagName)); int index = tagName.Length; if (index < line.Length) { var c = line[index]; if (c == ':' || c == '(' || c == ';' || c == '.') index++; } // trim leading whitespaces while (index < line.Length && char.IsWhiteSpace(line[index])) index++; this.Text = (index < line.Length) ? line.Substring(index) : string.Empty; } internal override void ParseLine(string line, out Element next) { next = null; this.Text = string.IsNullOrEmpty(this.Text) ? line : (this.Text + NewLineString + line); } internal override void OnEndParsing() { base.OnEndParsing(); if (string.IsNullOrWhiteSpace(this.Text)) this.Text = string.Empty; else this.Text = this.Text.Trim(); } } /// <summary> /// Represents an unknown PHPDoc tag followed by text. /// </summary> public sealed class UnknownTextTag : TextTag { /// <summary> /// Tag name. /// </summary> public string TagName { get; private set; } internal UnknownTextTag(string tagName, string/*!*/line) : base(tagName, line) { this.TagName = tagName; } public override string ToString() { return string.IsNullOrEmpty(Text) ? (TagName) : (TagName + " " + Text); } } /// <summary> /// Private information for advanced developers. /// </summary> public sealed class InternalTag : TextTag { public const string Name = "@internal"; public InternalTag(string/*!*/line) :base(Name, line) { } public override string ToString() { return Name + " " + Text; } } ///// <summary> ///// URL information. ///// </summary> //public sealed class LinkTag : SingleLineTag //{ // public const string Name = "@link"; // /// <summary> // /// URL // /// </summary> // public string Url { get { return this.text; } } // public LinkTag(string/*!*/line) // :base(Name, line) // { // } //} /// <summary> /// Specifies an alias for a variable. For example, $GLOBALS['myvariable'] becomes $myvariable. /// </summary> public sealed class NameTag : SingleLineTag { public const string Name = "@name"; /// <summary> /// Variable name. Empty string or a name starting with '$' character. /// </summary> public string VariableName { get { return string.IsNullOrEmpty(this.text) ? string.Empty : ((this.text[0] == '$') ? this.text : ('$' + this.text)); } } public NameTag(string/*!*/line) : base(Name, line) { } } /// <summary> /// phpdoc.de compatibility "phpDocumentor tags". /// </summary> public sealed class MagicTag : EmptyTag { public const string Name = "@magic"; public override string ToString() { return Name; } } /// <summary> /// Documents a group of related classes and functions. /// </summary> public sealed class PackageTag : SingleLineTag { public const string Name = "@package"; /// <summary> /// Name of the package. /// </summary> public string PackageName { get { return this.text; } } public PackageTag(string/*!*/line) : base(Name, line) { } } /// <summary> /// Documents a group of related classes and functions within a package. /// </summary> public sealed class SubPackageTag : SingleLineTag { public const string Name = "@subpackage"; /// <summary> /// Name of the sub-package. /// </summary> public string SubPackageName { get { return this.text; } } public SubPackageTag(string/*!*/line) : base(Name, line) { } } /// <summary> /// Documents a parameter. /// @param type [$varname] description /// </summary> public sealed class ParamTag : TypeVarDescTag { public const string Name = "@param"; public ParamTag(string/*!*/line) : base(Name, line, true) { } public override string ToString() { StringBuilder result = new StringBuilder(Name, Name.Length + ((this.Description != null) ? this.Description.Length : 0) + 16); if (this.TypeNames != null) { result.Append(' '); result.Append(this.TypeNames); } if (this.VariableName != null) { result.Append(' '); result.Append(this.VariableName); } if (this.Description != null) { result.Append(' '); result.Append(this.Description); } // return result.ToString(); } } /// <summary> /// Documents function return value. This tag should not be used for constructors or methods defined with a void return type /// @return type [description] /// </summary> public sealed class ReturnTag : TypeVarDescTag { public const string Name = "@return"; public ReturnTag(string/*!*/line) : base(Name, line, false) { } public override string ToString() { return Name + " " + TypeNames + NewLineString + Description; } } /// <summary> /// Documents an association to any element (global variable, include, page, class, function, define, method, variable). /// </summary> public sealed class SeeTag : SingleLineTag { public const string Name = "@see"; /// <summary> /// element /// </summary> public string ElementName { get { return this.text; } } public SeeTag(string/*!*/line) : base(Name, line) { } } /// <summary> /// Documents when a method was added to a class. /// </summary> public sealed class SinceTag : SingleLineTag { public const string Name = "@since"; /// <summary> /// version /// </summary> public string Version { get { return this.text; } } public SinceTag(string/*!*/line) : base(Name, line) { } } /// <summary> /// Documents a static class or method. /// </summary> public sealed class StaticTag : EmptyTag { public const string Name = "@static"; public override string ToString() { return Name; } } /// <summary> /// Documents a static variable's use in a function or class. /// </summary> public sealed class StaticVarTag : TypeVarDescTag { public const string Name = "@staticvar"; public StaticVarTag(string/*!*/line) :base(Name, line, false) { } public override string ToString() { return Name + " " + this.TypeNames; } } /// <summary> /// Documents things that need to be done to the code at a later date. /// </summary> public sealed class TodoTag : TextTag { public const string Name = "@todo"; public TodoTag(string/*!*/line) :base(Name, line) { } public override string ToString() { return Name + " " + Text; } } /// <summary> /// Documents a link to an external source. /// </summary> public sealed class LinkTag : TextTag { public const string Name = "@link"; public LinkTag(string/*!*/line) : base(Name, line) { } public override string ToString() { return Name + " " + Text; } } /// <summary> /// Documents a license information. /// </summary> public sealed class LicenseTag : TextTag { public const string Name = "@license"; public LicenseTag(string/*!*/line) : base(Name, line) { } public override string ToString() { return Name + " " + Text; } } public sealed class VarTag : TypeVarDescTag { public const string Name = "@var"; public VarTag(string/*!*/line) : base(Name, line, true) { } public override string ToString() { return Name + " " + this.TypeNames; } } /// <summary> /// Dynamic property description within a class. /// </summary> public sealed class PropertyTag : TypeVarDescTag { public const string Name1 = "@property"; public const string Name2 = "@property-read"; public const string Name3 = "@property-write"; public PropertyTag(string tagName, string/*!*/line) : base(tagName, line, true) { } public override string ToString() { return Name1 + " " + this.TypeNames; } } /// <summary> /// Dynamic method description within a class. /// </summary> public sealed class MethodTag : Element { public const string Name = "@method"; /// <summary> /// Optional. Type names separated by '|'. /// </summary> public string TypeNames { get { var names = _typeNames; if (names == null || names.Length == 0) return null; return string.Join(TypeVarDescTag.TypeNamesSeparator.ToString(), names); } } /// <summary> /// Array of type names. Cannot be <c>null</c>. Can be an empty array. /// </summary> public string[]/*!!*/TypeNamesArray { get { return _typeNames; } } private readonly string[]/*!*/_typeNames; /// <summary> /// Array of type names span within the source code. /// </summary> public Span[]/*!*/TypeNameSpans { get { var positions = _typeNamesPos; var names = _typeNames; Debug.Assert(names.Length == positions.Length); Span[] spans = new Span[positions.Length]; var offset = this.Span.Start; for (int i = 0; i < spans.Length; i++) spans[i] = new Span(offset + positions[i], names[i].Length); return spans; } } private readonly int[]/*!*/_typeNamesPos; /// <summary> /// Array of method parameters; /// </summary> public readonly AST.FormalParam[]/*!*/Parameters; /// <summary> /// Method name. /// </summary> public readonly string MethodName; /// <summary> /// Span within the source code of the method name. /// </summary> public Span MethodNameSpan { get { var pos = _methodNamePos; if (pos < 0) return Span.Invalid; Debug.Assert(MethodName != null); return new Span(pos + this.Span.Start, this.MethodName.Length); } } private readonly int _methodNamePos; /// <summary> /// Optional. Element description. /// </summary> public string Description { get; private set; } public MethodTag(string/*!*/tagName, string/*!*/line) { Debug.Assert(line.StartsWith(tagName)); _methodNamePos = -1; // [type] [name()] [name(params ...)] [description] int index = tagName.Length; // current index within line int descStart = index; // start of description, moved when [type] or [name] found // try to find [type] TypeVarDescTag.TryReadTypeName(line, ref index, out _typeNames, out _typeNamesPos); descStart = index; string word = NextWord(line, ref index); // [name()] if (word != null && word.EndsWith("()", StringComparison.Ordinal)) { this.MethodName = word.Remove(word.Length - 2); _methodNamePos = index - word.Length; descStart = index; word = NextWord(line, ref index); } // [name(params ...)] while (descStart < line.Length && char.IsWhiteSpace(line[descStart])) descStart++; // skip whitespaces this.Parameters = null; int nameStart = descStart; int paramsFrom = -1; // skip [name] while (descStart < line.Length && char.IsLetterOrDigit(line[descStart])) descStart++; // parse parameters if (descStart < line.Length && line[descStart] == '(') { paramsFrom = descStart; if (nameStart < paramsFrom) { if (this.MethodName == null) this.MethodName = line.Substring(nameStart, paramsFrom - nameStart); _methodNamePos = nameStart; } } else { descStart = nameStart; } if (string.IsNullOrEmpty(this.MethodName)) return; if (paramsFrom > 0 && paramsFrom < line.Length && line[paramsFrom] == '(') { // "name(" found int paramsEnd = line.IndexOf(')', paramsFrom); if (paramsEnd > 0) { descStart = paramsEnd + 1; string[] paramsDecl = line.Substring(paramsFrom + 1, paramsEnd - paramsFrom - 1).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (paramsDecl != null && paramsDecl.Length > 0) { this.Parameters = new AST.FormalParam[paramsDecl.Length]; for (int i = 0; i < paramsDecl.Length; i++) this.Parameters[i] = ParseParam(paramsDecl[i]); } } } if (this.Parameters == null) this.Parameters = EmptyArray<AST.FormalParam>.Instance; if (descStart < line.Length) this.Description = line.Substring(descStart).TrimStart(null/*default whitespace characters*/); } /// <summary> /// Parses parameter description in a form of [type][$name][=initializer]. /// </summary> /// <param name="paramDecl"></param> /// <returns></returns> private static AST.FormalParam/*!*/ParseParam(string/*!*/paramDecl) { Debug.Assert(!string.IsNullOrEmpty(paramDecl)); string typehint = null; string paramname = null; bool byref = false; int i = 0; var word = NextWord(paramDecl, ref i); if (word != null) { // [type] if (word.Length > 0 && word[0] != '$') { typehint = word; word = NextWord(paramDecl, ref i); } // [$name][=initializer] if (word != null && word.Length > 0 && word[0] == '$') { int eqIndex = word.IndexOf('='); paramname = ((eqIndex == -1) ? word : word.Remove(eqIndex)); byref = paramname.IndexOf('&') != -1; paramname = paramname.TrimStart(new char[]{ '$', '&'}); } } return new AST.FormalParam(Text.Span.Invalid, paramname, typehint, byref, null, new List<AST.CustomAttribute>()); } #region Helpers private static string NextWord(string/*!*/text, ref int index) { // skip whitespaces: while (index < text.Length && char.IsWhiteSpace(text[index])) index++; // read word: int startIndex = index; while (index < text.Length && !char.IsWhiteSpace(text[index])) index++; // cut off the word: if (startIndex < index) return text.Substring(startIndex, index - startIndex); else return null; } #endregion internal override void ParseLine(string line, out Element next) { next = null; // add the line into description: Description = string.IsNullOrWhiteSpace(Description) ? line : (Description + NewLineString + line); } internal override void OnEndParsing() { base.OnEndParsing(); if (string.IsNullOrWhiteSpace(this.Description)) this.Description = null; else this.Description = this.Description.Trim(); } internal override bool IsEmpty { get { return _typeNames.Length == 0 && string.IsNullOrEmpty(this.MethodName) && string.IsNullOrWhiteSpace(this.Description); } } public override string ToString() { return Name + " " + this.MethodName + "()\n" + this.Description; } } public sealed class VersionTag : SingleLineTag { public const string Name = "@version"; public string Version { get { return this.text; } } public VersionTag(string/*!*/line) : base(Name, line) { } public override string ToString() { return Name + " " + this.Version; } } public sealed class TestTag : EmptyTag { public const string Name = "@test"; public TestTag(string/*!*/line) : base() { } public override string ToString() { return Name; } } public sealed class GroupTag : SingleLineTag { public const string Name = "@group"; public string Group { get { return this.text; } } public GroupTag(string/*!*/line) : base(Name, line) { } public override string ToString() { return Name + " " + this.Group; } } #endregion #region Properties /// <summary> /// Empty singleton <see cref="Element"/> array. /// </summary> private static Element[]/*!*/EmptyElements { get { return EmptyArray<Element>.Instance; } } /// <summary> /// Original PHPDoc text, including comment tags. /// </summary> /// <remarks>Used internally for lazy initialization.</remarks> private string _docCommentString; /// <summary> /// Parsed data. Lazily initialized. /// </summary> private Element[] elements; /// <summary> /// Elements within the PHPDoc block. Some elements may be ignored due to missing information. /// Cannot be <c>null</c> reference. /// </summary> public Element[]/*!*/Elements { get { if (this.elements == null) lock (this) if (this.elements == null) // double checked lock { var elementsList = ParseNoLock(this._docCommentString, this.Span.Start); if (elementsList != null && elementsList.Count > 0) this.elements = elementsList.ToArray(); else this.elements = EmptyElements; // dispose the string this._docCommentString = null; } return this.elements; } } #endregion #region Initialization /// <summary> /// Initializes new instance of <see cref="PHPDocBlock"/>. /// </summary> /// <param name="doccomment">PHPDoc token content.</param> /// <param name="span">Position of the comment in the source code.</param> public PHPDocBlock(string doccomment, TextSpan span) :base(span) { this._docCommentString = doccomment; } /// <summary> /// Parses given <paramref name="doccomment"/> into a list of <see cref="Element"/> instances. /// </summary> /// <param name="doccomment">Content of the PHPDoc token.</param> /// <param name="offset">Start position of <paramref name="doccomment"/> within the source code.</param> private static List<Element>/*!*/ParseNoLock(string/*!*/doccomment, int offset) { Debug.Assert(doccomment != null); // initialize line endings information var/*!*/lineBreaks = Text.LineBreaks.Create(doccomment); // var result = new List<Element>(); Element tmp; Element/*!*/current = new ShortDescriptionElement(); current.Span = Span.Invalid; for (int lineIndex = 0; lineIndex < lineBreaks.LinesCount; lineIndex++) { var lineSpan = lineBreaks.GetLineSpan(lineIndex); string/*!*/line = lineSpan.GetText(doccomment); int startCharIndex, endCharIndex; if (Element.TryParseLine(ref line, out tmp, lineIndex, out startCharIndex, out endCharIndex)) // validate the line, process tags { Debug.Assert(line != null); if (tmp == null) // no new element created { // pass the line into the current element current.ParseLine(line, out tmp); // update position of the element if (current.Span.IsValid == false) // ShortDescriptionElement has not initialized Span { if (!current.IsEmpty) // initialize Start iff element has some text current.Span = new Span(offset + lineSpan.Start + startCharIndex, endCharIndex - startCharIndex); } else // other elements has to update their end position { if (tmp != null) current.Span = new Span(current.Span.Start, offset + lineSpan.Start + endCharIndex - current.Span.Start); // update its end position } } if (tmp != null) // new element created, it is already initialized with the current line { if (!current.IsEmpty) { current.OnEndParsing(); result.Add(current); } tmp.Span = new Span(offset + lineSpan.Start + startCharIndex, endCharIndex - startCharIndex); current = tmp; // it is current element from now } } } // add the last found element if (!current.IsEmpty) { current.OnEndParsing(); result.Add(current); } // return result; } #endregion #region Helper access methods public T GetElement<T>() where T: Element { var elements = this.Elements; for (int i = 0; i < elements.Length; i++) if (elements[i] is T) return (T)elements[i]; return null; } /// <summary> /// Enumerate all the '@param' tags. /// </summary> public IEnumerable<ParamTag> Params { get { return this.Elements.OfType<ParamTag>(); } } /// <summary> /// Gets '@return' tag or <c>null</c>. /// </summary> public ReturnTag Returns { get { return GetElement<ReturnTag>(); } } /// <summary> /// Whether the PHPDoc block contains '@ignore' tag. /// </summary> public bool IsIgnored { get { return GetElement<IgnoreTag>() != null; } } /// <summary> /// Gets short description or <c>null</c>. /// </summary> public string ShortDescription { get { var tag = GetElement<ShortDescriptionElement>(); return (tag != null) ? tag.Text : null; } } /// <summary> /// Gets long description or <c>null</c>. /// </summary> public string LongDescription { get { var tag = GetElement<LongDescriptionElement>(); return (tag != null) ? tag.Text : null; } } /// <summary> /// Gets whole description, as a concatenation of <see cref="ShortDescription"/> and <see cref="LongDescription"/>. /// </summary> public string Summary { get { var shortdesc = ShortDescription; var longdesc = LongDescription; if (shortdesc != null || longdesc != null) { if (string.IsNullOrEmpty(shortdesc)) return longdesc; if (string.IsNullOrEmpty(longdesc)) return shortdesc; return shortdesc + "\n" + longdesc; } return null; } } /// <summary> /// Gets '@access' value or 'Public' if no such tag is found. /// </summary> public PhpMemberAttributes Access { get { var access = GetElement<AccessTag>(); return (access != null) ? access.Access : PhpMemberAttributes.Public; } } /// <summary> /// Reconstructs PHPDoc block from parsed elements, including comment tags. /// </summary> public string PHPDocPreview { get { var result = new StringBuilder(); result.AppendLine("/**"); foreach (var element in this.Elements) { var str = element.ToString(); if (str == null) continue; foreach (var line in str.Split('\n')) { result.Append(" * "); result.AppendLine(line); } } result.Append(" */"); return result.ToString(); } } #endregion #region ToString /// <summary> /// Returns summary of PHPDoc. /// </summary> public override string ToString() { return this.Summary; } #endregion #region LangElement public override void VisitMe(AST.TreeVisitor visitor) { throw new NotImplementedException(); } #endregion } internal static class PHPDocBlockHelper { /// <summary> /// Gets <see cref="PHPDocBlock"/> associated with <paramref name="properties"/>. /// </summary> public static PHPDocBlock GetPHPDoc(this IPropertyCollection/*!*/properties) { return properties.GetProperty<PHPDocBlock>(); } /// <summary> /// Sets <see cref="PHPDocBlock"/> to <paramref name="properties"/>. /// </summary> public static void SetPHPDoc(this IPropertyCollection/*!*/properties, PHPDocBlock phpdoc) { if (phpdoc != null) { properties.SetProperty<PHPDocBlock>(phpdoc); // remember LangElement associated with phpdoc var element = properties as AST.LangElement; if (element != null) phpdoc.SetProperty<AST.LangElement>(element); } else { properties.RemoveProperty<PHPDocBlock>(); } } } }
35.16058
191
0.44723
[ "Apache-2.0" ]
endel/Phalanger
Source/Core.Parsers/PHPDocBlock.cs
70,288
C#
using HandlebarsDotNet; using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; namespace Dotnet.CodeGen.CustomHandlebars.Helpers { /// <summary> /// /// </summary> #if DEBUG [HandlebarsHelperSpecification("[{t: 'c'}, {t: 'a'}, {t: 'b'}]", "{{#each .}}{{t}}{{/each}}", "cab")] [HandlebarsHelperSpecification("[{t: 'c'}, {t: 'a'}, {t: 'b'}]", "{{#each_with_sort . 't'}}{{#each .}}{{t}}{{/each}}{{/each_with_sort}}", "abc")] [HandlebarsHelperSpecification("[]", "{{#each_with_sort . .}}{{/each_with_sort}}", "")] [HandlebarsHelperSpecification("{ a : {}, b : {} }", "{{#each_with_sort .}}{{#each .}}{{@key}}{{/each}}{{/each_with_sort}}", "ab")] [HandlebarsHelperSpecification("{ b : {}, a : {} }", "{{#each_with_sort .}}{{#each .}}{{@key}}{{/each}}{{/each_with_sort}}", "ab")] [HandlebarsHelperSpecification(GLOBAL_SPECS.SWAGGER_SAMPLE, "{{#each_with_sort parameters}}{{#each .}}{{@key}},{{/each}}{{/each_with_sort}}", "accountIdParameter,credentialParameter,feedTypeParameter,marketplaceBusinessCodeParameter,publicationIdParameter,")] #endif public class EachWithSort : SimpleBlockHelperBase { public EachWithSort() : base("each_with_sort") { } public override HandlebarsBlockHelper Helper => (TextWriter output, HelperOptions options, object context, object[] arguments) => { EnsureArgumentsCountMin(arguments, 1); EnsureArgumentsCountMax(arguments, 2); Sort(output, options, context, arguments, SortDirection.Ascending, Name); }; internal enum SortDirection { Ascending, Descending } internal static void Sort(TextWriter output, HelperOptions options, object context, object[] arguments, SortDirection direction, string name) { var to_order = arguments[0]; if (!(to_order is IEnumerable enumerable)) options.Template(output, context); var jPath = arguments.Length == 2 ? arguments[1]?.ToString() : null; object newContext; switch (to_order) { case JObject jObject: { JToken keySelector(KeyValuePair<string, JToken> t) => (jPath == null) ? t.Key : t.Value.SelectToken(jPath); newContext = direction == SortDirection.Ascending ? ((IDictionary<string, JToken>)jObject).OrderBy(keySelector) : ((IDictionary<string, JToken>)jObject).OrderByDescending(keySelector) ; } break; case JArray jArray: { if (jPath == null) throw new CodeGenHelperException($"First argument being an Array, the second argument cannot be empty in the {name} helper."); JToken keySelector(JToken t) => t.SelectToken(jPath); newContext = direction == SortDirection.Ascending ? jArray.OrderBy(keySelector) : jArray.OrderByDescending(keySelector) ; } break; default: throw new NotImplementedException($"{name} helper couldn't handle ordering on a {to_order?.GetType().Name} token."); } options.Template(output, newContext); } } }
45.679012
264
0.545135
[ "Apache-2.0" ]
thomasraynal/dotnet-codegen
src/Dotnet.CodeGen/CustomHandlebars/Helpers/EachWithSort.cs
3,702
C#
 using System.Collections; using System.Collections.Generic; using UnityEngine; public class AutoConnect : MonoBehaviour { // Use this for initialization void Start ( ) { PhotonNetwork.ConnectUsingSettings( "DinoGen1.5" ); } public void OnConnectedToMaster ( ) { Debug.Log( "OnConnectedToMaster" ); PhotonNetwork.JoinRandomRoom(); } public void OnJoinedLobby ( ) { Debug.Log( "OnJoinedLobby" ); PhotonNetwork.JoinRandomRoom(); } public void OnJoinedRoom ( ) { Debug.Log( "OnJoinedRoom() called by PUN. Now this client is in a room. From here on, your game would be running. For reference, all callbacks are listed in enum: PhotonNetworkingMessage" ); } public virtual void OnPhotonRandomJoinFailed ( ) { Debug.Log( "OnPhotonRandomJoinFailed() was called by PUN. No random room available, so we create one. Calling: PhotonNetwork.CreateRoom(null, new RoomOptions() {maxPlayers = 4}, null);" ); } public void Update ( ) { if ( Input.GetKeyDown(KeyCode.Space) ) { Debug.Log(PhotonNetwork.playerList.Length); } } }
28.333333
198
0.643697
[ "MIT" ]
L1247/photon-unity-framework
Scripts/Mono/AutoConnect.cs
1,192
C#
// // Copyright 2015 Blu Age Corporation - Plano, Texas // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Runtime.Serialization; using Summer.Batch.Extra.Copybook; namespace Summer.Batch.Extra.Ebcdic.Exception { /// <summary> /// Exception is thrown by EbcdicDecoder to signal an error while trying to parse an Ebcdic field. /// </summary> [Serializable] public class FieldParsingException : EbcdicException { private readonly byte[] _readData; private readonly FieldFormat _fieldFormat; /// <summary> /// Custom constructor with a message /// </summary> /// <param name="message"></param> public FieldParsingException(string message) : base(message) { } /// <summary> /// Custom constructor with a message and an inner exception /// </summary> /// <param name="message"></param> /// <param name="cause"></param> public FieldParsingException(string message, System.Exception cause) : base(message, cause) { } /// <summary> /// Custom constructor using FieldFormat and read data /// </summary> /// <param name="fieldFormat"></param> /// <param name="readData"></param> public FieldParsingException(FieldFormat fieldFormat, byte[] readData) : base(string.Format("Error while reading field {0} - read data: {1}", fieldFormat.Name, readData)) { _fieldFormat = fieldFormat; _readData = new byte[readData.Length]; readData.CopyTo(_readData, 0); } /// <summary> /// Constructor for deserialization. /// </summary> /// <param name="info">the info holding the serialization data</param> /// <param name="context">the serialization context</param> public FieldParsingException(SerializationInfo info, StreamingContext context) : base(info, context) { _fieldFormat = (FieldFormat) info.GetValue("FieldFormat", typeof(FieldFormat)); _readData = (byte[]) info.GetValue("ReadData", typeof (byte[])); } /// <summary> /// A message that describes the current exception. /// </summary> public override string Message { get { return string.Format("Error while reading field {0} - read data: {1}", _fieldFormat.Name, _readData); } } /// <summary> /// Sets the <see cref="SerializationInfo"/> with information about the exception. /// </summary> /// <param name="info"> /// The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown. /// </param> /// <param name="context"> /// The <see cref="StreamingContext"/> that contains contextual information about the source or destination. /// </param> public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("FieldFormat",_fieldFormat); info.AddValue("ReadData",_readData); } } }
37.92381
120
0.586891
[ "Apache-2.0" ]
Andrey-Ostapenko/SummerBatch
Summer.Batch.Extra/Ebcdic/Exception/FieldParsingException.cs
3,984
C#
#region License // <copyright> // iGeospatial Geometries Package // // This is part of the Open Geospatial Library for .NET. // // Package Description: // This is a collection of C# classes that implement the fundamental // operations required to validate a given geo-spatial data set to // a known topological specification. // It aims to provide a complete implementation of the Open Geospatial // Consortium (www.opengeospatial.org) specifications for Simple // Feature Geometry. // // Contact Information: // Paul Selormey (paulselormey@gmail.com or paul@toolscenter.org) // // Credits: // This library is based on the JTS Topology Suite, a Java library by // // Vivid Solutions Inc. (www.vividsolutions.com) // // License: // See the license.txt file in the package directory. // </copyright> #endregion using System; namespace iGeospatial.Geometries.Indexers.SweepLine { internal class SweepLineEvent : System.IComparable { private enum SweepLineEventType { INSERT = 1, DELETE = 2 } private double xValue; private SweepLineEventType eventType; private SweepLineEvent insertEvent; // null if this is an INSERT event private int deleteEventIndex; private SweepLineInterval sweepInt; public SweepLineEvent(double x, SweepLineEvent insertEvent, SweepLineInterval sweepInt) { this.xValue = x; this.insertEvent = insertEvent; this.eventType = SweepLineEventType.INSERT; if (insertEvent != null) this.eventType = SweepLineEventType.DELETE; this.sweepInt = sweepInt; } public bool IsInsert { get { return insertEvent == null; } } public bool IsDelete { get { return insertEvent != null; } } public SweepLineEvent InsertEvent { get { return insertEvent; } } public int DeleteEventIndex { get { return deleteEventIndex; } set { this.deleteEventIndex = value; } } internal SweepLineInterval Interval { get { return sweepInt; } } /// <summary> /// ProjectionEvents are ordered first by their x-value, and then by their eventType. /// It is important that Insert events are sorted before Delete events, so that /// items whose Insert and Delete events occur at the same x-value will be /// correctly handled. /// </summary> public int CompareTo(SweepLineEvent pe) { if (xValue < pe.xValue) return - 1; if (xValue > pe.xValue) return 1; if (eventType < pe.eventType) return - 1; if (eventType > pe.eventType) return 1; return 0; } public int CompareTo(object o) { return CompareTo((SweepLineEvent)o); } } }
22.632
89
0.644044
[ "MIT" ]
IBAS0742/iGeospatial_change
Geometries/Indexers/SweepLine/SweepLineEvent.cs
2,829
C#
namespace X4D.Diagnostics.Counters { /// <summary> /// An <see cref="ICounter{T}"/> that supports Incrementing. /// </summary> /// <typeparam name="T"></typeparam> public interface ISupportsIncrement<T> : ICounter<T> { /// <summary> /// Increment the Counter by the specified <paramref name="value"/>. /// </summary> /// <param name="value">The value to Increment the Counter by.</param> /// <returns>The resulting Counter Value after Incrementing.</returns> T Increment(T value); } }
31.666667
78
0.592982
[ "MIT" ]
wilson0x4d/diagnostics
X4D.Diagnostics/Counters/ISupportsIncrement.cs
572
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Azure.Core.TestFramework; using NUnit.Framework; [assembly: LiveParallelizable(ParallelScope.Fixtures)]
26.125
61
0.794258
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/storage/Azure.Storage.Common/tests/Shared/AssemblyInfo.cs
211
C#
// Copyright 2014 Max Toro Q. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Xml; using System.Xml.Linq; namespace NTransform.Xml.Linq { sealed class XObjectPatternParser : PatternParser<XObject> { public XObjectPatternParser(NamespaceBindings ns) : base(ns) { } public override Func<XObject, bool> attribute() { return n => n.NodeType == XmlNodeType.Attribute; } protected override Func<XObject, bool> attribute(XmlQualifiedName name) { XAttribute attr; return n => attribute()(n) && (attr = (XAttribute)n).Name.LocalName == name.Name && attr.Name.NamespaceName == name.Namespace; } public override Func<XObject, bool> comment() { return n => n.NodeType == XmlNodeType.Comment; } public override Func<XObject, bool> document_node() { return n => n.NodeType == XmlNodeType.Document; } public override Func<XObject, bool> element() { return n => n.NodeType == XmlNodeType.Element; } protected override Func<XObject, bool> element(XmlQualifiedName name) { XElement el; return n => element()(n) && (el = (XElement)n).Name.LocalName == name.Name && el.Name.NamespaceName == name.Namespace; } public override Func<XObject, bool> processing_instruction() { return n => n.NodeType == XmlNodeType.ProcessingInstruction; } protected override Func<XObject, bool> processing_instruction(XmlQualifiedName name) { return n => processing_instruction()(n) && ((XProcessingInstruction)n).Target == name.Name; } public override Func<XObject, bool> text() { return n => { switch (n.NodeType) { case XmlNodeType.CDATA: case XmlNodeType.SignificantWhitespace: case XmlNodeType.Text: case XmlNodeType.Whitespace: return true; default: return false; } }; } } }
30.252874
92
0.620061
[ "Apache-2.0" ]
maxtoroq/NTransform
src/NTransform.Xml.Linq/XObjectPatternParser.cs
2,634
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 Microsoft.Azure.Commands.AnalysisServices.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Azure.Commands.AnalysisServices.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Analysis Services server with name &apos;{0}&apos; already exists.. /// </summary> internal static string AnalysisServerExists { get { return ResourceManager.GetString("AnalysisServerExists", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Create Analysis Services Server. /// </summary> internal static string CreateNewAnalysisServicesServer { get { return ResourceManager.GetString("CreateNewAnalysisServicesServer", resourceCulture); } } /// <summary> /// Looks up a localized string similar to &quot;default &quot;. /// </summary> internal static string DefaultAclWord { get { return ResourceManager.GetString("DefaultAclWord", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not find server: &apos;{0}&apos; in any resource group in the currently selected subscription: {1}. Please ensure this server exists and that the current user has access to it.. /// </summary> internal static string FailedToDiscoverResourceGroup { get { return ResourceManager.GetString("FailedToDiscoverResourceGroup", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No default subscription has been designated. Use Select-AzureSubscription -Default &lt;subscriptionName&gt; to set the default subscription.. /// </summary> internal static string InvalidDefaultSubscription { get { return ResourceManager.GetString("InvalidDefaultSubscription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to AnalysisServices server operation failed with the following error code: {0} and message: {1}. /// </summary> internal static string LongRunningOperationFailed { get { return ResourceManager.GetString("LongRunningOperationFailed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No subscription found in the context. Please ensure that the credentials you provided are authorized to access an Azure subscription, then run Login-AzureRMAccount to login.. /// </summary> internal static string NoSubscriptionInContext { get { return ResourceManager.GetString("NoSubscriptionInContext", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Are you sure you want to remove Analysis Services server: &apos;{0}&apos;?. /// </summary> internal static string RemoveAnalysisServicesServer { get { return ResourceManager.GetString("RemoveAnalysisServicesServer", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Remove Analysis Services Server. /// </summary> internal static string RemovingAnalysisServicesServer { get { return ResourceManager.GetString("RemovingAnalysisServicesServer", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Are you sure you want to resume Analysis Services server: &apos;{0}&apos;?. /// </summary> internal static string ResumeAnalysisServicesServer { get { return ResourceManager.GetString("ResumeAnalysisServicesServer", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Resume Analysis Services Server. /// </summary> internal static string ResumingAnalysisServicesServer { get { return ResourceManager.GetString("ResumingAnalysisServicesServer", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The script file at path &apos;{0}&apos; does not exist or the current user does not have permission to it. Please ensure the path exists and is accessible.. /// </summary> internal static string ScriptFilePathDoesNotExist { get { return ResourceManager.GetString("ScriptFilePathDoesNotExist", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Cannot perform the requested operation because the specified server &apos;{0}&apos; does not exist.. /// </summary> internal static string ServerDoesNotExist { get { return ResourceManager.GetString("ServerDoesNotExist", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Are you sure you want to suspend Analysis Services server: &apos;{0}&apos;?. /// </summary> internal static string SuspendAnalysisServicesServer { get { return ResourceManager.GetString("SuspendAnalysisServicesServer", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Suspend Analysis Services Server. /// </summary> internal static string SuspendingAnalysisServicesServer { get { return ResourceManager.GetString("SuspendingAnalysisServicesServer", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The operation is being cancelled, please wait.... /// </summary> internal static string TaskCancelledMessage { get { return ResourceManager.GetString("TaskCancelledMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Are you sure you want to update Analysis Services server: &apos;{0}&apos;?. /// </summary> internal static string UpdateAnalysisServicesServer { get { return ResourceManager.GetString("UpdateAnalysisServicesServer", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Update Analysis Services Server. /// </summary> internal static string UpdatingAnalysisServicesServer { get { return ResourceManager.GetString("UpdatingAnalysisServicesServer", resourceCulture); } } } }
44.438053
237
0.587573
[ "MIT" ]
ajaygit158/azure-powershell
src/ResourceManager/AnalysisServices/Commands.AnalysisServices/Properties/Resources.Designer.cs
9,820
C#
namespace MyCoolWebServer.GameStoreApplication.Utilities { using System.Linq; using System.ComponentModel.DataAnnotations; using Microsoft.EntityFrameworkCore.Internal; public class PasswordAttribute : ValidationAttribute { public PasswordAttribute() { this.ErrorMessage = "Password should be at least 6 symbols long, should contain at least 1 upper case letter, 1 lowercase letter and 1 digit."; } public override bool IsValid(object value) { var password = value as string; if (password == null) { return false; } return password.Any(char.IsUpper) && password.Any(char.IsLower) && password.Any(char.IsDigit); } } }
28.068966
155
0.599509
[ "MIT" ]
pirocorp/CSharp-Web-Basics
Workshop/WebServer/MyCoolWebServer/GameStoreApplication/Utilities/PasswordAttribute.cs
816
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.DotNet.Framework.UpdateDependencies.Models; using Microsoft.DotNet.VersionTools; using Microsoft.DotNet.VersionTools.Automation; using Microsoft.DotNet.VersionTools.Dependencies; using Microsoft.DotNet.VersionTools.Dependencies.BuildOutput; using Newtonsoft.Json; namespace Microsoft.DotNet.Framework.UpdateDependencies { public class DependencyUpdater { private readonly Options options; private static readonly Lazy<IEnumerable<DockerfileInfo>> dockerfiles; public const string RuntimeImageVariant = "runtime"; public const string SdkImageVariant = "sdk"; public const string AspnetImageVariant = "aspnet"; public const string WcfImageVariant = "wcf"; public DependencyUpdater(Options options) { this.options = options; } static DependencyUpdater() { dockerfiles = new Lazy<IEnumerable<DockerfileInfo>>(() => new DirectoryInfo(Program.RepoRoot).GetDirectories("4.*") .Append(new DirectoryInfo(Path.Combine(Program.RepoRoot, "3.5"))) .SelectMany(dir => dir.GetFiles("Dockerfile", SearchOption.AllDirectories)) .Select(file => new DockerfileInfo(file.FullName)) .ToArray()); } public async Task ExecuteAsync() { IEnumerable<IDependencyInfo> dependencyInfos = new IDependencyInfo[] { CreateBuildInfo(RuntimeImageVariant, this.options.DateStampRuntime?? this.options.DateStampAll ?? String.Empty), CreateBuildInfo(SdkImageVariant, this.options.DateStampSdk ?? this.options.DateStampAll ?? String.Empty), CreateBuildInfo(AspnetImageVariant, this.options.DateStampAspnet ?? this.options.DateStampAll ?? String.Empty), CreateBuildInfo(WcfImageVariant, this.options.DateStampWcf ?? this.options.DateStampAll ?? String.Empty), }; DependencyUpdateResults updateResults = UpdateFiles(dependencyInfos); if (updateResults.ChangesDetected()) { if (this.options.UpdateOnly) { Trace.TraceInformation($"Changes made but no GitHub credentials specified, skipping PR creation"); } else { await CreatePullRequestAsync(dependencyInfos); } } } private async Task CreatePullRequestAsync(IEnumerable<IDependencyInfo> buildInfos) { GitHubAuth gitHubAuth = new GitHubAuth(this.options.GitHubPassword, this.options.GitHubUser, this.options.GitHubEmail); PullRequestCreator prCreator = new PullRequestCreator(gitHubAuth, this.options.GitHubUser); PullRequestOptions prOptions = new PullRequestOptions() { BranchNamingStrategy = new SingleBranchNamingStrategy($"UpdateDependencies-{this.options.GitHubUpstreamBranch}") }; string commitMessage = $"[{this.options.GitHubUpstreamBranch}] Update image dependencies"; await prCreator.CreateOrUpdateAsync( commitMessage, commitMessage, string.Empty, new GitHubBranch(this.options.GitHubUpstreamBranch, new GitHubProject(this.options.GitHubProject, this.options.GitHubUpstreamOwner)), new GitHubProject(this.options.GitHubProject, gitHubAuth.User), prOptions); } private static BuildDependencyInfo CreateBuildInfo(string name, string version) { return new BuildDependencyInfo( new BuildInfo { Name = name, LatestPackages = new Dictionary<string, string> { }, LatestReleaseVersion = version }, false, Enumerable.Empty<string>()); } private DependencyUpdateResults UpdateFiles(IEnumerable<IDependencyInfo> buildInfos) { List<IDependencyUpdater> updaters = new List<IDependencyUpdater>(); updaters.AddRange(CreateManifestUpdaters()); updaters.AddRange(CreateLcuUpdaters()); updaters.AddRange(CreateVsUpdaters()); updaters.AddRange(CreateNuGetUpdaters()); updaters.Add(new ReadmeUpdater()); return DependencyUpdateUtils.Update(updaters, buildInfos); } private IEnumerable<IDependencyUpdater> CreateLcuUpdaters() { LcuInfo[] lcuConfigs = JsonConvert.DeserializeObject<LcuInfo[]>( File.ReadAllText(this.options.LcuInfoPath)); const string UrlVersionGroupName = "Url"; const string CabFileVersionGroupName = "CabFile"; return dockerfiles.Value .Where(dockerfile => dockerfile.ImageVariant == RuntimeImageVariant) .Select(dockerfile => new { Dockerfile = dockerfile, LcuConfigInfo = GetLcuConfigInfo(dockerfile, lcuConfigs) }) .Where(val => val.LcuConfigInfo != null) .SelectMany(val => new IDependencyUpdater[] { new CustomFileRegexUpdater(val.LcuConfigInfo!.DownloadUrl, RuntimeImageVariant) { Path = val.Dockerfile.Path, VersionGroupName = UrlVersionGroupName, Regex = new Regex(@$"# Apply latest patch(.|\n)+(?<{UrlVersionGroupName}>http:\/\/[^\s""]+)") }, new CustomFileRegexUpdater(ParseCabFileName(val.LcuConfigInfo!.DownloadUrl), RuntimeImageVariant) { Path = val.Dockerfile.Path, VersionGroupName = CabFileVersionGroupName, Regex = new Regex(@$"# Apply latest patch(.|\n)+dism.+C:\\patch\\(?<{CabFileVersionGroupName}>\S+)", RegexOptions.IgnoreCase) } } ); } private IEnumerable<IDependencyUpdater> CreateVsUpdaters() { VsInfo vsConfig = JsonConvert.DeserializeObject<VsInfo>( File.ReadAllText(this.options.VsInfoPath)); const string TestAgentGroupName = "TestAgent"; const string BuildToolsGroupName = "BuildTools"; const string WebTargetsGroupName = "WebTargets"; return dockerfiles.Value .Where(dockerfile => dockerfile.ImageVariant == SdkImageVariant) .SelectMany(dockerfile => new IDependencyUpdater[] { new CustomFileRegexUpdater(vsConfig.TestAgentUrl, dockerfile.ImageVariant) { VersionGroupName = TestAgentGroupName, Path = dockerfile.Path, Regex = new Regex(@$"(?<{TestAgentGroupName}>https:\/\/\S+vs_TestAgent\.exe)"), }, new CustomFileRegexUpdater(vsConfig.BuildToolsUrl, dockerfile.ImageVariant) { VersionGroupName = BuildToolsGroupName, Path = dockerfile.Path, Regex = new Regex(@$"(?<{BuildToolsGroupName}>https:\/\/\S+vs_BuildTools\.exe)"), }, new CustomFileRegexUpdater(vsConfig.WebTargetsUrl, dockerfile.ImageVariant) { VersionGroupName = WebTargetsGroupName, Path = dockerfile.Path, Regex = new Regex(@$"# Install web targets(.|\n)+?(?<{WebTargetsGroupName}>https:\/\/\S+)"), } }); } private static string ParseCabFileName(string lcuDownloadUrl) { string msuFilename = lcuDownloadUrl.Substring(lcuDownloadUrl.LastIndexOf("/") + 1); return msuFilename.Substring(0, msuFilename.IndexOf("_")) + ".cab"; } private static LcuInfo? GetLcuConfigInfo(DockerfileInfo dockerfile, LcuInfo[] lcuConfigs) { return lcuConfigs .FirstOrDefault(config => config.OsVersion == dockerfile.OsVersion && config.RuntimeVersions.Any(runtime => runtime == dockerfile.FrameworkVersion)); } private IEnumerable<IDependencyUpdater> CreateNuGetUpdaters() { NuGetInfo[] nuGetVersions = JsonConvert.DeserializeObject<NuGetInfo[]>( File.ReadAllText(this.options.NuGetInfoPath)); const string NuGetVersionGroupName = "version"; return dockerfiles.Value .Where(dockerfile => dockerfile.ImageVariant == SdkImageVariant) .Select(dockerfile => { // Find the NuGetInfo that matches the OS version of this Dockerfile NuGetInfo nuGetInfo = nuGetVersions.FirstOrDefault(ver => ver.OsVersions.Contains(dockerfile.OsVersion)); if (nuGetInfo is null) { throw new InvalidOperationException($"No NuGet info is specified in '{this.options.NuGetInfoPath}' for OS version '{dockerfile.OsVersion}'."); } return new CustomFileRegexUpdater(nuGetInfo.NuGetClientVersion, dockerfile.ImageVariant) { Path = dockerfile.Path, VersionGroupName = NuGetVersionGroupName, Regex = new Regex(@$"ENV NUGET_VERSION (?<{NuGetVersionGroupName}>\d+\.\d+\.\d+)") }; }); } private IEnumerable<IDependencyUpdater> CreateManifestUpdaters() { const string RuntimePrefix = "Runtime"; const string SdkPrefix = "Sdk"; const string AspnetPrefix = "Aspnet"; const string WcfPrefix = "Wcf"; if (this.options.DateStampAll != null) { yield return CreateManifestUpdater(RuntimePrefix, RuntimeImageVariant); yield return CreateManifestUpdater(SdkPrefix, SdkImageVariant); yield return CreateManifestUpdater(AspnetPrefix, AspnetImageVariant); yield return CreateManifestUpdater(WcfPrefix, WcfImageVariant); } else { if (this.options.DateStampRuntime != null) { yield return CreateManifestUpdater(RuntimePrefix, RuntimeImageVariant); } if (this.options.DateStampSdk != null) { yield return CreateManifestUpdater(SdkPrefix, SdkImageVariant); } if (this.options.DateStampAspnet != null) { yield return CreateManifestUpdater(AspnetPrefix, AspnetImageVariant); } if (this.options.DateStampWcf != null) { yield return CreateManifestUpdater(WcfPrefix, WcfImageVariant); } } } private static IDependencyUpdater CreateManifestUpdater(string dateStampVariablePrefix, string buildInfoName) { const string TagDateStampGroupName = "tagDateStampValue"; return new FileRegexReleaseUpdater { Path = Path.Combine(Program.RepoRoot, "manifest.json"), BuildInfoName = buildInfoName, Regex = new Regex($"\"{dateStampVariablePrefix}ReleaseDateStamp\": \"(?<{TagDateStampGroupName}>\\d{{8}})\""), VersionGroupName = TagDateStampGroupName }; } private class DockerfileInfo { public DockerfileInfo(string path) { this.Path = path; string[] pathParts = path.Substring(Program.RepoRoot.Length + 1) .Replace(@"\", "/") .Split("/"); this.FrameworkVersion = pathParts[0]; this.ImageVariant = pathParts[1]; this.OsVersion = pathParts[2]; } public string Path { get; } public string FrameworkVersion { get; } public string OsVersion { get; } public string ImageVariant { get; } } } }
43.531353
166
0.568992
[ "MIT" ]
G10van1/dotnet-framework-docker
eng/update-dependencies/DependencyUpdater.cs
13,192
C#
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; using System.Diagnostics; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecP256K1FieldElement : AbstractFpFieldElement { public static readonly BigInteger Q = new BigInteger(1, Hex.DecodeStrict("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F")); protected internal readonly uint[] x; public SecP256K1FieldElement(BigInteger x) { if (x == null || x.SignValue < 0 || x.CompareTo(Q) >= 0) throw new ArgumentException("value invalid for SecP256K1FieldElement", "x"); this.x = SecP256K1Field.FromBigInteger(x); } public SecP256K1FieldElement() { this.x = Nat256.Create(); } protected internal SecP256K1FieldElement(uint[] x) { this.x = x; } public override bool IsZero { get { return Nat256.IsZero(x); } } public override bool IsOne { get { return Nat256.IsOne(x); } } public override bool TestBitZero() { return Nat256.GetBit(x, 0) == 1; } public override BigInteger ToBigInteger() { return Nat256.ToBigInteger(x); } public override string FieldName { get { return "SecP256K1Field"; } } public override int FieldSize { get { return Q.BitLength; } } public override ECFieldElement Add(ECFieldElement b) { uint[] z = Nat256.Create(); SecP256K1Field.Add(x, ((SecP256K1FieldElement)b).x, z); return new SecP256K1FieldElement(z); } public override ECFieldElement AddOne() { uint[] z = Nat256.Create(); SecP256K1Field.AddOne(x, z); return new SecP256K1FieldElement(z); } public override ECFieldElement Subtract(ECFieldElement b) { uint[] z = Nat256.Create(); SecP256K1Field.Subtract(x, ((SecP256K1FieldElement)b).x, z); return new SecP256K1FieldElement(z); } public override ECFieldElement Multiply(ECFieldElement b) { uint[] z = Nat256.Create(); SecP256K1Field.Multiply(x, ((SecP256K1FieldElement)b).x, z); return new SecP256K1FieldElement(z); } public override ECFieldElement Divide(ECFieldElement b) { //return Multiply(b.Invert()); uint[] z = Nat256.Create(); Mod.Invert(SecP256K1Field.P, ((SecP256K1FieldElement)b).x, z); SecP256K1Field.Multiply(z, x, z); return new SecP256K1FieldElement(z); } public override ECFieldElement Negate() { uint[] z = Nat256.Create(); SecP256K1Field.Negate(x, z); return new SecP256K1FieldElement(z); } public override ECFieldElement Square() { uint[] z = Nat256.Create(); SecP256K1Field.Square(x, z); return new SecP256K1FieldElement(z); } public override ECFieldElement Invert() { //return new SecP256K1FieldElement(ToBigInteger().ModInverse(Q)); uint[] z = Nat256.Create(); Mod.Invert(SecP256K1Field.P, x, z); return new SecP256K1FieldElement(z); } /** * return a sqrt root - the routine verifies that the calculation returns the right value - if * none exists it returns null. */ public override ECFieldElement Sqrt() { /* * Raise this element to the exponent 2^254 - 2^30 - 2^7 - 2^6 - 2^5 - 2^4 - 2^2 * * Breaking up the exponent's binary representation into "repunits", we get: * { 223 1s } { 1 0s } { 22 1s } { 4 0s } { 2 1s } { 2 0s} * * Therefore we need an addition chain containing 2, 22, 223 (the lengths of the repunits) * We use: 1, [2], 3, 6, 9, 11, [22], 44, 88, 176, 220, [223] */ uint[] x1 = this.x; if (Nat256.IsZero(x1) || Nat256.IsOne(x1)) return this; uint[] x2 = Nat256.Create(); SecP256K1Field.Square(x1, x2); SecP256K1Field.Multiply(x2, x1, x2); uint[] x3 = Nat256.Create(); SecP256K1Field.Square(x2, x3); SecP256K1Field.Multiply(x3, x1, x3); uint[] x6 = Nat256.Create(); SecP256K1Field.SquareN(x3, 3, x6); SecP256K1Field.Multiply(x6, x3, x6); uint[] x9 = x6; SecP256K1Field.SquareN(x6, 3, x9); SecP256K1Field.Multiply(x9, x3, x9); uint[] x11 = x9; SecP256K1Field.SquareN(x9, 2, x11); SecP256K1Field.Multiply(x11, x2, x11); uint[] x22 = Nat256.Create(); SecP256K1Field.SquareN(x11, 11, x22); SecP256K1Field.Multiply(x22, x11, x22); uint[] x44 = x11; SecP256K1Field.SquareN(x22, 22, x44); SecP256K1Field.Multiply(x44, x22, x44); uint[] x88 = Nat256.Create(); SecP256K1Field.SquareN(x44, 44, x88); SecP256K1Field.Multiply(x88, x44, x88); uint[] x176 = Nat256.Create(); SecP256K1Field.SquareN(x88, 88, x176); SecP256K1Field.Multiply(x176, x88, x176); uint[] x220 = x88; SecP256K1Field.SquareN(x176, 44, x220); SecP256K1Field.Multiply(x220, x44, x220); uint[] x223 = x44; SecP256K1Field.SquareN(x220, 3, x223); SecP256K1Field.Multiply(x223, x3, x223); uint[] t1 = x223; SecP256K1Field.SquareN(t1, 23, t1); SecP256K1Field.Multiply(t1, x22, t1); SecP256K1Field.SquareN(t1, 6, t1); SecP256K1Field.Multiply(t1, x2, t1); SecP256K1Field.SquareN(t1, 2, t1); uint[] t2 = x2; SecP256K1Field.Square(t1, t2); return Nat256.Eq(x1, t2) ? new SecP256K1FieldElement(t1) : null; } public override bool Equals(object obj) { return Equals(obj as SecP256K1FieldElement); } public override bool Equals(ECFieldElement other) { return Equals(other as SecP256K1FieldElement); } public virtual bool Equals(SecP256K1FieldElement other) { if (this == other) return true; if (null == other) return false; return Nat256.Eq(x, other.x); } public override int GetHashCode() { return Q.GetHashCode() ^ Arrays.GetHashCode(x, 0, 8); } } } #pragma warning restore #endif
32.58371
102
0.551035
[ "MIT" ]
Bregermann/TargetCrack
Target Crack/Assets/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256K1FieldElement.cs
7,201
C#
using System; namespace _2.Count_of_Negative_Elements_in_Array { class NegativeElementsInArray { static void Main() { var numbers = int.Parse(Console.ReadLine()); var array = new int[numbers]; var countOfNegativeNums = 0; for (int i = 0; i < array.Length; i++) { var currentNum = int.Parse(Console.ReadLine()); array[i] = currentNum; if (array[i] < 0) { countOfNegativeNums++; } } Console.WriteLine(countOfNegativeNums); } } }
24.111111
63
0.479263
[ "MIT" ]
bingoo0/SoftUni-TechModule
Simple Arrays - Exercises/2. Count of Negative Elements in Array/NegativeElementsInArray.cs
653
C#
using Microsoft.WindowsAzure.MobileServices; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace mvamobiletodo { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { // This MobileServiceClient has been configured to communicate with your Mobile Service's url // and application key. You're all set to start working with your Mobile Service! public static MobileServiceClient MobileService = new MobileServiceClient( "", "" ); /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; #if !WINDOWS_PHONE_APP RequestedTheme = ApplicationTheme.Light; #endif } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // Set the default language rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } } }
37.92562
101
0.625844
[ "MIT" ]
MicrosoftLearning/DocumentDB-MVA
mobile app demo/net/mvamobiletodo/mvamobiletodo.Shared/App.xaml.cs
4,591
C#
using System; namespace Bridge.Html5 { /// <summary> /// The HTMLElement interface represents any HTML element. Some elements directly implement this interface, others implement it via an interface that inherits it. /// </summary> [External] [Name("HTMLElement")] public class HTMLElement : Element { [Template("document.createElement(\"div\")")] public extern HTMLElement(); [Template("document.createElement({0})")] public extern HTMLElement(ElementType type); [Template("document.createElement({0})")] public extern HTMLElement(string tagName); #region Properties /// <summary> /// The access key assigned to the element. /// </summary> public string AccessKey; /// <summary> /// A string that represents the element's assigned access key. /// </summary> public readonly string AccessKeyLabel; /// <summary> /// Gets/sets whether or not the element is editable. /// </summary> public ContentEditable ContentEditable; /// <summary> /// Indicates whether or not the content of the element can be edited. /// </summary> public readonly bool IsContentEditable; /// <summary> /// Allows access to read and write custom data attributes (data-*) of the element. /// </summary> public readonly DOMStringMap Dataset; /// <summary> /// The HTMLElement.dir attribute gets or sets the text writing directionality of the content of the current element. /// </summary> public TextDirection Dir; /// <summary> /// Gets/sets the language of an element's attributes, text, and element contents. /// </summary> public string Lang; /// <summary> /// The height of an element, relative to the layout. /// </summary> public readonly int OffsetHeight; /// <summary> /// The distance from this element's left border to its offsetParent's left border. /// </summary> public readonly int OffsetLeft; /// <summary> /// The element from which all offset calculations are currently computed. /// </summary> public readonly HTMLElement OffsetParent; /// <summary> /// The distance from this element's top border to its offsetParent's top border. /// </summary> public readonly int OffsetTop; /// <summary> /// The width of an element, relative to the layout. /// </summary> public readonly int OffsetWidth; /// <summary> /// An object representing the declarations of an element's style attributes. /// </summary> public readonly CSSStyleDeclaration Style; /// <summary> /// Gets/sets the position of the element in the tabbing order. /// </summary> public int TabIndex; /// <summary> /// A string that appears in a popup box when mouse is over the element. /// </summary> public string Title; #endregion Properties #region Event handlers /// <summary> /// The oncopy property returns the onCopy event handler code on the current element. /// </summary> [Name("oncopy")] public Delegate OnCopy; /// <summary> /// Returns the event handling code for the cut event. /// </summary> [Name("oncut")] public Delegate OnCut; /// <summary> /// Returns the event handling code for the paste event. /// </summary> [Name("onpaste")] public Delegate OnPaste; #endregion Event handlers #region Methods /// <summary> /// Removes keyboard focus from the currently focused element. /// </summary> public virtual extern void Blur(); /// <summary> /// Sends a mouse click event to the element. /// </summary> public virtual extern void Click(); /// <summary> /// Makes the element the current keyboard focus. /// </summary> public virtual extern void Focus(); #endregion Methods /// <summary> /// EventHandler representing the code to be called when the abort event is raised. /// </summary> [Name("onabort")] public Action<Event> OnAbort; /// <summary> /// EventHandler representing the code to be called when the blur event is raised. /// </summary> [Name("onblur")] public Action<Event> OnBlur; /// <summary> /// OnErrorEventHandler representing the code to be called when the error event is raised. /// </summary> [Name("onerror")] public ErrorEventHandler OnError; /// <summary> /// EventHandler representing the code to be called when the focus event is raised. /// </summary> [Name("onfocus")] public Action<Event> OnFocus; /// <summary> /// EventHandler representing the code to be called when the cancel event is raised. /// </summary> [Name("oncancel")] public Action<Event> OnCancel; /// <summary> /// EventHandler representing the code to be called when the canplay event is raised /// </summary> [Name("oncanplay")] public Action<Event> OnCanPlay; /// <summary> /// EventHandler representing the code to be called when the canplaythrough event is raised. /// </summary> [Name("oncanplaythrough")] public Action<Event> OnCanPlayThrough; /// <summary> /// EventHandler representing the code to be called when the change event is raised. /// </summary> [Name("onchange")] public Action<Event> OnChange; /// <summary> /// EventHandler representing the code to be called when the click event is raised. /// </summary> [Name("onclick")] public Action<MouseEvent> OnClick; /// <summary> /// EventHandler representing the code to be called when the close event is raised. /// </summary> [Name("onclose")] public Action<Event> OnClose; /// <summary> /// EventHandler representing the code to be called when the contextmenu event is raised. /// </summary> [Name("oncontextmenu")] public Action<Event> OnContextMenu; /// <summary> /// EventHandler representing the code to be called when the cuechange event is raised. /// </summary> [Name("oncuechange")] public Action<Event> OnCueChange; /// <summary> /// EventHandler representing the code to be called when the dblclick event is raised. /// </summary> [Name("ondblclick")] public Action<MouseEvent> OnDblClick; /// <summary> /// EventHandler representing the code to be called when the drag event is raised. /// </summary> [Name("ondrag")] public Action<Event> OnDrag; /// <summary> /// Is an EventHandler representing the code to be called when the dragend event is raised /// </summary> [Name("ondragend")] public Action<Event> OnDragEnd; /// <summary> /// Is an EventHandler representing the code to be called when the dragenter event is raised /// </summary> [Name("ondragenter")] public Action<Event> OnDragEnter; /// <summary> /// Is an EventHandler representing the code to be called when the dragexit event is raised /// </summary> [Name("ondragexit")] public Action<Event> OnDragExit; /// <summary> /// Is an EventHandler representing the code to be called when the dragleave event is raised /// </summary> [Name("ondragleave")] public Action<Event> OnDragLeave; /// <summary> /// Is an EventHandler representing the code to be called when the dragover event is raised /// </summary> [Name("ondragover")] public Action<Event> OnDragOver; /// <summary> /// Is an EventHandler representing the code to be called when the dragstart event is raised /// </summary> [Name("ondragstart")] public Action<Event> OnDragStart; /// <summary> /// Is an EventHandler representing the code to be called when the drop event is raised /// </summary> [Name("ondrop")] public Action<Event> OnDrop; /// <summary> /// Is an EventHandler representing the code to be called when the durationchange event is raised /// </summary> [Name("ondurationchange")] public Action<Event> OnDurationChange; /// <summary> /// Is an EventHandler representing the code to be called when the emptied event is raised /// </summary> [Name("onemptied")] public Action<Event> OnEmptied; /// <summary> /// Is an EventHandler representing the code to be called when the ended event is raised /// </summary> [Name("onended")] public Action<Event> OnEnded; /// <summary> /// Is an EventHandler representing the code to be called when the input event is raised /// </summary> [Name("oninput")] public Action<Event> OnInput; /// <summary> /// Is an EventHandler representing the code to be called when the invalid event is raised /// </summary> [Name("oninvalid")] public Action<Event> OnInvalid; /// <summary> /// Is an EventHandler representing the code to be called when the keydown event is raised /// </summary> [Name("onkeydown")] public Action<KeyboardEvent> OnKeyDown; /// <summary> /// Is an EventHandler representing the code to be called when the keypress event is raised /// </summary> [Name("onkeypress")] public Action<KeyboardEvent> OnKeyPress; /// <summary> /// Is an EventHandler representing the code to be called when the keyup event is raised /// </summary> [Name("onkeyup")] public Action<KeyboardEvent> OnKeyUp; /// <summary> /// Is an EventHandler representing the code to be called when the load event is raised /// </summary> [Name("onload")] public Action<Event> OnLoad; /// <summary> /// Is an EventHandler representing the code to be called when the loadeddata event is raised /// </summary> [Name("onloadeddata")] public Action<Event> OnLoadedData; /// <summary> /// Is an EventHandler representing the code to be called when the loadedmetadata event is raised /// </summary> [Name("onloadedmetadata")] public Action<Event> OnLoadedMetaData; /// <summary> /// Is an EventHandler representing the code to be called when the loadstart event is raised /// </summary> [Name("onloadstart")] public Action<Event> OnLoadStart; /// <summary> /// Is an EventHandler representing the code to be called when the mousedown event is raised /// </summary> [Name("onmousedown")] public Action<MouseEvent> OnMouseDown; /// <summary> /// Is an EventHandler representing the code to be called when the mouseenter event is raised /// </summary> [Name("onmouseenter")] public Action<MouseEvent> OnMouseEnter; /// <summary> /// Is an EventHandler representing the code to be called when the mouseleave event is raised /// </summary> [Name("onmouseleave")] public Action<MouseEvent> OnMouseLeave; /// <summary> /// Is an EventHandler representing the code to be called when the mousemove event is raised /// </summary> [Name("onmousemove")] public Action<MouseEvent> OnMouseMove; /// <summary> /// Is an EventHandler representing the code to be called when the mouseout event is raised /// </summary> [Name("onmouseout")] public Action<MouseEvent> OnMouseOut; /// <summary> /// Is an EventHandler representing the code to be called when the mouseover event is raised /// </summary> [Name("onmouseover")] public Action<MouseEvent> OnMouseOver; /// <summary> /// Is an EventHandler representing the code to be called when the mouseup event is raised /// </summary> [Name("onmouseup")] public Action<MouseEvent> OnMouseUp; /// <summary> /// Is an EventHandler representing the code to be called when the mousewheel event is raised /// </summary> [Name("onmousewheel")] public Action<MouseEvent> OnMouseWheel; /// <summary> /// Is an EventHandler representing the code to be called when the pause event is raised /// </summary> [Name("onpause")] public Action<Event> OnPause; /// <summary> /// Is an EventHandler representing the code to be called when the play event is raised /// </summary> [Name("onplay")] public Action<Event> OnPlay; /// <summary> /// Is an EventHandler representing the code to be called when the playing event is raised /// </summary> [Name("onplaying")] public Action<Event> OnPlaying; /// <summary> /// Is an EventHandler representing the code to be called when the progress event is raised /// </summary> [Name("onprogress")] public Action<ProgressEvent> OnProgress; /// <summary> /// Is an EventHandler representing the code to be called when the ratechange event is raised /// </summary> [Name("onratechange")] public Action<Event> OnRateChange; /// <summary> /// Is an EventHandler representing the code to be called when the reset event is raised /// </summary> [Name("onreset")] public Action<Event> OnReset; /// <summary> /// Is an EventHandler representing the code to be called when the scroll event is raised /// </summary> [Name("onscroll")] public Action<Event> OnScroll; /// <summary> /// Is an EventHandler representing the code to be called when the seeked event is raised /// </summary> [Name("onseeked")] public Action<Event> OnSeeked; /// <summary> /// Is an EventHandler representing the code to be called when the seeking event is raised /// </summary> [Name("onseeking")] public Action<Event> OnSeeking; /// <summary> /// Is an EventHandler representing the code to be called when the select event is raised /// </summary> [Name("onselect")] public Action<Event> OnSelect; /// <summary> /// Is an EventHandler representing the code to be called when the show event is raised /// </summary> [Name("onshow")] public Action<Event> OnShow; /// <summary> /// Is an EventHandler representing the code to be called when the sort event is raised /// </summary> [Name("onsort")] public Action<Event> OnSort; /// <summary> /// Is an EventHandler representing the code to be called when the stalled event is raised /// </summary> [Name("onstalled")] public Action<Event> OnStalled; /// <summary> /// Is an EventHandler representing the code to be called when the submit event is raised /// </summary> [Name("onsubmit")] public Action<Event> OnSubmit; /// <summary> /// Is an EventHandler representing the code to be called when the suspend event is raised /// </summary> [Name("onsuspend")] public Action<Event> OnSuspend; /// <summary> /// Is an EventHandler representing the code to be called when the timeupdate event is raised /// </summary> [Name("ontimeupdate")] public Action<Event> OnTimeUpdate; /// <summary> /// Is an EventHandler representing the code to be called when the volumechange event is raised /// </summary> [Name("onvolumechange")] public Action<Event> OnVolumeChange; /// <summary> /// Is an EventHandler representing the code to be called when the waiting event is raised /// </summary> [Name("onwaiting")] public Action<Event> OnWaiting; /// <summary> /// Returns the event handling code for the touchstart event. /// </summary> [Name("ontouchstart")] public Action<TouchEvent> OnTouchStart; /// <summary> /// Returns the event handling code for the touchend event. /// </summary> [Name("ontouchend")] public Action<TouchEvent> OnTouchEnd; /// <summary> /// Returns the event handling code for the touchmove event. /// </summary> [Name("ontouchmove")] public Action<TouchEvent> OnTouchMove; /// <summary> /// Returns the event handling code for the touchenter event. /// </summary> [Name("ontouchenter")] public Action<TouchEvent> OnTouchEnter; /// <summary> /// Returns the event handling code for the touchleave event. /// </summary> [Name("ontouchleave")] public Action<TouchEvent> OnTouchLeave; /// <summary> /// Returns the event handling code for the touchcancel event. /// </summary> [Name("ontouchcancel")] public Action<TouchEvent> OnTouchCancel; } /// <summary> /// A generic version of the Element class. The type parameter is a type of Events' CurrentTarget. /// </summary> /// <typeparam name="TCurrentTarget">The CurrentTarget type of all Element's events</typeparam> [External] [IgnoreGeneric] [Namespace(false)] public class HTMLElement<TCurrentTarget> : HTMLElement where TCurrentTarget : HTMLElement { /// <summary> /// EventHandler representing the code to be called when the abort event is raised. /// </summary> [Name("onabort")] public new Action<Event<TCurrentTarget>> OnAbort; /// <summary> /// EventHandler representing the code to be called when the blur event is raised. /// </summary> [Name("onblur")] public new Action<Event<TCurrentTarget>> OnBlur; /// <summary> /// EventHandler representing the code to be called when the focus event is raised. /// </summary> [Name("onfocus")] public new Action<Event<TCurrentTarget>> OnFocus; /// <summary> /// EventHandler representing the code to be called when the cancel event is raised. /// </summary> [Name("oncancel")] public new Action<Event<TCurrentTarget>> OnCancel; /// <summary> /// EventHandler representing the code to be called when the canplay event is raised /// </summary> [Name("oncanplay")] public new Action<Event<TCurrentTarget>> OnCanPlay; /// <summary> /// EventHandler representing the code to be called when the canplaythrough event is raised. /// </summary> [Name("oncanplaythrough")] public new Action<Event<TCurrentTarget>> OnCanPlayThrough; /// <summary> /// EventHandler representing the code to be called when the change event is raised. /// </summary> [Name("onchange")] public new Action<Event<TCurrentTarget>> OnChange; /// <summary> /// EventHandler representing the code to be called when the click event is raised. /// </summary> [Name("onclick")] public new Action<MouseEvent<TCurrentTarget>> OnClick; /// <summary> /// EventHandler representing the code to be called when the close event is raised. /// </summary> [Name("onclose")] public new Action<Event<TCurrentTarget>> OnClose; /// <summary> /// EventHandler representing the code to be called when the contextmenu event is raised. /// </summary> [Name("oncontextmenu")] public new Action<Event<TCurrentTarget>> OnContextMenu; /// <summary> /// EventHandler representing the code to be called when the cuechange event is raised. /// </summary> [Name("oncuechange")] public new Action<Event<TCurrentTarget>> OnCueChange; /// <summary> /// EventHandler representing the code to be called when the dblclick event is raised. /// </summary> [Name("ondblclick")] public new Action<MouseEvent<TCurrentTarget>> OnDblClick; /// <summary> /// EventHandler representing the code to be called when the drag event is raised. /// </summary> [Name("ondrag")] public new Action<Event<TCurrentTarget>> OnDrag; /// <summary> /// Is an EventHandler representing the code to be called when the dragend event is raised /// </summary> [Name("ondragend")] public new Action<Event<TCurrentTarget>> OnDragEnd; /// <summary> /// Is an EventHandler representing the code to be called when the dragenter event is raised /// </summary> [Name("ondragenter")] public new Action<Event<TCurrentTarget>> OnDragEnter; /// <summary> /// Is an EventHandler representing the code to be called when the dragexit event is raised /// </summary> [Name("ondragexit")] public new Action<Event<TCurrentTarget>> OnDragExit; /// <summary> /// Is an EventHandler representing the code to be called when the dragleave event is raised /// </summary> [Name("ondragleave")] public new Action<Event<TCurrentTarget>> OnDragLeave; /// <summary> /// Is an EventHandler representing the code to be called when the dragover event is raised /// </summary> [Name("ondragover")] public new Action<Event<TCurrentTarget>> OnDragOver; /// <summary> /// Is an EventHandler representing the code to be called when the dragstart event is raised /// </summary> [Name("ondragstart")] public new Action<Event<TCurrentTarget>> OnDragStart; /// <summary> /// Is an EventHandler representing the code to be called when the drop event is raised /// </summary> [Name("ondrop")] public new Action<Event<TCurrentTarget>> OnDrop; /// <summary> /// Is an EventHandler representing the code to be called when the durationchange event is raised /// </summary> [Name("ondurationchange")] public new Action<Event<TCurrentTarget>> OnDurationChange; /// <summary> /// Is an EventHandler representing the code to be called when the emptied event is raised /// </summary> [Name("onemptied")] public new Action<Event<TCurrentTarget>> OnEmptied; /// <summary> /// Is an EventHandler representing the code to be called when the ended event is raised /// </summary> [Name("onended")] public new Action<Event<TCurrentTarget>> OnEnded; /// <summary> /// Is an EventHandler representing the code to be called when the input event is raised /// </summary> [Name("oninput")] public new Action<Event<TCurrentTarget>> OnInput; /// <summary> /// Is an EventHandler representing the code to be called when the invalid event is raised /// </summary> [Name("oninvalid")] public new Action<Event<TCurrentTarget>> OnInvalid; /// <summary> /// Is an EventHandler representing the code to be called when the keydown event is raised /// </summary> [Name("onkeydown")] public new Action<KeyboardEvent<TCurrentTarget>> OnKeyDown; /// <summary> /// Is an EventHandler representing the code to be called when the keypress event is raised /// </summary> [Name("onkeypress")] public new Action<KeyboardEvent<TCurrentTarget>> OnKeyPress; /// <summary> /// Is an EventHandler representing the code to be called when the keyup event is raised /// </summary> [Name("onkeyup")] public new Action<KeyboardEvent<TCurrentTarget>> OnKeyUp; /// <summary> /// Is an EventHandler representing the code to be called when the load event is raised /// </summary> [Name("onload")] public new Action<Event<TCurrentTarget>> OnLoad; /// <summary> /// Is an EventHandler representing the code to be called when the loadeddata event is raised /// </summary> [Name("onloadeddata")] public new Action<Event<TCurrentTarget>> OnLoadedData; /// <summary> /// Is an EventHandler representing the code to be called when the loadedmetadata event is raised /// </summary> [Name("onloadedmetadata")] public new Action<Event<TCurrentTarget>> OnLoadedMetaData; /// <summary> /// Is an EventHandler representing the code to be called when the loadstart event is raised /// </summary> [Name("onloadstart")] public new Action<Event<TCurrentTarget>> OnLoadStart; /// <summary> /// Is an EventHandler representing the code to be called when the mousedown event is raised /// </summary> [Name("onmousedown")] public new Action<MouseEvent<TCurrentTarget>> OnMouseDown; /// <summary> /// Is an EventHandler representing the code to be called when the mouseenter event is raised /// </summary> [Name("onmouseenter")] public new Action<MouseEvent<TCurrentTarget>> OnMouseEnter; /// <summary> /// Is an EventHandler representing the code to be called when the mouseleave event is raised /// </summary> [Name("onmouseleave")] public new Action<MouseEvent<TCurrentTarget>> OnMouseLeave; /// <summary> /// Is an EventHandler representing the code to be called when the mousemove event is raised /// </summary> [Name("onmousemove")] public new Action<MouseEvent<TCurrentTarget>> OnMouseMove; /// <summary> /// Is an EventHandler representing the code to be called when the mouseout event is raised /// </summary> [Name("onmouseout")] public new Action<MouseEvent<TCurrentTarget>> OnMouseOut; /// <summary> /// Is an EventHandler representing the code to be called when the mouseover event is raised /// </summary> [Name("onmouseover")] public new Action<MouseEvent<TCurrentTarget>> OnMouseOver; /// <summary> /// Is an EventHandler representing the code to be called when the mouseup event is raised /// </summary> [Name("onmouseup")] public new Action<MouseEvent<TCurrentTarget>> OnMouseUp; /// <summary> /// Is an EventHandler representing the code to be called when the mousewheel event is raised /// </summary> [Name("onmousewheel")] public new Action<MouseEvent<TCurrentTarget>> OnMouseWheel; /// <summary> /// Is an EventHandler representing the code to be called when the pause event is raised /// </summary> [Name("onpause")] public new Action<Event<TCurrentTarget>> OnPause; /// <summary> /// Is an EventHandler representing the code to be called when the play event is raised /// </summary> [Name("onplay")] public new Action<Event<TCurrentTarget>> OnPlay; /// <summary> /// Is an EventHandler representing the code to be called when the playing event is raised /// </summary> [Name("onplaying")] public new Action<Event<TCurrentTarget>> OnPlaying; /// <summary> /// Is an EventHandler representing the code to be called when the progress event is raised /// </summary> [Name("onprogress")] public new Action<ProgressEvent<TCurrentTarget>> OnProgress; /// <summary> /// Is an EventHandler representing the code to be called when the ratechange event is raised /// </summary> [Name("onratechange")] public new Action<Event<TCurrentTarget>> OnRateChange; /// <summary> /// Is an EventHandler representing the code to be called when the reset event is raised /// </summary> [Name("onreset")] public new Action<Event<TCurrentTarget>> OnReset; /// <summary> /// Is an EventHandler representing the code to be called when the scroll event is raised /// </summary> [Name("onscroll")] public new Action<Event<TCurrentTarget>> OnScroll; /// <summary> /// Is an EventHandler representing the code to be called when the seeked event is raised /// </summary> [Name("onseeked")] public new Action<Event<TCurrentTarget>> OnSeeked; /// <summary> /// Is an EventHandler representing the code to be called when the seeking event is raised /// </summary> [Name("onseeking")] public new Action<Event<TCurrentTarget>> OnSeeking; /// <summary> /// Is an EventHandler representing the code to be called when the select event is raised /// </summary> [Name("onselect")] public new Action<Event<TCurrentTarget>> OnSelect; /// <summary> /// Is an EventHandler representing the code to be called when the show event is raised /// </summary> [Name("onshow")] public new Action<Event<TCurrentTarget>> OnShow; /// <summary> /// Is an EventHandler representing the code to be called when the sort event is raised /// </summary> [Name("onsort")] public new Action<Event<TCurrentTarget>> OnSort; /// <summary> /// Is an EventHandler representing the code to be called when the stalled event is raised /// </summary> [Name("onstalled")] public new Action<Event<TCurrentTarget>> OnStalled; /// <summary> /// Is an EventHandler representing the code to be called when the submit event is raised /// </summary> [Name("onsubmit")] public new Action<Event<TCurrentTarget>> OnSubmit; /// <summary> /// Is an EventHandler representing the code to be called when the suspend event is raised /// </summary> [Name("onsuspend")] public new Action<Event<TCurrentTarget>> OnSuspend; /// <summary> /// Is an EventHandler representing the code to be called when the timeupdate event is raised /// </summary> [Name("ontimeupdate")] public new Action<Event<TCurrentTarget>> OnTimeUpdate; /// <summary> /// Is an EventHandler representing the code to be called when the volumechange event is raised /// </summary> [Name("onvolumechange")] public new Action<Event<TCurrentTarget>> OnVolumeChange; /// <summary> /// Is an EventHandler representing the code to be called when the waiting event is raised /// </summary> [Name("onwaiting")] public new Action<Event<TCurrentTarget>> OnWaiting; /// <summary> /// Returns the event handling code for the touchstart event. /// </summary> [Name("ontouchstart")] public new Action<TouchEvent<TCurrentTarget>> OnTouchStart; /// <summary> /// Returns the event handling code for the touchend event. /// </summary> [Name("ontouchend")] public new Action<TouchEvent<TCurrentTarget>> OnTouchEnd; /// <summary> /// Returns the event handling code for the touchmove event. /// </summary> [Name("ontouchmove")] public new Action<TouchEvent<TCurrentTarget>> OnTouchMove; /// <summary> /// Returns the event handling code for the touchenter event. /// </summary> [Name("ontouchenter")] public new Action<TouchEvent<TCurrentTarget>> OnTouchEnter; /// <summary> /// Returns the event handling code for the touchleave event. /// </summary> [Name("ontouchleave")] public new Action<TouchEvent<TCurrentTarget>> OnTouchLeave; /// <summary> /// Returns the event handling code for the touchcancel event. /// </summary> [Name("ontouchcancel")] public new Action<TouchEvent<TCurrentTarget>> OnTouchCancel; } }
36.117838
166
0.599838
[ "Apache-2.0" ]
Antonio24/Bridge
Html5/Elements/HTMLElement.cs
33,409
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; //A delegate for creating event public delegate void UpdateStackEvent(); public class ObservableStack<T> : Stack<T> { /// <summary> /// Event that is raised when we push something /// </summary> public event UpdateStackEvent OnPush; /// <summary> /// Event that is raised when we pop something /// </summary> public event UpdateStackEvent OnPop; /// <summary> /// Event that is raised when we clear the stack /// </summary> public event UpdateStackEvent OnClear; public ObservableStack(ObservableStack<T> items) : base(items) { } public ObservableStack() { } public new void Push(T item) { base.Push(item); if (OnPush != null) //Makes sure something is listening to the event before we call it { OnPush(); //Calls the event } } public new T Pop() { T item = base.Pop(); if (OnPop != null) //Makes sure something is listening to the event before we call it { OnPop();//Calls the event } return item; } public new void Clear() { base.Clear(); if (OnClear != null)//Makes sure something is listening to the event before we call it { OnClear();//Calls the event } } }
20.794118
94
0.586987
[ "MIT" ]
gusdn6763/inScope_RPG_Tutorial
Assets/Scripts/ObservableStack.cs
1,416
C#
// // Bindings for DoubleActions's in various classes in AppKit // // Copyright 2010, 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. // #if !__MACCATALYST__ using System; using Foundation; namespace AppKit { public partial class NSBrowser { public event EventHandler DoubleClick { add { Target = ActionDispatcher.SetupDoubleAction (Target, value); DoubleAction = ActionDispatcher.DoubleAction; } remove { ActionDispatcher.RemoveDoubleAction (Target, value); } } } public partial class NSMatrix { public event EventHandler DoubleClick { add { Target = ActionDispatcher.SetupDoubleAction (Target, value); DoubleAction = ActionDispatcher.DoubleAction; } remove { ActionDispatcher.RemoveDoubleAction (Target, value); } } } public partial class NSPathCell { public event EventHandler DoubleClick { add { Target = ActionDispatcher.SetupDoubleAction (Target, value); DoubleAction = ActionDispatcher.DoubleAction; } remove { ActionDispatcher.RemoveDoubleAction (Target, value); } } } public partial class NSPathControl { public event EventHandler DoubleClick { add { Target = ActionDispatcher.SetupDoubleAction (Target, value); DoubleAction = ActionDispatcher.DoubleAction; } remove { ActionDispatcher.RemoveDoubleAction (Target, value); } } } public partial class NSStatusItem { public event EventHandler DoubleClick { add { Target = ActionDispatcher.SetupDoubleAction (Target, value); DoubleAction = ActionDispatcher.DoubleAction; } remove { ActionDispatcher.RemoveDoubleAction (Target, value); } } } public partial class NSTableView { public event EventHandler DoubleClick { add { Target = ActionDispatcher.SetupDoubleAction (Target, value); DoubleAction = ActionDispatcher.DoubleAction; } remove { ActionDispatcher.RemoveDoubleAction (Target, value); } } } } #endif // !__MACCATALYST__
28.471698
73
0.733598
[ "BSD-3-Clause" ]
NormanChiflen/xamarin-all-IOS
src/AppKit/DoubleWrapper.cs
3,018
C#
using QTObjectModelLib; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace HpToolsLauncher { public class MBTRunner : RunnerBase, IDisposable { private readonly object _lockObject = new object(); private string parentFolder;//folder in which we will create new tests private string repoFolder; private IEnumerable<MBTTest> tests; public MBTRunner(string parentFolder, string repoFolder, IEnumerable<MBTTest> tests) { this.parentFolder = parentFolder; this.repoFolder = repoFolder; this.tests = tests; } public override TestSuiteRunResults Run() { var type = Type.GetTypeFromProgID("Quicktest.Application"); lock (_lockObject) { Application _qtpApplication = Activator.CreateInstance(type) as Application; try { if (Directory.Exists(parentFolder)) { Directory.Delete(parentFolder, true); } ConsoleWriter.WriteLine("Using parent folder : " + parentFolder); } catch (Exception e) { ConsoleWriter.WriteErrLine("Failed to delete parent folder : " + e.Message); } Directory.CreateDirectory(parentFolder); DirectoryInfo parentDir = new DirectoryInfo(parentFolder); try { if (_qtpApplication.Launched) { _qtpApplication.Quit(); } } catch (Exception e) { ConsoleWriter.WriteErrLine("Failed to close qtpApp : " + e.Message); } //START Test creation //_qtpApplication.Launch(); //_qtpApplication.Visible = false; foreach (var test in tests) { DateTime startTotal = DateTime.Now; ConsoleWriter.WriteLine("Creation of " + test.Name + " *****************************"); LoadNeededAddins(_qtpApplication, test.UnderlyingTests); try { DateTime startSub1 = DateTime.Now; _qtpApplication.New(); try { //The test is set to record and run on any open Web application. _qtpApplication.Test.Settings.Launchers["Web"].Active = false; } catch (Exception e) { ConsoleWriter.WriteLine("Failed to set .Launchers[Web].Active = false : " + e.Message); } ConsoleWriter.WriteLine(string.Format("_qtpApplication.New took {0:0.0} secs", DateTime.Now.Subtract(startSub1).TotalSeconds)); QTObjectModelLib.Action qtAction1 = _qtpApplication.Test.Actions[1]; qtAction1.Description = "unitIds=" + string.Join(",", test.UnitIds); //https://myskillpoint.com/how-to-use-loadandrunaction-in-uft/#LoadAndRunAction_Having_Input-Output_Parameters //LoadAndRunAction "E:\UFT_WorkSpace\TestScripts\SampleTest","Action1",0,"inputParam1","inputParam2",outParameterVal //string actionContent = "LoadAndRunAction \"c:\\Temp\\GUITest2\\\",\"Action1\""; string actionContent = File.Exists(test.Script) ? File.ReadAllText(test.Script) : test.Script; qtAction1.ValidateScript(actionContent); qtAction1.SetScript(actionContent); DirectoryInfo fullDir = parentDir; if (!string.IsNullOrEmpty(test.PackageName)) { fullDir = fullDir.CreateSubdirectory(test.PackageName); } //Expects to receive params in CSV format, encoded base64 if (!string.IsNullOrEmpty(test.DatableParams)) { string tempCsvFileName = Path.Combine(parentFolder, "temp.csv"); if (File.Exists(tempCsvFileName)) { File.Delete(tempCsvFileName); } byte[] data = Convert.FromBase64String(test.DatableParams); string decodedParams = Encoding.UTF8.GetString(data); File.WriteAllText(tempCsvFileName, decodedParams); _qtpApplication.Test.DataTable.Import(tempCsvFileName); File.Delete(tempCsvFileName); } string fullPath = fullDir.CreateSubdirectory(test.Name).FullName; _qtpApplication.Test.SaveAs(fullPath); double sec = DateTime.Now.Subtract(startTotal).TotalSeconds; ConsoleWriter.WriteLine(string.Format("MBT test was created in {0} in {1:0.0} secs", fullPath, sec)); } catch (Exception e) { ConsoleWriter.WriteErrLine("Fail in MBTRunner : " + e.Message); } } if (_qtpApplication.Launched) { _qtpApplication.Quit(); } } return null; } private string GetResourceFileNameAndAddToUftFoldersIfRequired(Application qtpApplication, string filePath) { //file path might be full or just file name; string location = qtpApplication.Folders.Locate(filePath); if (!string.IsNullOrEmpty(location)) { ConsoleWriter.WriteLine(string.Format("Adding resources : {0} - done", filePath)); } else { ConsoleWriter.WriteLine(string.Format("Adding resources : {0} - failed to find file in repository. Please check correctness of resource location.", filePath)); } /*else { string[] allFiles = Directory.GetFiles(repoFolder, fileName, SearchOption.AllDirectories); if (allFiles.Length == 0) { ConsoleWriter.WriteLine(string.Format("Adding resources : {0} - failed to find file in repository. Please check correctness of resource name.", fileName)); } else if (allFiles.Length > 1) { //we found several possible locations //if resource has full path, we can try to find it in found paths //for example resource : c://aa/bb/repo/resourceName //one of found paths is : c:/jenkins/repo/resourceName , after removing repo is will be /repo/resourceName //so /repo/resourceName is last part of c://aa/bb/repo/resourceName bool found = false; if (Path.IsPathRooted(filePath)) { foreach (string path in allFiles) { string pathInRepo = path.Replace(repoFolder,""); if (filePath.EndsWith(pathInRepo)) { string directoryPath = new FileInfo(path).Directory.FullName; ConsoleWriter.WriteLine(string.Format("Adding resources : {0} - folder {1} is added to settings", fileName, directoryPath.Replace(repoFolder, ""))); qtpApplication.Folders.Add(directoryPath); found = true; break; } } } if (!found) { StringBuilder sb = new StringBuilder(); foreach (string path in allFiles) { string directoryPath = new FileInfo(path).Directory.FullName; sb.Append(directoryPath).Append("; "); } ConsoleWriter.WriteLine(string.Format("Adding resources : {0} - found more than 1 file in repo. Please define 'Folder location' manually in (Tools->Options->GUI Testing->Folders). Possible values : {1}", fileName, sb.ToString())); } } else//found ==1 { string directoryPath = new FileInfo(allFiles[0]).Directory.FullName; ConsoleWriter.WriteLine(string.Format("Adding resources : {0} - folder {1} is added to settings", fileName, directoryPath.Replace(repoFolder,""))); qtpApplication.Folders.Add(directoryPath); } }*/ return filePath; } private void LoadNeededAddins(Application _qtpApplication, IEnumerable<String> fileNames) { try { HashSet<string> addinsSet = new HashSet<string>(); foreach (string fileName in fileNames) { try { DateTime start1 = DateTime.Now; var testAddinsObj = _qtpApplication.GetAssociatedAddinsForTest(fileName); ConsoleWriter.WriteLine(string.Format("GetAssociatedAddinsForTest took {0:0.0} secs", DateTime.Now.Subtract(start1).TotalSeconds)); object[] tempTestAddins = (object[])testAddinsObj; foreach (string addin in tempTestAddins) { addinsSet.Add(addin); } } catch (Exception testErr) { ConsoleWriter.WriteErrLine("Fail to LoadNeededAddins for : " + fileName + ", " + testErr.Message); } } //if (_qtpApplication.Launched) //{ //_qtpApplication.Quit(); //ConsoleWriter.WriteLine("LoadNeededAddins : _qtpApplication.Quit"); //} object erroDescription = null; string[] addinsArr = new string[addinsSet.Count]; addinsSet.CopyTo(addinsArr); ConsoleWriter.WriteLine("Loading Addins : " + string.Join(",", addinsArr)); DateTime start2 = DateTime.Now; _qtpApplication.SetActiveAddins(addinsArr, out erroDescription); ConsoleWriter.WriteLine(string.Format("SetActiveAddins took {0:0.0} secs", DateTime.Now.Subtract(start2).TotalSeconds)); if (!string.IsNullOrEmpty((string)erroDescription)) { ConsoleWriter.WriteErrLine("Fail to SetActiveAddins : " + erroDescription); } } catch (Exception globalErr) { ConsoleWriter.WriteErrLine("Fail to LoadNeededAddins : " + globalErr.Message); // Try anyway to run the test } } } public class RecoveryScenario { public string FileName { get; set; } public string Name { get; set; } public int Position { get; set; } public static RecoveryScenario ParseFromString(string content) { RecoveryScenario rs = new RecoveryScenario(); string[] parts = content.Split(',');//expected 3 parts separated by , : location,name,position(default is -1) if (parts.Length < 2) { ConsoleWriter.WriteErrLine("Fail to parse recovery scenario (need at least 2 parts, separated with ,): " + content); return null; } rs.FileName = parts[0]; rs.Name = parts[1]; if (parts.Length >= 3) { try { rs.Position = int.Parse(parts[2]); } catch (Exception e) { ConsoleWriter.WriteErrLine("Fail to parse position of recovery scenario : " + content + " : " + e.Message); rs.Position = -1; } } else { rs.Position = -1; } return rs; } } public class MBTTest { public string Name { get; set; } public string Script { get; set; } public string UnitIds { get; set; } public List<string> UnderlyingTests { get; set; } public string PackageName { get; set; } public string DatableParams { get; set; } } }
43.732673
254
0.496491
[ "MIT" ]
MicroFocus/ADM-FT-ToolsLauncher
HpToolsLauncher/Runners/MBTRunner.cs
13,253
C#
using System; namespace FluentTextTable.Sample._11.Margins { public class User { public int Id { get; set; } public string Name { get; set; } public DateTime Birthday; } public class Sample { public static void WriteConsole() { var users = new[] { new User {Id = 1, Name = "Bill Gates", Birthday = DateTime.Parse("1955/10/28")}, new User {Id = 2, Name = "Steven Jobs", Birthday = DateTime.Parse("1955/2/24")} }; Build .TextTable<User>(builder => { builder .Margins.Left.As(4) .Margins.Right.As(2); }) .WriteLine(users); var text = Build .TextTable<User>(builder => { builder .Margins.Left.As(4) .Margins.Right.As(2); }) .ToString(users); } } }
25.642857
96
0.411328
[ "MIT" ]
nuitsjp/FluentTextTable
src/FluentTextTable.Sample/11.Margins/Sample.cs
1,079
C#
using System; using System.Collections.Generic; using RimWorld; using UnityEngine; namespace CompCamo { // Token: 0x02000007 RID: 7 public class CamoPresetColour { // Token: 0x17000003 RID: 3 // (get) Token: 0x06000045 RID: 69 RVA: 0x00004AD0 File Offset: 0x00002CD0 public static Color Orange { get { return new Color(0.870588243f, 0.509803951f, 0f, 1f); } } // Token: 0x17000004 RID: 4 // (get) Token: 0x06000046 RID: 70 RVA: 0x00004AEB File Offset: 0x00002CEB public static Color Purple { get { return new Color(0.5019608f, 0f, 0.3372549f, 1f); } } // Token: 0x17000005 RID: 5 // (get) Token: 0x06000047 RID: 71 RVA: 0x00004B06 File Offset: 0x00002D06 public static Color Violet { get { return new Color(1f, 0.41568628f, 0.7607843f, 1f); } } // Token: 0x17000006 RID: 6 // (get) Token: 0x06000048 RID: 72 RVA: 0x00004B21 File Offset: 0x00002D21 public static Color Brown { get { return new Color(0.392156869f, 0.1254902f, 0.0784313753f, 1f); } } // Token: 0x06000049 RID: 73 RVA: 0x00004B3C File Offset: 0x00002D3C public static List<Color> colourChoices() { return new List<Color> { Color.white, Color.black, Color.red, Color.green, Color.blue, Color.yellow, Color.cyan, CamoPresetColour.Purple, CamoPresetColour.Orange, CamoPresetColour.Brown, CamoPresetColour.Violet }; } // Token: 0x0600004A RID: 74 RVA: 0x00004BC8 File Offset: 0x00002DC8 public static string GetClosestType(Apparel apparel) { string result = "White"; Color color = Color.white; Color drawColor = apparel.DrawColor; List<Color> list = CamoPresetColour.colourChoices(); if (list.Count > 0) { float num = 9f; foreach (Color color2 in list) { float num2 = CamoPresetColour.ColourCompare(drawColor, color2); if (num2 < num) { color = color2; num = num2; } } } if (color == Color.white) { result = "White"; } else if (color == Color.black) { result = "Black"; } else if (color == Color.red) { result = "Red"; } else if (color == CamoPresetColour.Orange) { result = "Orange"; } else if (color == Color.yellow) { result = "Yellow"; } else if (color == Color.green) { result = "Green"; } else if (color == Color.blue) { result = "Blue"; } else if (color == Color.cyan) { result = "Cyan"; } else if (color == CamoPresetColour.Violet) { result = "Violet"; } else if (color == CamoPresetColour.Purple) { result = "Purple"; } else if (color == CamoPresetColour.Brown) { result = "Brown"; } return result; } // Token: 0x0600004B RID: 75 RVA: 0x00004D44 File Offset: 0x00002F44 public static float ColourCompare(Color color, Color compare) { return 0f + Math.Abs(color.r - compare.r) + Math.Abs(color.g - compare.g) + Math.Abs(color.b - compare.b); } } }
20.9375
109
0.6199
[ "MIT" ]
Lucas559-noob/CamouflageandStealth
Source/CompCamo/CamoPresetColour.cs
3,017
C#
namespace Dapper.Query { public class JoinClause { internal JoinType JoinType { get; set; } internal SelectStatement ParentStatement { get; set; } internal Table JoinedTable { get; set; } internal Predicate OnPredicate { get; set; } internal JoinClause(SelectStatement parentStatement, Table joinedTable, JoinType joinType) { this.ParentStatement = parentStatement; this.JoinedTable = joinedTable; this.JoinType = joinType; } public IFromClause On(Predicate predicate) { this.OnPredicate = predicate; return this.ParentStatement; } public override string ToString() { string s = string.Empty; if (this.JoinType == JoinType.Inner) { s = "inner join "; } else if(this.JoinType == JoinType.Left) { s = "left outer join "; } else { s = "right outer join "; } s += this.JoinedTable.ToString(); s += " on "; s += this.OnPredicate.ToString(); return s; } } }
28.340909
98
0.504411
[ "MIT" ]
jdcgamer/DapperQuery
src/Dapper.Query/JoinClause.cs
1,249
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace MultiColorSliders.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); LoadApplication(new App()); return base.FinishedLaunching(app, options); } } }
34.59375
98
0.680217
[ "Apache-2.0" ]
DLozanoNavas/xamarin-forms-book-samples
Chapter23/MultiColorSliders/MultiColorSliders/MultiColorSliders.iOS/AppDelegate.cs
1,107
C#
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Intelligob.Servidor.Services { using Telerik.OpenAccess; using System.Linq.Dynamic; using Intelligob.Entidades; using Intelligob.Servidor.Dto; using Intelligob.Servidor.Assemblers; using Intelligob.Servidor.Repositories; using Intelligob.Servidor.Converters; using System; using System.Linq; using System.Linq.Expressions; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; public partial interface IService<TDto, TEntity> where TEntity : class where TDto : IDtoWithKey { IAssembler<TDto, TEntity> Assembler { get; } IRepository<TEntity> Repository { get; } IEnumerable<TDto> Find(Expression<Func<TEntity, bool>> filter); IEnumerable<TDto> GetAll(); IEnumerable<TDto> Find(int startRowIndex, int maximumRows); IEnumerable<TDto> Find(string sortExpression, string filterExpression); IEnumerable<TDto> Find(int? startRowIndex, int? maximumRows, string sortExpression, string filterExpression); int Count(); int Count(string filterExpression); TDto GetByKey(string dtoKey); string Add(TDto dto); void Update(TDto dto); void Delete(TDto dto); } public abstract partial class Service<TDto, TEntity> : IService<TDto, TEntity> where TEntity : class where TDto : IDtoWithKey { IAssembler<TDto, TEntity> assembler; IRepository<TEntity> repository; public Service(IAssembler<TDto, TEntity> assembler, IRepository<TEntity> repository) { this.assembler = assembler; this.repository = repository; } public IAssembler<TDto, TEntity> Assembler { get { return this.assembler; } } public IRepository<TEntity> Repository { get { return this.repository; } } public virtual IEnumerable<TDto> GetAll() { return this.assembler.Assemble(this.Repository.GetAll()); } public virtual IEnumerable<TDto> Find(Expression<Func<TEntity, bool>> filter) { return this.Assembler.Assemble(this.Repository.Find(filter)); } public virtual IEnumerable<TDto> Find(int startRowIndex, int maximumRows) { return this.Find(startRowIndex, maximumRows, null, null); } public virtual IEnumerable<TDto> Find(string sortExpression, string filterExpression) { return this.Find(null, null, sortExpression, filterExpression); } public virtual IEnumerable<TDto> Find(int? startRowIndex, int? maximumRows, string sortExpression, string filterExpression) { IQueryable<TEntity> query = this.Repository.GetAll(); /*if (!string.IsNullOrEmpty(filterExpression)) { query = query.Where(filterExpression); } if (!string.IsNullOrEmpty(sortExpression)) { query = query.OrderBy(sortExpression); }*/ if (startRowIndex.HasValue) { query = query.Skip(startRowIndex.Value); } if (maximumRows.HasValue) { query = query.Take(maximumRows.Value); } return this.Assembler.Assemble(query); } public virtual int Count() { return this.Count(string.Empty); } public virtual int Count(string filterExpression) { IQueryable<TEntity> query = this.Repository.GetAll(); /*if (!string.IsNullOrEmpty(filterExpression)) { query = query.Where(filterExpression); }*/ return query.Count(); } public virtual TDto GetByKey(string dtoKey) { ObjectKey key = KeyUtility.Instance.Convert<TEntity>(dtoKey); return this.assembler.Assemble(this.Repository.Get(key)); } public virtual string Add(TDto dto) { TEntity entity = this.assembler.Assemble(null, dto); this.repository.Add(entity); ObjectKey key = KeyUtility.Instance.Create(entity); return KeyUtility.Instance.Convert(key); } public virtual void Update(TDto dto) { ObjectKey key = KeyUtility.Instance.Convert<TEntity>(dto.DtoKey); TEntity entity = this.repository.Get(key); this.assembler.Assemble(entity, dto); } public virtual void Delete(TDto dto) { ObjectKey key = KeyUtility.Instance.Convert<TEntity>(dto.DtoKey); TEntity entity = this.repository.Get(key); this.Repository.Remove(entity); } } public partial interface ITablaClaveService : IService<TablaClaveDto, TablaClave> { } public partial class TablaClaveService : Service<TablaClaveDto, TablaClave>, ITablaClaveService { public TablaClaveService(ITablaClaveAssembler assembler, ITablaClaveRepository repository) : base(assembler, repository) { } } public partial interface ITablaService : IService<TablaDto, Tabla> { } public partial class TablaService : Service<TablaDto, Tabla>, ITablaService { public TablaService(ITablaAssembler assembler, ITablaRepository repository) : base(assembler, repository) { } } public partial interface IContribuyenteService : IService<ContribuyenteDto, Contribuyente> { } public partial class ContribuyenteService : Service<ContribuyenteDto, Contribuyente>, IContribuyenteService { public ContribuyenteService(IContribuyenteAssembler assembler, IContribuyenteRepository repository) : base(assembler, repository) { } } public partial interface IRubroService : IService<RubroDto, Rubro> { } public partial class RubroService : Service<RubroDto, Rubro>, IRubroService { public RubroService(IRubroAssembler assembler, IRubroRepository repository) : base(assembler, repository) { } } public partial interface IRebajasRubroService : IService<RebajasRubroDto, RebajasRubro> { } public partial class RebajasRubroService : Service<RebajasRubroDto, RebajasRubro>, IRebajasRubroService { public RebajasRubroService(IRebajasRubroAssembler assembler, IRebajasRubroRepository repository) : base(assembler, repository) { } } public partial interface IRebajaService : IService<RebajaDto, Rebaja> { } public partial class RebajaService : Service<RebajaDto, Rebaja>, IRebajaService { public RebajaService(IRebajaAssembler assembler, IRebajaRepository repository) : base(assembler, repository) { } } public partial interface IContribuyentesRebajaService : IService<ContribuyentesRebajaDto, ContribuyentesRebaja> { } public partial class ContribuyentesRebajaService : Service<ContribuyentesRebajaDto, ContribuyentesRebaja>, IContribuyentesRebajaService { public ContribuyentesRebajaService(IContribuyentesRebajaAssembler assembler, IContribuyentesRebajaRepository repository) : base(assembler, repository) { } } public partial interface IPredioTerrenoService : IService<PredioTerrenoDto, PredioTerreno> { } public partial class PredioTerrenoService : Service<PredioTerrenoDto, PredioTerreno>, IPredioTerrenoService { public PredioTerrenoService(IPredioTerrenoAssembler assembler, IPredioTerrenoRepository repository) : base(assembler, repository) { } } public partial interface IPredioTablaService : IService<PredioTablaDto, PredioTabla> { } public partial class PredioTablaService : Service<PredioTablaDto, PredioTabla>, IPredioTablaService { public PredioTablaService(IPredioTablaAssembler assembler, IPredioTablaRepository repository) : base(assembler, repository) { } } public partial interface IPredioPropietarioService : IService<PredioPropietarioDto, PredioPropietario> { } public partial class PredioPropietarioService : Service<PredioPropietarioDto, PredioPropietario>, IPredioPropietarioService { public PredioPropietarioService(IPredioPropietarioAssembler assembler, IPredioPropietarioRepository repository) : base(assembler, repository) { } } public partial interface IPredioPisoService : IService<PredioPisoDto, PredioPiso> { } public partial class PredioPisoService : Service<PredioPisoDto, PredioPiso>, IPredioPisoService { public PredioPisoService(IPredioPisoAssembler assembler, IPredioPisoRepository repository) : base(assembler, repository) { } } public partial interface IPredioFrenteService : IService<PredioFrenteDto, PredioFrente> { } public partial class PredioFrenteService : Service<PredioFrenteDto, PredioFrente>, IPredioFrenteService { public PredioFrenteService(IPredioFrenteAssembler assembler, IPredioFrenteRepository repository) : base(assembler, repository) { } } public partial interface IPredioFotoService : IService<PredioFotoDto, PredioFoto> { } public partial class PredioFotoService : Service<PredioFotoDto, PredioFoto>, IPredioFotoService { public PredioFotoService(IPredioFotoAssembler assembler, IPredioFotoRepository repository) : base(assembler, repository) { } } public partial interface IPredioConstruccionService : IService<PredioConstruccionDto, PredioConstruccion> { } public partial class PredioConstruccionService : Service<PredioConstruccionDto, PredioConstruccion>, IPredioConstruccionService { public PredioConstruccionService(IPredioConstruccionAssembler assembler, IPredioConstruccionRepository repository) : base(assembler, repository) { } } public partial interface IPredioBloqueService : IService<PredioBloqueDto, PredioBloque> { } public partial class PredioBloqueService : Service<PredioBloqueDto, PredioBloque>, IPredioBloqueService { public PredioBloqueService(IPredioBloqueAssembler assembler, IPredioBloqueRepository repository) : base(assembler, repository) { } } public partial interface IPredioBaseService : IService<PredioBaseDto, PredioBase> { } public partial class PredioBaseService : Service<PredioBaseDto, PredioBase>, IPredioBaseService { public PredioBaseService(IPredioBaseAssembler assembler, IPredioBaseRepository repository) : base(assembler, repository) { } } public partial interface IServicioService : IService<ServicioDto, Servicio> { } public partial class ServicioService : Service<ServicioDto, Servicio>, IServicioService { public ServicioService(IServicioAssembler assembler, IServicioRepository repository) : base(assembler, repository) { } } public partial interface IPatenteService : IService<PatenteDto, Patente> { } public partial class PatenteService : Service<PatenteDto, Patente>, IPatenteService { public PatenteService(IPatenteAssembler assembler, IPatenteRepository repository) : base(assembler, repository) { } } public partial interface IAguaPotableService : IService<AguaPotableDto, AguaPotable> { } public partial class AguaPotableService : Service<AguaPotableDto, AguaPotable>, IAguaPotableService { public AguaPotableService(IAguaPotableAssembler assembler, IAguaPotableRepository repository) : base(assembler, repository) { } } public partial interface IAguaLecturaService : IService<AguaLecturaDto, AguaLectura> { } public partial class AguaLecturaService : Service<AguaLecturaDto, AguaLectura>, IAguaLecturaService { public AguaLecturaService(IAguaLecturaAssembler assembler, IAguaLecturaRepository repository) : base(assembler, repository) { } } public partial interface IPatentesComponenteService : IService<PatentesComponenteDto, PatentesComponente> { } public partial class PatentesComponenteService : Service<PatentesComponenteDto, PatentesComponente>, IPatentesComponenteService { public PatentesComponenteService(IPatentesComponenteAssembler assembler, IPatentesComponenteRepository repository) : base(assembler, repository) { } } public partial interface IConceptoService : IService<ConceptoDto, Concepto> { } public partial class ConceptoService : Service<ConceptoDto, Concepto>, IConceptoService { public ConceptoService(IConceptoAssembler assembler, IConceptoRepository repository) : base(assembler, repository) { } } public partial interface ICoeficienteService : IService<CoeficienteDto, Coeficiente> { } public partial class CoeficienteService : Service<CoeficienteDto, Coeficiente>, ICoeficienteService { public CoeficienteService(ICoeficienteAssembler assembler, ICoeficienteRepository repository) : base(assembler, repository) { } } public partial interface ICoeficienteElementoService : IService<CoeficienteElementoDto, CoeficienteElemento> { } public partial class CoeficienteElementoService : Service<CoeficienteElementoDto, CoeficienteElemento>, ICoeficienteElementoService { public CoeficienteElementoService(ICoeficienteElementoAssembler assembler, ICoeficienteElementoRepository repository) : base(assembler, repository) { } } public partial interface ISupervisionService : IService<SupervisionDto, Supervision> { } public partial class SupervisionService : Service<SupervisionDto, Supervision>, ISupervisionService { public SupervisionService(ISupervisionAssembler assembler, ISupervisionRepository repository) : base(assembler, repository) { } } public partial interface IPrivilegioService : IService<PrivilegioDto, Privilegio> { } public partial class PrivilegioService : Service<PrivilegioDto, Privilegio>, IPrivilegioService { public PrivilegioService(IPrivilegioAssembler assembler, IPrivilegioRepository repository) : base(assembler, repository) { } } public partial interface IUsuarioService : IService<UsuarioDto, Usuario> { } public partial class UsuarioService : Service<UsuarioDto, Usuario>, IUsuarioService { public UsuarioService(IUsuarioAssembler assembler, IUsuarioRepository repository) : base(assembler, repository) { } } public partial interface IComandoService : IService<ComandoDto, Comando> { } public partial class ComandoService : Service<ComandoDto, Comando>, IComandoService { public ComandoService(IComandoAssembler assembler, IComandoRepository repository) : base(assembler, repository) { } } public partial interface IFuncionService : IService<FuncionDto, Funcion> { } public partial class FuncionService : Service<FuncionDto, Funcion>, IFuncionService { public FuncionService(IFuncionAssembler assembler, IFuncionRepository repository) : base(assembler, repository) { } } public partial interface IAutorizacionService : IService<AutorizacionDto, Autorizacion> { } public partial class AutorizacionService : Service<AutorizacionDto, Autorizacion>, IAutorizacionService { public AutorizacionService(IAutorizacionAssembler assembler, IAutorizacionRepository repository) : base(assembler, repository) { } } public partial interface IModuloUsuarioService : IService<ModuloUsuarioDto, ModuloUsuario> { } public partial class ModuloUsuarioService : Service<ModuloUsuarioDto, ModuloUsuario>, IModuloUsuarioService { public ModuloUsuarioService(IModuloUsuarioAssembler assembler, IModuloUsuarioRepository repository) : base(assembler, repository) { } } public partial interface ISeguimientoService : IService<SeguimientoDto, Seguimiento> { } public partial class SeguimientoService : Service<SeguimientoDto, Seguimiento>, ISeguimientoService { public SeguimientoService(ISeguimientoAssembler assembler, ISeguimientoRepository repository) : base(assembler, repository) { } } public partial interface IRubrosParametroService : IService<RubrosParametroDto, RubrosParametro> { } public partial class RubrosParametroService : Service<RubrosParametroDto, RubrosParametro>, IRubrosParametroService { public RubrosParametroService(IRubrosParametroAssembler assembler, IRubrosParametroRepository repository) : base(assembler, repository) { } } public partial interface IConceptosRubroService : IService<ConceptosRubroDto, ConceptosRubro> { } public partial class ConceptosRubroService : Service<ConceptosRubroDto, ConceptosRubro>, IConceptosRubroService { public ConceptosRubroService(IConceptosRubroAssembler assembler, IConceptosRubroRepository repository) : base(assembler, repository) { } } public partial interface IConceptosDocumentoService : IService<ConceptosDocumentoDto, ConceptosDocumento> { } public partial class ConceptosDocumentoService : Service<ConceptosDocumentoDto, ConceptosDocumento>, IConceptosDocumentoService { public ConceptosDocumentoService(IConceptosDocumentoAssembler assembler, IConceptosDocumentoRepository repository) : base(assembler, repository) { } } public partial interface IAguaServicioService : IService<AguaServicioDto, AguaServicio> { } public partial class AguaServicioService : Service<AguaServicioDto, AguaServicio>, IAguaServicioService { public AguaServicioService(IAguaServicioAssembler assembler, IAguaServicioRepository repository) : base(assembler, repository) { } } public partial interface IPlanillaSustitucionService : IService<PlanillaSustitucionDto, PlanillaSustitucion> { } public partial class PlanillaSustitucionService : Service<PlanillaSustitucionDto, PlanillaSustitucion>, IPlanillaSustitucionService { public PlanillaSustitucionService(IPlanillaSustitucionAssembler assembler, IPlanillaSustitucionRepository repository) : base(assembler, repository) { } } public partial interface IPlanillaRubroService : IService<PlanillaRubroDto, PlanillaRubro> { } public partial class PlanillaRubroService : Service<PlanillaRubroDto, PlanillaRubro>, IPlanillaRubroService { public PlanillaRubroService(IPlanillaRubroAssembler assembler, IPlanillaRubroRepository repository) : base(assembler, repository) { } } public partial interface IPlanillaAtributoService : IService<PlanillaAtributoDto, PlanillaAtributo> { } public partial class PlanillaAtributoService : Service<PlanillaAtributoDto, PlanillaAtributo>, IPlanillaAtributoService { public PlanillaAtributoService(IPlanillaAtributoAssembler assembler, IPlanillaAtributoRepository repository) : base(assembler, repository) { } } public partial interface IPlanillaService : IService<PlanillaDto, Planilla> { } public partial class PlanillaService : Service<PlanillaDto, Planilla>, IPlanillaService { public PlanillaService(IPlanillaAssembler assembler, IPlanillaRepository repository) : base(assembler, repository) { } } public partial interface IConvenioTransaccionService : IService<ConvenioTransaccionDto, ConvenioTransaccion> { } public partial class ConvenioTransaccionService : Service<ConvenioTransaccionDto, ConvenioTransaccion>, IConvenioTransaccionService { public ConvenioTransaccionService(IConvenioTransaccionAssembler assembler, IConvenioTransaccionRepository repository) : base(assembler, repository) { } } public partial interface IConvenioService : IService<ConvenioDto, Convenio> { } public partial class ConvenioService : Service<ConvenioDto, Convenio>, IConvenioService { public ConvenioService(IConvenioAssembler assembler, IConvenioRepository repository) : base(assembler, repository) { } } public partial interface ICobroTransaccionService : IService<CobroTransaccionDto, CobroTransaccion> { } public partial class CobroTransaccionService : Service<CobroTransaccionDto, CobroTransaccion>, ICobroTransaccionService { public CobroTransaccionService(ICobroTransaccionAssembler assembler, ICobroTransaccionRepository repository) : base(assembler, repository) { } } public partial interface ICobroService : IService<CobroDto, Cobro> { } public partial class CobroService : Service<CobroDto, Cobro>, ICobroService { public CobroService(ICobroAssembler assembler, ICobroRepository repository) : base(assembler, repository) { } } public partial interface ICobrosElementoService : IService<CobrosElementoDto, CobrosElemento> { } public partial class CobrosElementoService : Service<CobrosElementoDto, CobrosElemento>, ICobrosElementoService { public CobrosElementoService(ICobrosElementoAssembler assembler, ICobrosElementoRepository repository) : base(assembler, repository) { } } public partial interface ICobrosRubroService : IService<CobrosRubroDto, CobrosRubro> { } public partial class CobrosRubroService : Service<CobrosRubroDto, CobrosRubro>, ICobrosRubroService { public CobrosRubroService(ICobrosRubroAssembler assembler, ICobrosRubroRepository repository) : base(assembler, repository) { } } public partial interface IRepRecaudacionesFechaService : IService<RepRecaudacionesFechaDto, RepRecaudacionesFecha> { } public partial class RepRecaudacionesFechaService : Service<RepRecaudacionesFechaDto, RepRecaudacionesFecha>, IRepRecaudacionesFechaService { public RepRecaudacionesFechaService(IRepRecaudacionesFechaAssembler assembler, IRepRecaudacionesFechaRepository repository) : base(assembler, repository) { } } public partial interface IRepEmisionesSaldoService : IService<RepEmisionesSaldoDto, RepEmisionesSaldo> { } public partial class RepEmisionesSaldoService : Service<RepEmisionesSaldoDto, RepEmisionesSaldo>, IRepEmisionesSaldoService { public RepEmisionesSaldoService(IRepEmisionesSaldoAssembler assembler, IRepEmisionesSaldoRepository repository) : base(assembler, repository) { } } public partial interface IConceptosEmisionService : IService<ConceptosEmisionDto, ConceptosEmision> { } public partial class ConceptosEmisionService : Service<ConceptosEmisionDto, ConceptosEmision>, IConceptosEmisionService { public ConceptosEmisionService(IConceptosEmisionAssembler assembler, IConceptosEmisionRepository repository) : base(assembler, repository) { } } public partial interface IModuloService : IService<ModuloDto, Modulo> { } public partial class ModuloService : Service<ModuloDto, Modulo>, IModuloService { public ModuloService(IModuloAssembler assembler, IModuloRepository repository) : base(assembler, repository) { } } public partial interface IReporteService : IService<ReporteDto, Reporte> { } public partial class ReporteService : Service<ReporteDto, Reporte>, IReporteService { public ReporteService(IReporteAssembler assembler, IReporteRepository repository) : base(assembler, repository) { } } public partial interface IRepCuentaCorrienteResumenService : IService<RepCuentaCorrienteResumenDto, RepCuentaCorrienteResumen> { } public partial class RepCuentaCorrienteResumenService : Service<RepCuentaCorrienteResumenDto, RepCuentaCorrienteResumen>, IRepCuentaCorrienteResumenService { public RepCuentaCorrienteResumenService(IRepCuentaCorrienteResumenAssembler assembler, IRepCuentaCorrienteResumenRepository repository) : base(assembler, repository) { } } public partial interface IRepCuentaCorrienteDetalleService : IService<RepCuentaCorrienteDetalleDto, RepCuentaCorrienteDetalle> { } public partial class RepCuentaCorrienteDetalleService : Service<RepCuentaCorrienteDetalleDto, RepCuentaCorrienteDetalle>, IRepCuentaCorrienteDetalleService { public RepCuentaCorrienteDetalleService(IRepCuentaCorrienteDetalleAssembler assembler, IRepCuentaCorrienteDetalleRepository repository) : base(assembler, repository) { } } public partial interface ICajaService : IService<CajaDto, Caja> { } public partial class CajaService : Service<CajaDto, Caja>, ICajaService { public CajaService(ICajaAssembler assembler, ICajaRepository repository) : base(assembler, repository) { } } public partial interface ICajasUsuarioService : IService<CajasUsuarioDto, CajasUsuario> { } public partial class CajasUsuarioService : Service<CajasUsuarioDto, CajasUsuario>, ICajasUsuarioService { public CajasUsuarioService(ICajasUsuarioAssembler assembler, ICajasUsuarioRepository repository) : base(assembler, repository) { } } public partial interface IRepPredioService : IService<RepPredioDto, RepPredio> { } public partial class RepPredioService : Service<RepPredioDto, RepPredio>, IRepPredioService { public RepPredioService(IRepPredioAssembler assembler, IRepPredioRepository repository) : base(assembler, repository) { } } public partial interface ICuentaBancariaService : IService<CuentaBancariaDto, CuentaBancaria> { } public partial class CuentaBancariaService : Service<CuentaBancariaDto, CuentaBancaria>, ICuentaBancariaService { public CuentaBancariaService(ICuentaBancariaAssembler assembler, ICuentaBancariaRepository repository) : base(assembler, repository) { } } public partial interface ICajaElementoService : IService<CajaElementoDto, CajaElemento> { } public partial class CajaElementoService : Service<CajaElementoDto, CajaElemento>, ICajaElementoService { public CajaElementoService(ICajaElementoAssembler assembler, ICajaElementoRepository repository) : base(assembler, repository) { } } public partial interface ICajaComprobanteService : IService<CajaComprobanteDto, CajaComprobante> { } public partial class CajaComprobanteService : Service<CajaComprobanteDto, CajaComprobante>, ICajaComprobanteService { public CajaComprobanteService(ICajaComprobanteAssembler assembler, ICajaComprobanteRepository repository) : base(assembler, repository) { } } public partial interface ICarpetaCatastralAnualService : IService<CarpetaCatastralAnualDto, CarpetaCatastralAnual> { } public partial class CarpetaCatastralAnualService : Service<CarpetaCatastralAnualDto, CarpetaCatastralAnual>, ICarpetaCatastralAnualService { public CarpetaCatastralAnualService(ICarpetaCatastralAnualAssembler assembler, ICarpetaCatastralAnualRepository repository) : base(assembler, repository) { } } public partial interface ISoporteService : IService<SoporteDto, Soporte> { } public partial class SoporteService : Service<SoporteDto, Soporte>, ISoporteService { public SoporteService(ISoporteAssembler assembler, ISoporteRepository repository) : base(assembler, repository) { } } public partial interface ISoporteMovimientoService : IService<SoporteMovimientoDto, SoporteMovimiento> { } public partial class SoporteMovimientoService : Service<SoporteMovimientoDto, SoporteMovimiento>, ISoporteMovimientoService { public SoporteMovimientoService(ISoporteMovimientoAssembler assembler, ISoporteMovimientoRepository repository) : base(assembler, repository) { } } public partial interface IMejoraElementoService : IService<MejoraElementoDto, MejoraElemento> { } public partial class MejoraElementoService : Service<MejoraElementoDto, MejoraElemento>, IMejoraElementoService { public MejoraElementoService(IMejoraElementoAssembler assembler, IMejoraElementoRepository repository) : base(assembler, repository) { } } public partial interface IMejoraService : IService<MejoraDto, Mejora> { } public partial class MejoraService : Service<MejoraDto, Mejora>, IMejoraService { public MejoraService(IMejoraAssembler assembler, IMejoraRepository repository) : base(assembler, repository) { } } public partial interface IRepRecaudacionesCompDetalleService : IService<RepRecaudacionesCompDetalleDto, RepRecaudacionesCompDetalle> { } public partial class RepRecaudacionesCompDetalleService : Service<RepRecaudacionesCompDetalleDto, RepRecaudacionesCompDetalle>, IRepRecaudacionesCompDetalleService { public RepRecaudacionesCompDetalleService(IRepRecaudacionesCompDetalleAssembler assembler, IRepRecaudacionesCompDetalleRepository repository) : base(assembler, repository) { } } public partial interface ICobrosNotasElementoService : IService<CobrosNotasElementoDto, CobrosNotasElemento> { } public partial class CobrosNotasElementoService : Service<CobrosNotasElementoDto, CobrosNotasElemento>, ICobrosNotasElementoService { public CobrosNotasElementoService(ICobrosNotasElementoAssembler assembler, ICobrosNotasElementoRepository repository) : base(assembler, repository) { } } public partial interface ICobrosNotaService : IService<CobrosNotaDto, CobrosNota> { } public partial class CobrosNotaService : Service<CobrosNotaDto, CobrosNota>, ICobrosNotaService { public CobrosNotaService(ICobrosNotaAssembler assembler, ICobrosNotaRepository repository) : base(assembler, repository) { } } public partial interface IRepReversionesFechaService : IService<RepReversionesFechaDto, RepReversionesFecha> { } public partial class RepReversionesFechaService : Service<RepReversionesFechaDto, RepReversionesFecha>, IRepReversionesFechaService { public RepReversionesFechaService(IRepReversionesFechaAssembler assembler, IRepReversionesFechaRepository repository) : base(assembler, repository) { } } public partial interface IConveniosDividendoService : IService<ConveniosDividendoDto, ConveniosDividendo> { } public partial class ConveniosDividendoService : Service<ConveniosDividendoDto, ConveniosDividendo>, IConveniosDividendoService { public ConveniosDividendoService(IConveniosDividendoAssembler assembler, IConveniosDividendoRepository repository) : base(assembler, repository) { } } public partial interface IPlanillaMesService : IService<PlanillaMesDto, PlanillaMes> { } public partial class PlanillaMesService : Service<PlanillaMesDto, PlanillaMes>, IPlanillaMesService { public PlanillaMesService(IPlanillaMesAssembler assembler, IPlanillaMesRepository repository) : base(assembler, repository) { } } public partial interface IMercadoService : IService<MercadoDto, Mercado> { } public partial class MercadoService : Service<MercadoDto, Mercado>, IMercadoService { public MercadoService(IMercadoAssembler assembler, IMercadoRepository repository) : base(assembler, repository) { } } } #pragma warning restore 1591
27.039216
164
0.740675
[ "CC0-1.0" ]
jmbarberan/gobman
IntelligobServidor/Services.cs
31,717
C#
using BenchmarkCmp.Models.Internal; using BenchmarkCmp.Models.Output; using System.Linq; namespace BenchmarkCmp.Comparers { public class BranchMispredictionsComparer : BaseValueComparer { public override BenchmarkBranchMispredictionsComparing[] Compare(Benchmark[] old, Benchmark[] @new) { old = old.Where(x => x.BranchMispredictions != null).ToArray(); @new = @new.Where(x => x.BranchMispredictions != null).ToArray(); return old .Join(@new, old => old.Name, @new => @new.Name, (old, @new) => new BenchmarkBranchMispredictionsComparing { Benchmark = old.Name, ValueOld = old.BranchMispredictions.Value, ValueNew = @new.BranchMispredictions.Value }) .ToArray(); } } }
33.821429
107
0.538543
[ "MIT" ]
yakivyusin/BenchmarkCmp
BenchmarkCmp/Comparers/BranchMispredictionsComparer.cs
949
C#
using UniInject; using UnityEngine; using UnityEngine.UIElements; public class AudioWaveFormVisualization : INeedInjection { public Color WaveformColor { get; set; }= Color.white; private readonly DynamicTexture dynTexture; public AudioWaveFormVisualization(GameObject gameObject, VisualElement visualElement) { dynTexture = new DynamicTexture(gameObject, visualElement); } public void Destroy() { dynTexture.Destroy(); } public void DrawWaveFormMinAndMaxValues(AudioClip audioClip) { if (audioClip == null || audioClip.samples == 0) { return; } dynTexture.ClearTexture(); Vector2[] minMaxValues = CalculateMinAndMaxValues(audioClip); DrawMinAndMaxValuesToTexture(minMaxValues); } public void DrawWaveFormValues(float[] samples, int offset, int length) { if (samples == null || samples.Length == 0 || !dynTexture.IsInitialized) { return; } dynTexture.ClearTexture(); // Draw the waveform for (int x = 0; x < dynTexture.TextureWidth; x++) { int sampleIndex = offset + length * x / dynTexture.TextureWidth; if (sampleIndex >= samples.Length) { break; } float value = samples[sampleIndex]; // Draw the pixels int y = (int)(dynTexture.TextureHeight * (value + 1f) / 2f); dynTexture.SetPixel(x, y, WaveformColor); } // upload to the graphics card dynTexture.ApplyTexture(); } public void DrawWaveFormMinAndMaxValues(float[] samples) { if (samples.IsNullOrEmpty() || !dynTexture.IsInitialized) { return; } dynTexture.ClearTexture(); Vector2[] minMaxValues = CalculateMinAndMaxValues(samples); DrawMinAndMaxValuesToTexture(minMaxValues); } private float[] CopyAudioClipSamples(AudioClip audioClip) { float[] samples = new float[audioClip.samples]; audioClip.GetData(samples, 0); return samples; } private Vector2[] CalculateMinAndMaxValues(float[] samples) { Vector2[] minMaxValues = new Vector2[dynTexture.TextureWidth]; // calculate window size to fit all samples in the texture int windowSize = samples.Length / dynTexture.TextureWidth; // move the window over all the samples. For each position, find the min and max value. for (int i = 0; i < dynTexture.TextureWidth; i++) { int offset = i * windowSize; Vector2 minMax = FindMinAndMaxValues(samples, offset, windowSize); minMaxValues[i] = minMax; } return minMaxValues; } private Vector2[] CalculateMinAndMaxValues(AudioClip audioClip) { Vector2[] minMaxValues = new Vector2[dynTexture.TextureWidth]; // calculate window size to fit all samples in the texture int windowSize = audioClip.samples / dynTexture.TextureWidth; float[] windowSamples = new float[windowSize]; // move the window over all the samples. For each position, find the min and max value. for (int i = 0; i < dynTexture.TextureWidth; i++) { int offset = i * windowSize; audioClip.GetData(windowSamples, offset); Vector2 minMax = FindMinAndMaxValues(windowSamples, 0, windowSize); minMaxValues[i] = minMax; } return minMaxValues; } private Vector2 FindMinAndMaxValues(float[] samples, int offset, int length) { float min = float.MaxValue; float max = float.MinValue; for (int i = 0; i < length; i++) { int index = offset + i; if (index >= samples.Length) { break; } float f = samples[index]; if (f < min) { min = f; } if (f > max) { max = f; } } return new Vector2(min, max); } private void DrawMinAndMaxValuesToTexture(Vector2[] minMaxValues) { // Draw the waveform for (int x = 0; x < dynTexture.TextureWidth; x++) { Vector2 minMax = minMaxValues[x]; float min = minMax.x; float max = minMax.y; // Draw the pixels int yMin = (int)(dynTexture.TextureHeight * (min + 1f) / 2f); int yMax = (int)(dynTexture.TextureHeight * (max + 1f) / 2f); for (int y = yMin; y < yMax; y++) { dynTexture.SetPixel(x, y, WaveformColor); } } // upload to the graphics card dynTexture.ApplyTexture(); } }
28.473684
95
0.569316
[ "MIT" ]
achimmihca/Play
UltraStar Play/Packages/playshared/Runtime/Audio/AudioWaveFormVisualization.cs
4,871
C#
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Core.TimerJobs.Samples.ExpandJobAppOnly { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// This method is deprecated because the autohosted option is no longer available. /// </summary> [ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)] public string GetDatabaseConnectionString() { throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available."); } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; bool contextTokenExpired = false; try { if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } } catch (SecurityTokenExpiredException) { contextTokenExpired = true; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
39.215135
199
0.609362
[ "Apache-2.0" ]
AKrasheninnikov/PnP
Solutions/Core.TimerJobs.Samples/Core.TimerJobs.Samples.ExpandJobAppOnly/SharePointContext.cs
36,274
C#
using System; using System.Collections.Generic; using ArcanaStudio.Toolkit.Functional; namespace Toolkit.Tests.Functional.TestCasesSource { public static class EitherAdaptersTestCaseSources { public static IEnumerable<object[]> MapFuncTest { get { var s = "test"; var func = new Func<string, int>(s => s.Length); yield return new object[] { new Left<double,string>(10), func, typeof(Left<double, int>) }; yield return new object[] { new Right<double, string>(s), func, typeof(Right<double, int>) }; } } public static IEnumerable<object[]> MapLazyFuncTest { get { var s = "test"; var func = new Func<string, Either<double,int>>(s => s.Length); yield return new object[] { new Left<double, string>(10), func, typeof(Left<double, int>) }; yield return new object[] { new Right<double, string>(s), func, typeof(Right<double, int>) }; } } public static IEnumerable<object[]> ReduceTest { get { var s = "test"; var func = new Func<int, string>(s => s.ToString()); yield return new object[] { new Left<int, string>(10), func, "10" }; yield return new object[] { new Right<int, string>(s), func, s }; } } } }
35.452381
109
0.519812
[ "MIT" ]
ArcanaStudio/Arcana-Toolk
src/Tests/Toolkit.Tests/Functional/TestCasesSource/EitherAdaptersTestCaseSources.cs
1,491
C#
using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Net; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.ClientObservers; using Orleans.CodeGeneration; using Orleans.Configuration; using Orleans.Messaging; using Orleans.Providers; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Serialization; using Orleans.Serialization.Invocation; namespace Orleans { internal class OutsideRuntimeClient : IRuntimeClient, IDisposable, IClusterConnectionStatusListener { internal static bool TestOnlyThrowExceptionDuringInit { get; set; } private readonly ILogger logger; private readonly ClientMessagingOptions clientMessagingOptions; private readonly ConcurrentDictionary<CorrelationId, CallbackData> callbacks; private InvokableObjectManager localObjects; private bool disposing; private bool disposed; internal readonly ClientStatisticsManager ClientStatistics; private readonly MessagingTrace messagingTrace; private readonly ClientGrainId clientId; private ThreadTrackingStatistic incomingMessagesThreadTimeTracking; public IInternalGrainFactory InternalGrainFactory { get; private set; } private MessageFactory messageFactory; private IPAddress localAddress; private readonly ILoggerFactory loggerFactory; private readonly IOptions<StatisticsOptions> statisticsOptions; private readonly ApplicationRequestsStatisticsGroup appRequestStatistics; private readonly StageAnalysisStatisticsGroup schedulerStageStatistics; private readonly SharedCallbackData sharedCallbackData; private SafeTimer callbackTimer; public GrainAddress CurrentActivationAddress { get; private set; } public ClientGatewayObserver gatewayObserver { get; private set; } public string CurrentActivationIdentity { get { return CurrentActivationAddress.ToString(); } } public IGrainReferenceRuntime GrainReferenceRuntime { get; private set; } internal ClientMessageCenter MessageCenter { get; private set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "MessageCenter is IDisposable but cannot call Dispose yet as it lives past the end of this method call.")] public OutsideRuntimeClient( ILoggerFactory loggerFactory, IOptions<ClientMessagingOptions> clientMessagingOptions, IOptions<StatisticsOptions> statisticsOptions, ApplicationRequestsStatisticsGroup appRequestStatistics, StageAnalysisStatisticsGroup schedulerStageStatistics, ClientStatisticsManager clientStatisticsManager, MessagingTrace messagingTrace, IServiceProvider serviceProvider) { this.ServiceProvider = serviceProvider; this.loggerFactory = loggerFactory; this.statisticsOptions = statisticsOptions; this.appRequestStatistics = appRequestStatistics; this.schedulerStageStatistics = schedulerStageStatistics; this.ClientStatistics = clientStatisticsManager; this.messagingTrace = messagingTrace; this.logger = loggerFactory.CreateLogger<OutsideRuntimeClient>(); this.clientId = ClientGrainId.Create(); callbacks = new ConcurrentDictionary<CorrelationId, CallbackData>(); this.clientMessagingOptions = clientMessagingOptions.Value; this.sharedCallbackData = new SharedCallbackData( msg => this.UnregisterCallback(msg.Id), this.loggerFactory.CreateLogger<CallbackData>(), this.clientMessagingOptions, this.appRequestStatistics, this.clientMessagingOptions.ResponseTimeout); } internal void ConsumeServices() { try { var connectionLostHandlers = this.ServiceProvider.GetServices<ConnectionToClusterLostHandler>(); foreach (var handler in connectionLostHandlers) { this.ClusterConnectionLost += handler; } var gatewayCountChangedHandlers = this.ServiceProvider.GetServices<GatewayCountChangedHandler>(); foreach (var handler in gatewayCountChangedHandlers) { this.GatewayCountChanged += handler; } this.InternalGrainFactory = this.ServiceProvider.GetRequiredService<IInternalGrainFactory>(); this.messageFactory = this.ServiceProvider.GetService<MessageFactory>(); var copier = this.ServiceProvider.GetRequiredService<DeepCopier>(); this.localObjects = new InvokableObjectManager( ServiceProvider.GetRequiredService<ClientGrainContext>(), this, copier, this.messagingTrace, this.loggerFactory.CreateLogger<ClientGrainContext>()); var timerLogger = this.loggerFactory.CreateLogger<SafeTimer>(); var minTicks = Math.Min(this.clientMessagingOptions.ResponseTimeout.Ticks, TimeSpan.FromSeconds(1).Ticks); var period = TimeSpan.FromTicks(minTicks); this.callbackTimer = new SafeTimer(timerLogger, this.OnCallbackExpiryTick, null, period, period); this.GrainReferenceRuntime = this.ServiceProvider.GetRequiredService<IGrainReferenceRuntime>(); this.localAddress = this.clientMessagingOptions.LocalAddress ?? ConfigUtilities.GetLocalIPAddress(this.clientMessagingOptions.PreferredFamily, this.clientMessagingOptions.NetworkInterfaceName); // Client init / sign-on message logger.LogInformation((int)ErrorCode.ClientStarting, "Starting Orleans client with runtime version \"{RuntimeVersion}\", local address {LocalAddress} and client id {ClientId}", RuntimeVersion.Current, localAddress, clientId); if (TestOnlyThrowExceptionDuringInit) { throw new InvalidOperationException("TestOnlyThrowExceptionDuringInit"); } var statisticsLevel = statisticsOptions.Value.CollectionLevel; if (statisticsLevel.CollectThreadTimeTrackingStats()) { incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver", this.loggerFactory, this.statisticsOptions, this.schedulerStageStatistics); } } catch (Exception exc) { if (logger != null) logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc); ConstructorReset(); throw; } } public IServiceProvider ServiceProvider { get; private set; } public async Task Start(CancellationToken cancellationToken) { ConsumeServices(); // Deliberately avoid capturing the current synchronization context during startup and execute on the default scheduler. // This helps to avoid any issues (such as deadlocks) caused by executing with the client's synchronization context/scheduler. await Task.Run(() => this.StartInternal(cancellationToken)).ConfigureAwait(false); logger.LogInformation((int)ErrorCode.ProxyClient_StartDone, "Started client with address {ActivationAddress} and id {ClientId}", CurrentActivationAddress.ToString(), clientId); } // used for testing to (carefully!) allow two clients in the same process private async Task StartInternal(CancellationToken cancellationToken) { var retryFilter = ServiceProvider.GetService<IClientConnectionRetryFilter>(); var gatewayManager = this.ServiceProvider.GetRequiredService<GatewayManager>(); await ExecuteWithRetries( async () => await gatewayManager.StartAsync(cancellationToken), retryFilter, cancellationToken); var generation = -SiloAddress.AllocateNewGeneration(); // Client generations are negative MessageCenter = ActivatorUtilities.CreateInstance<ClientMessageCenter>(this.ServiceProvider, localAddress, generation, clientId); MessageCenter.RegisterLocalMessageHandler(this.HandleMessage); await ExecuteWithRetries( async () => await MessageCenter.StartAsync(cancellationToken), retryFilter, cancellationToken); CurrentActivationAddress = GrainAddress.NewActivationAddress(MessageCenter.MyAddress, clientId.GrainId); this.gatewayObserver = new ClientGatewayObserver(gatewayManager); this.InternalGrainFactory.CreateObjectReference<IClientGatewayObserver>(this.gatewayObserver); await ExecuteWithRetries( async () => await this.ServiceProvider.GetRequiredService<ClientClusterManifestProvider>().StartAsync(), retryFilter, cancellationToken); ClientStatistics.Start(MessageCenter, clientId.GrainId); static async Task ExecuteWithRetries(Func<Task> task, IClientConnectionRetryFilter retryFilter, CancellationToken cancellationToken) { do { try { await task(); return; } catch (Exception exception) when (retryFilter is not null && !cancellationToken.IsCancellationRequested) { var shouldRetry = await retryFilter.ShouldRetryConnectionAttempt(exception, cancellationToken); if (cancellationToken.IsCancellationRequested || !shouldRetry) { throw; } } } while (!cancellationToken.IsCancellationRequested); } } private void HandleMessage(Message message) { switch (message.Direction) { case Message.Directions.Response: { ReceiveResponse(message); break; } case Message.Directions.OneWay: case Message.Directions.Request: { this.localObjects.Dispatch(message); break; } default: logger.Error(ErrorCode.Runtime_Error_100327, $"Message not supported: {message}."); break; } } public void SendResponse(Message request, Response response) { ThrowIfDisposed(); var message = this.messageFactory.CreateResponseMessage(request); OrleansOutsideRuntimeClientEvent.Log.SendResponse(message); message.BodyObject = response; MessageCenter.SendMessage(message); } public void SendRequest(GrainReference target, IInvokable request, IResponseCompletionSource context, InvokeMethodOptions options) { ThrowIfDisposed(); var message = this.messageFactory.CreateMessage(request, options); OrleansOutsideRuntimeClientEvent.Log.SendRequest(message); SendRequestMessage(target, message, context, options); } private void SendRequestMessage(GrainReference target, Message message, IResponseCompletionSource context, InvokeMethodOptions options) { message.InterfaceType = target.InterfaceType; message.InterfaceVersion = target.InterfaceVersion; var targetGrainId = target.GrainId; var oneWay = (options & InvokeMethodOptions.OneWay) != 0; message.SendingGrain = CurrentActivationAddress.GrainId; message.SendingActivation = CurrentActivationAddress.ActivationId; message.TargetGrain = targetGrainId; if (SystemTargetGrainId.TryParse(targetGrainId, out var systemTargetGrainId)) { // If the silo isn't be supplied, it will be filled in by the sender to be the gateway silo message.TargetSilo = systemTargetGrainId.GetSiloAddress(); message.TargetActivation = ActivationId.GetDeterministic(targetGrainId); } if (message.IsExpirableMessage(this.clientMessagingOptions.DropExpiredMessages)) { // don't set expiration for system target messages. message.TimeToLive = this.clientMessagingOptions.ResponseTimeout; } if (!oneWay) { var callbackData = new CallbackData(this.sharedCallbackData, context, message); callbacks.TryAdd(message.Id, callbackData); } else { context?.Complete(); } if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Send {0}", message); MessageCenter.SendMessage(message); } public void ReceiveResponse(Message response) { OrleansOutsideRuntimeClientEvent.Log.ReceiveResponse(response); if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Received {0}", response); // ignore duplicate requests if (response.Result == Message.ResponseTypes.Rejection && (response.RejectionType == Message.RejectionTypes.DuplicateRequest || response.RejectionType == Message.RejectionTypes.CacheInvalidation)) { return; } else if (response.Result == Message.ResponseTypes.Status) { var status = (StatusResponse)response.BodyObject; callbacks.TryGetValue(response.Id, out var callback); var request = callback?.Message; if (!(request is null)) { callback.OnStatusUpdate(status); if (status.Diagnostics != null && status.Diagnostics.Count > 0 && logger.IsEnabled(LogLevel.Information)) { var diagnosticsString = string.Join("\n", status.Diagnostics); this.logger.LogInformation("Received status update for pending request, Request: {RequestMessage}. Status: {Diagnostics}", request, diagnosticsString); } } else { if (status.Diagnostics != null && status.Diagnostics.Count > 0 && logger.IsEnabled(LogLevel.Information)) { var diagnosticsString = string.Join("\n", status.Diagnostics); this.logger.LogInformation("Received status update for unknown request. Message: {StatusMessage}. Status: {Diagnostics}", response, diagnosticsString); } } return; } CallbackData callbackData; var found = callbacks.TryRemove(response.Id, out callbackData); if (found) { // We need to import the RequestContext here as well. // Unfortunately, it is not enough, since CallContext.LogicalGetData will not flow "up" from task completion source into the resolved task. // RequestContextExtensions.Import(response.RequestContextData); callbackData.DoCallback(response); } else { logger.Warn(ErrorCode.Runtime_Error_100011, "No callback for response message: " + response); } } private void UnregisterCallback(CorrelationId id) { callbacks.TryRemove(id, out _); } public void Reset() { Utils.SafeExecute(() => { if (logger != null) { logger.Info("OutsideRuntimeClient.Reset(): client Id " + clientId); } }, this.logger); Utils.SafeExecute(() => { incomingMessagesThreadTimeTracking?.OnStopExecution(); }, logger, "Client.incomingMessagesThreadTimeTracking.OnStopExecution"); Utils.SafeExecute(() => { if (MessageCenter != null) { MessageCenter.Stop(); } }, logger, "Client.Stop-Transport"); Utils.SafeExecute(() => { if (ClientStatistics != null) { ClientStatistics.Stop(); } }, logger, "Client.Stop-ClientStatistics"); ConstructorReset(); } private void ConstructorReset() { Utils.SafeExecute(() => { if (logger != null) { logger.Info("OutsideRuntimeClient.ConstructorReset(): client Id " + clientId); } }); Utils.SafeExecute(() => this.Dispose()); } /// <inheritdoc /> public TimeSpan GetResponseTimeout() => this.sharedCallbackData.ResponseTimeout; /// <inheritdoc /> public void SetResponseTimeout(TimeSpan timeout) => this.sharedCallbackData.ResponseTimeout = timeout; public IAddressable CreateObjectReference(IAddressable obj) { if (obj is GrainReference) throw new ArgumentException("Argument obj is already a grain reference.", nameof(obj)); if (obj is IGrainBase) throw new ArgumentException("Argument must not be a grain class.", nameof(obj)); var observerId = obj is ClientObserver clientObserver ? clientObserver.GetObserverGrainId(this.clientId) : ObserverGrainId.Create(this.clientId); var reference = this.InternalGrainFactory.GetGrain(observerId.GrainId); if (!localObjects.TryRegister(obj, observerId)) { throw new ArgumentException($"Failed to add new observer {reference} to localObjects collection.", "reference"); } return reference; } public void DeleteObjectReference(IAddressable obj) { if (!(obj is GrainReference reference)) { throw new ArgumentException("Argument reference is not a grain reference."); } if (!ObserverGrainId.TryParse(reference.GrainId, out var observerId)) { throw new ArgumentException($"Reference {reference.GrainId} is not an observer reference"); } if (!localObjects.TryDeregister(observerId)) { throw new ArgumentException("Reference is not associated with a local object.", "reference"); } } private string PrintAppDomainDetails() { return string.Format("<AppDomain.Id={0}, AppDomain.FriendlyName={1}>", AppDomain.CurrentDomain.Id, AppDomain.CurrentDomain.FriendlyName); } public void Dispose() { if (this.disposing) return; this.disposing = true; Utils.SafeExecute(() => this.callbackTimer?.Dispose()); Utils.SafeExecute(() => MessageCenter?.Dispose()); this.ClusterConnectionLost = null; this.GatewayCountChanged = null; GC.SuppressFinalize(this); disposed = true; } public void BreakOutstandingMessagesToDeadSilo(SiloAddress deadSilo) { foreach (var callback in callbacks) { if (deadSilo.Equals(callback.Value.Message.TargetSilo)) { callback.Value.OnTargetSiloFail(); } } } /// <inheritdoc /> public event ConnectionToClusterLostHandler ClusterConnectionLost; /// <inheritdoc /> public event GatewayCountChangedHandler GatewayCountChanged; /// <inheritdoc /> public void NotifyClusterConnectionLost() { try { this.ClusterConnectionLost?.Invoke(this, EventArgs.Empty); } catch (Exception ex) { this.logger.Error(ErrorCode.ClientError, "Error when sending cluster disconnection notification", ex); } } /// <inheritdoc /> public void NotifyGatewayCountChanged(int currentNumberOfGateways, int previousNumberOfGateways) { try { this.GatewayCountChanged?.Invoke(this, new GatewayCountChangedEventArgs(currentNumberOfGateways, previousNumberOfGateways)); } catch (Exception ex) { this.logger.Error(ErrorCode.ClientError, "Error when sending gateway count changed notification", ex); } } private void OnCallbackExpiryTick(object state) { var currentStopwatchTicks = Stopwatch.GetTimestamp(); foreach (var pair in callbacks) { var callback = pair.Value; if (callback.IsCompleted) continue; if (callback.IsExpired(currentStopwatchTicks)) callback.OnTimeout(this.clientMessagingOptions.ResponseTimeout); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ThrowIfDisposed() { if (disposed) { ThrowObjectDisposedException(); } [MethodImpl(MethodImplOptions.NoInlining)] void ThrowObjectDisposedException() => throw new ObjectDisposedException(nameof(OutsideRuntimeClient)); } } }
42.214552
241
0.607681
[ "MIT" ]
DerHulk/orleans
src/Orleans.Core/Runtime/OutsideRuntimeClient.cs
22,627
C#
// Copyright 2020 Energinet DataHub A/S // // Licensed under the Apache License, Version 2.0 (the "License2"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using Energinet.DataHub.Core.Messaging.MessageTypes.Common; using GreenEnergyHub.Charges.Domain.Charges; using GreenEnergyHub.Charges.Domain.Dtos.Messages; using NodaTime; namespace GreenEnergyHub.Charges.Application.Charges.Acknowledgement { public class ChargePricesUpdatedEvent : IMessage { public ChargePricesUpdatedEvent( string chargeId, ChargeType chargeType, string chargeOwner, Instant updatePeriodStartDate, Instant updatePeriodEndDate, List<Point> points) { ChargeId = chargeId; ChargeType = chargeType; ChargeOwner = chargeOwner; UpdatePeriodStartDate = updatePeriodStartDate; UpdatePeriodEndDate = updatePeriodEndDate; Points = points; Transaction = Transaction.NewTransaction(); } public string ChargeId { get; } public ChargeType ChargeType { get; } public string ChargeOwner { get; } public Instant UpdatePeriodStartDate { get; } public Instant UpdatePeriodEndDate { get; } public List<Point> Points { get; } public Transaction Transaction { get; set; } } }
32.719298
75
0.683646
[ "Apache-2.0" ]
Energinet-DataHub/geh-charges
source/GreenEnergyHub.Charges/source/GreenEnergyHub.Charges.Application/Charges/Acknowledgement/ChargePricesUpdatedEvent.cs
1,867
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable namespace Azure.ResourceManager.Network.Models { /// <summary> The routes table associated with the ExpressRouteCircuit. </summary> public partial class ExpressRouteCircuitRoutesTableSummary { /// <summary> Initializes a new instance of ExpressRouteCircuitRoutesTableSummary. </summary> internal ExpressRouteCircuitRoutesTableSummary() { } /// <summary> Initializes a new instance of ExpressRouteCircuitRoutesTableSummary. </summary> /// <param name="neighbor"> IP address of the neighbor. </param> /// <param name="v"> BGP version number spoken to the neighbor. </param> /// <param name="as"> Autonomous system number. </param> /// <param name="upDown"> The length of time that the BGP session has been in the Established state, or the current status if not in the Established state. </param> /// <param name="statePfxRcd"> Current state of the BGP session, and the number of prefixes that have been received from a neighbor or peer group. </param> internal ExpressRouteCircuitRoutesTableSummary(string neighbor, int? v, int? @as, string upDown, string statePfxRcd) { Neighbor = neighbor; V = v; As = @as; UpDown = upDown; StatePfxRcd = statePfxRcd; } /// <summary> IP address of the neighbor. </summary> public string Neighbor { get; } /// <summary> BGP version number spoken to the neighbor. </summary> public int? V { get; } /// <summary> Autonomous system number. </summary> public int? As { get; } /// <summary> The length of time that the BGP session has been in the Established state, or the current status if not in the Established state. </summary> public string UpDown { get; } /// <summary> Current state of the BGP session, and the number of prefixes that have been received from a neighbor or peer group. </summary> public string StatePfxRcd { get; } } }
48.2
172
0.658829
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/Models/ExpressRouteCircuitRoutesTableSummary.cs
2,169
C#
using System; using _Game.GameResources; using _Game.InventorySystem; using _Game.ShopSystem; using _Game.Towers; using _Game.UI.Utils; using MEC; using UnityEngine; using UnityEngine.SceneManagement; namespace _Game { //TODO: Improve this mess //Sorry future self for making this. I was in a hurry :c //At least is not that much. public class Global : MonoBehaviour { public static Global Instance { get; private set; } [Header("Main References")] [SerializeField] private Shop shop = default; [SerializeField] private Inventory inventory = default; [SerializeField] private Dropper dropper = default; [SerializeField] private FaderUI gameOverScreen = default; public static Shop Shop => Instance.shop; public static Inventory Inventory => Instance.inventory; public static Dropper Dropper => Instance.dropper; public static int Difficult => Instance.isGameOver ? 1 : Instance.mainTower.UpgradeLevel + 1; //TODO: Clean this //TODO: Separate Resource into ResourceSettings [SerializeField] private Resource energyResource = default; [SerializeField] private Resource metalResource = default; [SerializeField] private Resource knowledgeResource = default; [SerializeField] private Resource contaminationResource = default; public static Resource Energy => Instance.energyResource; public static Resource Metal => Instance.metalResource; public static Resource Knowledge => Instance.knowledgeResource; public static Resource Contamination => Instance.contaminationResource; public static bool IsSpecialTowersUnlocked { get; private set; } private BaseTower mainTower; public static BaseTower MainTower { get { if (Instance.mainTower == null) Instance.mainTower = FindObjectOfType<BaseTower>(); return Instance.mainTower; } } private void Awake() { Instance = this; IsSpecialTowersUnlocked = false; } public void UnlockSpecialTowers() => IsSpecialTowersUnlocked = true; public void Exit() => Application.Quit(); //TODO: Make a better Pause System private bool isPaused; public void TogglePause() { if(isPaused) UnPause(); else Pause(); } public void Pause() { isPaused = true; Time.timeScale = 0f; } public void UnPause() { isPaused = false; Time.timeScale = 1f; } //TODO: Improve private bool isGameOver; public static bool IsGameOver => Instance.isGameOver; public void GameOver() { isGameOver = true; gameOverScreen.gameObject.SetActive(true); gameOverScreen.Show(); Timing.KillCoroutines(); } public void Restart() { UnPause(); SceneManager.LoadScene(0); } } }
30.688073
122
0.578475
[ "MIT" ]
MarcoElz/ggj22
Assets/_Game/Scripts/Global.cs
3,347
C#
using System; using System.Collections.Generic; using ProductionCode.Orders.Models; using System.Linq; namespace NUnit.FullFramework.Orders.Builders { class OrderBuilder { private decimal? _amount = null; private int? _id = null; private DateTime? _bookedDate = new DateTime(2019, 02, 13); private List<Adjustment> _adjustments = new List<Adjustment>(); private List<Refund> _refunds = new List<Refund>(); private bool _deleted = false; private string _currencyCode = null; public OrderBuilder WithBookedDate(DateTime? bookedDate) { _bookedDate = bookedDate; return this; } public OrderBuilder WithOrderId(int id) { _id = id; return this; } public OrderBuilder WithAmount(decimal amount) { _amount = amount; return this; } public OrderBuilder WithCredit(decimal creditAmount) { _adjustments.Add(new Adjustment() { Amount = creditAmount * -1 }); return this; } public OrderBuilder WithDebit(decimal debitAmount) { _adjustments.Add(new Adjustment() { Amount = debitAmount }); return this; } public OrderBuilder WithRefund(decimal refundAmount) { _refunds.Add(new Refund() { Amount = refundAmount }); return this; } public OrderBuilder AsDeleted() { _deleted = true; return this; } public OrderBuilder WithCurrency(string currencyCode) { _currencyCode = currencyCode; return this; } public Order Build() { if (!_amount.HasValue) { _amount = 1000; } if (!_id.HasValue) { _id = new Random(DateTime.UtcNow.Millisecond).Next(); } var order = new Order() { OrderId = _id.Value, Amount = _amount.Value, Subtotal = _amount.Value, BookedDate = _bookedDate, IsDeleted = _deleted, CurrencyIsoCode = _currencyCode ?? "USD" }; order.Adjustments.AddRange(_adjustments); order.Refunds.AddRange(_refunds); return order; } } }
24.558824
78
0.522555
[ "MIT" ]
elizabethcrich/UnitTestingBootcamp
NUnit.FullFramework/Orders (Exercises)/Builders/OrderBuilder.cs
2,507
C#
using System; namespace SampleApp.Models { public class FormModel : BaseModel { private DateTime _birthDate = DateTime.Today; private string _city = string.Empty; private string _email = string.Empty; private string _emailConfirm = string.Empty; private bool _english; private string _firstname = string.Empty; private string _gender = string.Empty; private string _lastname = string.Empty; private string _password = string.Empty; private int _rateEnglish; private int _rateRussian; private int _rateSpanish; private bool _russian; private bool _spanish; private string _zipCode = string.Empty; public string Firstname { get => _firstname; set => SetProperty(ref _firstname, value); } public string Lastname { get => _lastname; set => SetProperty(ref _lastname, value); } public string Gender { get => _gender; set => SetProperty(ref _gender, value); } public string Email { get => _email; set => SetProperty(ref _email, value); } public string EmailConfirm { get => _emailConfirm; set => SetProperty(ref _emailConfirm, value); } public string Password { get => _password; set => SetProperty(ref _password, value); } public string ZipCode { get => _zipCode; set => SetProperty(ref _zipCode, value); } public string City { get => _city; set => SetProperty(ref _city, value); } public DateTime BirthDate { get => _birthDate; set => SetProperty(ref _birthDate, value); } public bool English { get => _english; set => SetProperty(ref _english, value); } public bool Spanish { get => _spanish; set => SetProperty(ref _spanish, value); } public bool Russian { get => _russian; set => SetProperty(ref _russian, value); } public int RateEnglish { get => _rateEnglish; set => SetProperty(ref _rateEnglish, value); } public int RateSpanish { get => _rateSpanish; set => SetProperty(ref _rateSpanish, value); } public int RateRussian { get => _rateRussian; set => SetProperty(ref _rateRussian, value); } } }
24.27193
57
0.513914
[ "MIT" ]
Bhekinkosi12/Global.InputForms
Sample/SampleApp/Models/FormModel.cs
2,769
C#
namespace BYteWare.XAF.ElasticSearch.Win.Template { partial class OutlookStyleMainRibbonDynamicActionContainer { /// <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)) { actionContainersManager.Dispose(); 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(); System.ComponentModel.ComponentResourceManager resources = new DevExpress.ExpressApp.Win.Templates.XafComponentResourceManager(typeof(OutlookStyleMainRibbonDynamicActionContainer)); DevExpress.Utils.Animation.Transition transition = new DevExpress.Utils.Animation.Transition(); DevExpress.Utils.Animation.SlideFadeTransition slideFadeTransition = new DevExpress.Utils.Animation.SlideFadeTransition(); this.mainContainer = new DevExpress.XtraEditors.XtraUserControl(); this.viewSitePanel = new DevExpress.XtraEditors.PanelControl(); this.separatorControl = new DevExpress.XtraEditors.SeparatorControl(); this.navBarControl = new DevExpress.ExpressApp.Win.Templates.Navigation.XafNavBarControl(); this.navBarSingleChoiceActionControl = new DevExpress.ExpressApp.Win.Templates.Navigation.NavBarSingleChoiceActionControl(); this.ribbonControl = new DevExpress.ExpressApp.Win.Templates.Ribbon.XafRibbonControlV2(); this.barActionContainerViewsHistoryNavigation = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerViewsHistoryNavigation = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerObjectsCreation = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerObjectsCreation = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerFile = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerFile = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerSave = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerSave = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerPrint = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerPrint = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerEdit = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerEdit = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerUndoRedo = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerUndoRedo = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerOpenObject = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerOpenObject = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerExport = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerExport = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerRecordEdit = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerRecordEdit = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerWorkflow = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerWorkflow = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerView = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerView = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerReports = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerReports = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerDefault = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerDefault = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerPanels = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerPanels = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerRecordsNavigation = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerRecordsNavigation = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerFilters = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerFilters = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerSearch = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerSearch = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerFullTextSearch = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerFullTextSearch = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerViewsNavigation = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerViewsNavigation = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerWindows = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerWindows = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerTools = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerTools = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerOptions = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerOptions = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerDiagnostic = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerDiagnostic = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerExit = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerExit = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerAbout = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerAbout = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerMenu = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerMenu = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barActionContainerNotifications = new DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer(); this.barContainerNotifications = new DevExpress.XtraBars.BarLinkContainerExItem(); this.ribbonChooseSkinActionControl = new DevExpress.ExpressApp.Win.Templates.Ribbon.ActionControls.RibbonChooseSkinActionControl(); this.ribbonGallerySkins = new DevExpress.XtraBars.RibbonGalleryBarItem(); this.applicationMenu = new DevExpress.XtraBars.Ribbon.ApplicationMenu(this.components); this.mainBarAndDockingController = new DevExpress.XtraBars.BarAndDockingController(this.components); this.barSubItemPanels = new DevExpress.XtraBars.BarSubItem(); this.barContainerStatusMessages = new DevExpress.XtraBars.BarLinkContainerExItem(); this.barCheckItemNormal = new DevExpress.XtraBars.BarCheckItem(); this.barCheckItemReading = new DevExpress.XtraBars.BarCheckItem(); this.barSubItemNavigationPane = new DevExpress.XtraBars.BarSubItem(); this.defaultPage = new DevExpress.XtraBars.Ribbon.RibbonPage(); this.ribbonGroupViewsHistoryNavigation = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.ribbonGroupObjectsCreation = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.ribbonGroupSave = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.ribbonGroupEdit = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.ribbonGroupRecordEdit = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.ribbonGroupOpenObject = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.ribbonGroupWorkflow = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.ribbonGroupView = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.ribbonGroupDefault = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.ribbonGroupRecordsNavigation = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.ribbonGroupFilters = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.ribbonGroupSearch = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.ribbonGroupFullTextSearch = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.viewPage = new DevExpress.XtraBars.Ribbon.RibbonPage(); this.ribbonGroupViewsNavigation = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.ribbonGroupAppearance = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.ribbonGroupWindows = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.defaultPageGroup = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.toolsPage = new DevExpress.XtraBars.Ribbon.RibbonPage(); this.ribbonGroupTools = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.ribbonGroupOptions = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.ribbonGroupDiagnostic = new DevExpress.XtraBars.Ribbon.RibbonPageGroup(); this.windowPage = new DevExpress.XtraBars.Ribbon.RibbonPage(); this.ribbonStatusBar = new DevExpress.XtraBars.Ribbon.RibbonStatusBar(); this.officeNavigationBar = new DevExpress.XtraBars.Navigation.OfficeNavigationBar(); this.dockManager = new DevExpress.XtraBars.Docking.DockManager(this.components); this.documentManager = new DevExpress.XtraBars.Docking2010.DocumentManager(this.components); this.noDocumentsView = new DevExpress.XtraBars.Docking2010.Views.NoDocuments.NoDocumentsView(this.components); this.viewSiteManager = new DevExpress.ExpressApp.Win.Templates.ViewSiteManager(this.components); this.transitionManager = new DevExpress.Utils.Animation.TransitionManager(); this.modelSynchronizationManager = new DevExpress.ExpressApp.Win.Templates.ModelSynchronizationManager(this.components); this.formStateModelSynchronizer = new DevExpress.ExpressApp.Win.Core.FormStateModelSynchronizer(this.components); this.navBarControlModelSynchronizer = new DevExpress.ExpressApp.Win.Templates.Navigation.NavBarControlModelSynchronizer(this.components); this.officeNavigationBarCustomizationModelSynchronizer = new DevExpress.ExpressApp.Win.Templates.Navigation.OfficeNavigationBarCustomizationModelSynchronizer(this.components); this.contextMenu = new DevExpress.XtraBars.PopupMenu(this.components); this.actionContainersManager = new DevExpress.ExpressApp.Win.Templates.ActionContainersManager(this.components); this.mainContainer.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.viewSitePanel)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.separatorControl)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.navBarControl)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.navBarSingleChoiceActionControl)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.ribbonControl)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerViewsHistoryNavigation)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerObjectsCreation)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerFile)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerSave)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerPrint)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerEdit)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerUndoRedo)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerOpenObject)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerExport)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerRecordEdit)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerWorkflow)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerReports)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerDefault)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerPanels)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerRecordsNavigation)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerFilters)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerSearch)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerFullTextSearch)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerViewsNavigation)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerWindows)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerTools)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerOptions)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerDiagnostic)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerExit)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerAbout)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerMenu)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerNotifications)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.ribbonChooseSkinActionControl)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.applicationMenu)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.mainBarAndDockingController)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.officeNavigationBar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dockManager)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.documentManager)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.noDocumentsView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.contextMenu)).BeginInit(); this.SuspendLayout(); // // mainContainer // this.mainContainer.Controls.Add(this.viewSitePanel); this.mainContainer.Controls.Add(this.separatorControl); this.mainContainer.Controls.Add(this.navBarControl); resources.ApplyResources(this.mainContainer, "mainContainer"); this.mainContainer.Name = "mainContainer"; // // viewSitePanel // this.viewSitePanel.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder; resources.ApplyResources(this.viewSitePanel, "viewSitePanel"); this.viewSitePanel.Name = "viewSitePanel"; // // separatorControl // resources.ApplyResources(this.separatorControl, "separatorControl"); this.separatorControl.LineAlignment = DevExpress.XtraEditors.Alignment.Center; this.separatorControl.LineOrientation = System.Windows.Forms.Orientation.Vertical; this.separatorControl.LineThickness = 1; this.separatorControl.Name = "separatorControl"; // // navBarControl // this.navBarControl.ActionControl = this.navBarSingleChoiceActionControl; this.navBarControl.ActiveGroup = null; this.navBarControl.AllowHorizontalResizing = DevExpress.Utils.DefaultBoolean.True; this.navBarControl.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder; resources.ApplyResources(this.navBarControl, "navBarControl"); this.navBarControl.DragDropFlags = DevExpress.XtraNavBar.NavBarDragDrop.None; this.navBarControl.LinkSelectionMode = DevExpress.XtraNavBar.LinkSelectionModeType.OneInGroupAndAllowAutoSelect; this.navBarControl.MenuManager = this.ribbonControl.Manager; this.navBarControl.Name = "navBarControl"; this.navBarControl.OptionsNavPane.ExpandedWidth = ((int)(resources.GetObject("resource.ExpandedWidth"))); this.navBarControl.PaintStyleKind = DevExpress.XtraNavBar.NavBarViewKind.NavigationPane; this.navBarControl.StoreDefaultPaintStyleName = true; // // navBarSingleChoiceActionControl // this.navBarSingleChoiceActionControl.ActionId = "ShowNavigationItem"; this.navBarSingleChoiceActionControl.NavigationControl = this.navBarControl; // // ribbonControl // this.ribbonControl.ActionContainers.Add(this.barActionContainerViewsHistoryNavigation); this.ribbonControl.ActionContainers.Add(this.barActionContainerObjectsCreation); this.ribbonControl.ActionContainers.Add(this.barActionContainerFile); this.ribbonControl.ActionContainers.Add(this.barActionContainerSave); this.ribbonControl.ActionContainers.Add(this.barActionContainerPrint); this.ribbonControl.ActionContainers.Add(this.barActionContainerEdit); this.ribbonControl.ActionContainers.Add(this.barActionContainerUndoRedo); this.ribbonControl.ActionContainers.Add(this.barActionContainerOpenObject); this.ribbonControl.ActionContainers.Add(this.barActionContainerExport); this.ribbonControl.ActionContainers.Add(this.barActionContainerRecordEdit); this.ribbonControl.ActionContainers.Add(this.barActionContainerWorkflow); this.ribbonControl.ActionContainers.Add(this.barActionContainerView); this.ribbonControl.ActionContainers.Add(this.barActionContainerReports); this.ribbonControl.ActionContainers.Add(this.barActionContainerDefault); this.ribbonControl.ActionContainers.Add(this.barActionContainerPanels); this.ribbonControl.ActionContainers.Add(this.barActionContainerRecordsNavigation); this.ribbonControl.ActionContainers.Add(this.barActionContainerFilters); this.ribbonControl.ActionContainers.Add(this.barActionContainerSearch); this.ribbonControl.ActionContainers.Add(this.barActionContainerFullTextSearch); this.ribbonControl.ActionContainers.Add(this.barActionContainerViewsNavigation); this.ribbonControl.ActionContainers.Add(this.barActionContainerWindows); this.ribbonControl.ActionContainers.Add(this.barActionContainerTools); this.ribbonControl.ActionContainers.Add(this.barActionContainerOptions); this.ribbonControl.ActionContainers.Add(this.barActionContainerDiagnostic); this.ribbonControl.ActionContainers.Add(this.barActionContainerExit); this.ribbonControl.ActionContainers.Add(this.barActionContainerAbout); this.ribbonControl.ActionContainers.Add(this.barActionContainerMenu); this.ribbonControl.ActionContainers.Add(this.barActionContainerNotifications); this.ribbonControl.ActionControls.Add(this.ribbonChooseSkinActionControl); this.ribbonControl.ApplicationButtonDropDownControl = this.applicationMenu; this.ribbonControl.AutoHideEmptyItems = true; this.ribbonControl.Controller = this.mainBarAndDockingController; this.ribbonControl.ExpandCollapseItem.Id = 0; this.ribbonControl.Items.AddRange(new DevExpress.XtraBars.BarItem[] { this.ribbonControl.ExpandCollapseItem, this.barSubItemPanels, this.barContainerViewsHistoryNavigation, this.barContainerEdit, this.barContainerUndoRedo, this.barContainerView, this.barContainerReports, this.barContainerObjectsCreation, this.barContainerFile, this.barContainerSave, this.barContainerPrint, this.barContainerOpenObject, this.barContainerRecordEdit, this.barContainerWorkflow, this.barContainerExport, this.barContainerDefault, this.barContainerPanels, this.barContainerRecordsNavigation, this.barContainerFilters, this.barContainerSearch, this.barContainerFullTextSearch, this.barContainerViewsNavigation, this.barContainerWindows, this.barContainerTools, this.barContainerOptions, this.barContainerDiagnostic, this.barContainerExit, this.barContainerAbout, this.barContainerMenu, this.barContainerNotifications, this.barContainerStatusMessages, this.ribbonGallerySkins, this.barCheckItemNormal, this.barCheckItemReading, this.barSubItemNavigationPane}); resources.ApplyResources(this.ribbonControl, "ribbonControl"); this.ribbonControl.MaxItemId = 19; this.ribbonControl.MdiMergeStyle = DevExpress.XtraBars.Ribbon.RibbonMdiMergeStyle.Never; this.ribbonControl.Name = "ribbonControl"; this.ribbonControl.Pages.AddRange(new DevExpress.XtraBars.Ribbon.RibbonPage[] { this.defaultPage, this.viewPage, this.toolsPage, this.windowPage}); this.ribbonControl.StatusBar = this.ribbonStatusBar; // // barActionContainerViewsHistoryNavigation // this.barActionContainerViewsHistoryNavigation.ActionCategory = "ViewsHistoryNavigation"; this.barActionContainerViewsHistoryNavigation.BarContainerItem = this.barContainerViewsHistoryNavigation; this.barActionContainerViewsHistoryNavigation.IsMenuMode = true; // // barContainerViewsHistoryNavigation // resources.ApplyResources(this.barContainerViewsHistoryNavigation, "barContainerViewsHistoryNavigation"); this.barContainerViewsHistoryNavigation.Id = 35; this.barContainerViewsHistoryNavigation.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerViewsHistoryNavigation.Name = "barContainerViewsHistoryNavigation"; // // barActionContainerObjectsCreation // this.barActionContainerObjectsCreation.ActionCategory = "ObjectsCreation"; this.barActionContainerObjectsCreation.BarContainerItem = this.barContainerObjectsCreation; // // barContainerObjectsCreation // resources.ApplyResources(this.barContainerObjectsCreation, "barContainerObjectsCreation"); this.barContainerObjectsCreation.Id = 18; this.barContainerObjectsCreation.MergeOrder = 1; this.barContainerObjectsCreation.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerObjectsCreation.Name = "barContainerObjectsCreation"; // // barActionContainerFile // this.barActionContainerFile.ActionCategory = "File"; this.barActionContainerFile.BarContainerItem = this.barContainerFile; // // barContainerFile // resources.ApplyResources(this.barContainerFile, "barContainerFile"); this.barContainerFile.Id = 5; this.barContainerFile.MergeOrder = 2; this.barContainerFile.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerFile.Name = "barContainerFile"; // // barActionContainerSave // this.barActionContainerSave.ActionCategory = "Save"; this.barActionContainerSave.BarContainerItem = this.barContainerSave; // // barContainerSave // resources.ApplyResources(this.barContainerSave, "barContainerSave"); this.barContainerSave.Id = 8; this.barContainerSave.MergeOrder = 7; this.barContainerSave.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerSave.Name = "barContainerSave"; // // barActionContainerPrint // this.barActionContainerPrint.ActionCategory = "Print"; this.barActionContainerPrint.BarContainerItem = this.barContainerPrint; // // barContainerPrint // resources.ApplyResources(this.barContainerPrint, "barContainerPrint"); this.barContainerPrint.Id = 6; this.barContainerPrint.MergeOrder = 11; this.barContainerPrint.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerPrint.Name = "barContainerPrint"; // // barActionContainerEdit // this.barActionContainerEdit.ActionCategory = "Edit"; this.barActionContainerEdit.BarContainerItem = this.barContainerEdit; // // barContainerEdit // resources.ApplyResources(this.barContainerEdit, "barContainerEdit"); this.barContainerEdit.Id = 9; this.barContainerEdit.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerEdit.Name = "barContainerEdit"; // // barActionContainerUndoRedo // this.barActionContainerUndoRedo.ActionCategory = "UndoRedo"; this.barActionContainerUndoRedo.BarContainerItem = this.barContainerUndoRedo; // // barContainerUndoRedo // resources.ApplyResources(this.barContainerUndoRedo, "barContainerUndoRedo"); this.barContainerUndoRedo.Id = 10; this.barContainerUndoRedo.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerUndoRedo.Name = "barContainerUndoRedo"; // // barActionContainerOpenObject // this.barActionContainerOpenObject.ActionCategory = "OpenObject"; this.barActionContainerOpenObject.BarContainerItem = this.barContainerOpenObject; // // barContainerOpenObject // resources.ApplyResources(this.barContainerOpenObject, "barContainerOpenObject"); this.barContainerOpenObject.Id = 9; this.barContainerOpenObject.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerOpenObject.Name = "barContainerOpenObject"; // // barActionContainerExport // this.barActionContainerExport.ActionCategory = "Export"; this.barActionContainerExport.BarContainerItem = this.barContainerExport; // // barContainerExport // resources.ApplyResources(this.barContainerExport, "barContainerExport"); this.barContainerExport.Id = 7; this.barContainerExport.MergeOrder = 10; this.barContainerExport.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerExport.Name = "barContainerExport"; // // barActionContainerRecordEdit // this.barActionContainerRecordEdit.ActionCategory = "RecordEdit"; this.barActionContainerRecordEdit.BarContainerItem = this.barContainerRecordEdit; // // barContainerRecordEdit // resources.ApplyResources(this.barContainerRecordEdit, "barContainerRecordEdit"); this.barContainerRecordEdit.Id = 9; this.barContainerRecordEdit.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerRecordEdit.Name = "barContainerRecordEdit"; // // barActionContainerWorkflow // this.barActionContainerWorkflow.ActionCategory = "Workflow"; this.barActionContainerWorkflow.BarContainerItem = this.barContainerWorkflow; // // barContainerWorkflow // resources.ApplyResources(this.barContainerWorkflow, "barContainerWorkflow"); this.barContainerWorkflow.Id = 9; this.barContainerWorkflow.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerWorkflow.Name = "barContainerWorkflow"; // // barActionContainerView // this.barActionContainerView.ActionCategory = "View"; this.barActionContainerView.BarContainerItem = this.barContainerView; // // barContainerView // resources.ApplyResources(this.barContainerView, "barContainerView"); this.barContainerView.Id = 12; this.barContainerView.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerView.Name = "barContainerView"; // // barActionContainerReports // this.barActionContainerReports.ActionCategory = "Reports"; this.barActionContainerReports.BarContainerItem = this.barContainerReports; // // barContainerReports // resources.ApplyResources(this.barContainerReports, "barContainerReports"); this.barContainerReports.Id = 11; this.barContainerReports.MergeOrder = 12; this.barContainerReports.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerReports.Name = "barContainerReports"; // // barActionContainerDefault // this.barActionContainerDefault.ActionCategory = "Default"; this.barActionContainerDefault.BarContainerItem = this.barContainerDefault; // // barContainerDefault // resources.ApplyResources(this.barContainerDefault, "barContainerDefault"); this.barContainerDefault.Id = 50; this.barContainerDefault.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerDefault.Name = "barContainerDefault"; // // barActionContainerPanels // this.barActionContainerPanels.ActionCategory = "Panels"; this.barActionContainerPanels.BarContainerItem = this.barContainerPanels; this.barActionContainerPanels.IsMenuMode = true; // // barContainerPanels // resources.ApplyResources(this.barContainerPanels, "barContainerPanels"); this.barContainerPanels.Id = 16; this.barContainerPanels.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerPanels.Name = "barContainerPanels"; // // barActionContainerRecordsNavigation // this.barActionContainerRecordsNavigation.ActionCategory = "RecordsNavigation"; this.barActionContainerRecordsNavigation.BarContainerItem = this.barContainerRecordsNavigation; // // barContainerRecordsNavigation // resources.ApplyResources(this.barContainerRecordsNavigation, "barContainerRecordsNavigation"); this.barContainerRecordsNavigation.Id = 10; this.barContainerRecordsNavigation.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerRecordsNavigation.Name = "barContainerRecordsNavigation"; // // barActionContainerFilters // this.barActionContainerFilters.ActionCategory = "Filters"; this.barActionContainerFilters.BarContainerItem = this.barContainerFilters; // // barContainerFilters // resources.ApplyResources(this.barContainerFilters, "barContainerFilters"); this.barContainerFilters.Id = 26; this.barContainerFilters.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerFilters.Name = "barContainerFilters"; // // barActionContainerSearch // this.barActionContainerSearch.ActionCategory = "Search"; this.barActionContainerSearch.BarContainerItem = this.barContainerSearch; // // barContainerSearch // resources.ApplyResources(this.barContainerSearch, "barContainerSearch"); this.barContainerSearch.Id = 11; this.barContainerSearch.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerSearch.Name = "barContainerSearch"; // // barActionContainerFullTextSearch // this.barActionContainerFullTextSearch.ActionCategory = "FullTextSearch"; this.barActionContainerFullTextSearch.BarContainerItem = this.barContainerFullTextSearch; // // barContainerFullTextSearch // resources.ApplyResources(this.barContainerFullTextSearch, "barContainerFullTextSearch"); this.barContainerFullTextSearch.Id = 12; this.barContainerFullTextSearch.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerFullTextSearch.Name = "barContainerFullTextSearch"; // // barActionContainerViewsNavigation // this.barActionContainerViewsNavigation.ActionCategory = "ViewsNavigation"; this.barActionContainerViewsNavigation.BarContainerItem = this.barContainerViewsNavigation; // // barContainerViewsNavigation // resources.ApplyResources(this.barContainerViewsNavigation, "barContainerViewsNavigation"); this.barContainerViewsNavigation.Id = 14; this.barContainerViewsNavigation.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerViewsNavigation.Name = "barContainerViewsNavigation"; // // barActionContainerWindows // this.barActionContainerWindows.ActionCategory = "Windows"; this.barActionContainerWindows.BarContainerItem = this.barContainerWindows; // // barContainerWindows // this.barContainerWindows.Id = 16; this.barContainerWindows.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerWindows.Name = "barContainerWindows"; // // barActionContainerTools // this.barActionContainerTools.ActionCategory = "Tools"; this.barActionContainerTools.BarContainerItem = this.barContainerTools; this.barActionContainerTools.IsMenuMode = true; // // barContainerTools // resources.ApplyResources(this.barContainerTools, "barContainerTools"); this.barContainerTools.Id = 13; this.barContainerTools.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerTools.Name = "barContainerTools"; // // barActionContainerOptions // this.barActionContainerOptions.ActionCategory = "Options"; this.barActionContainerOptions.BarContainerItem = this.barContainerOptions; this.barActionContainerOptions.IsMenuMode = true; // // barContainerOptions // resources.ApplyResources(this.barContainerOptions, "barContainerOptions"); this.barContainerOptions.Id = 14; this.barContainerOptions.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerOptions.Name = "barContainerOptions"; // // barActionContainerDiagnostic // this.barActionContainerDiagnostic.ActionCategory = "Diagnostic"; this.barActionContainerDiagnostic.BarContainerItem = this.barContainerDiagnostic; this.barActionContainerDiagnostic.IsMenuMode = true; // // barContainerDiagnostic // resources.ApplyResources(this.barContainerDiagnostic, "barContainerDiagnostic"); this.barContainerDiagnostic.Id = 16; this.barContainerDiagnostic.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerDiagnostic.Name = "barContainerDiagnostic"; // // barActionContainerExit // this.barActionContainerExit.ActionCategory = "Exit"; this.barActionContainerExit.BarContainerItem = this.barContainerExit; // // barContainerExit // resources.ApplyResources(this.barContainerExit, "barContainerExit"); this.barContainerExit.Id = 8; this.barContainerExit.MergeOrder = 900; this.barContainerExit.Name = "barContainerExit"; // // barActionContainerAbout // this.barActionContainerAbout.ActionCategory = "About"; this.barActionContainerAbout.BarContainerItem = this.barContainerAbout; this.barActionContainerAbout.IsMenuMode = true; // // barContainerAbout // resources.ApplyResources(this.barContainerAbout, "barContainerAbout"); this.barContainerAbout.Id = 15; this.barContainerAbout.MergeOrder = 15; this.barContainerAbout.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerAbout.Name = "barContainerAbout"; // // barActionContainerMenu // this.barActionContainerMenu.ActionCategory = "Menu"; this.barActionContainerMenu.BarContainerItem = this.barContainerMenu; // // barContainerMenu // resources.ApplyResources(this.barContainerMenu, "barContainerMenu"); this.barContainerMenu.Id = 7; this.barContainerMenu.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerMenu.Name = "barContainerMenu"; // // barActionContainerNotifications // this.barActionContainerNotifications.ActionCategory = "Notifications"; this.barActionContainerNotifications.BarContainerItem = this.barContainerNotifications; // // barContainerNotifications // this.barContainerNotifications.Alignment = DevExpress.XtraBars.BarItemLinkAlignment.Right; resources.ApplyResources(this.barContainerNotifications, "barContainerNotifications"); this.barContainerNotifications.Id = 28; this.barContainerNotifications.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerNotifications.Name = "barContainerNotifications"; // // ribbonChooseSkinActionControl // this.ribbonChooseSkinActionControl.ActionId = "ChooseSkin"; this.ribbonChooseSkinActionControl.BarItem = this.ribbonGallerySkins; // // ribbonGallerySkins // resources.ApplyResources(this.ribbonGallerySkins, "ribbonGallerySkins"); this.ribbonGallerySkins.Id = 1; this.ribbonGallerySkins.Name = "ribbonGallerySkins"; // // applicationMenu // this.applicationMenu.ItemLinks.Add(this.barContainerObjectsCreation, true); this.applicationMenu.ItemLinks.Add(this.barContainerFile, true); this.applicationMenu.ItemLinks.Add(this.barContainerSave, true); this.applicationMenu.ItemLinks.Add(this.barContainerExport, true); this.applicationMenu.ItemLinks.Add(this.barContainerPrint, true); this.applicationMenu.ItemLinks.Add(this.barContainerReports, true); this.applicationMenu.ItemLinks.Add(this.barContainerAbout, true); this.applicationMenu.ItemLinks.Add(this.barContainerExit, true); this.applicationMenu.MenuDrawMode = DevExpress.XtraBars.MenuDrawMode.LargeImagesText; this.applicationMenu.Name = "applicationMenu"; this.applicationMenu.Ribbon = this.ribbonControl; // // mainBarAndDockingController // this.mainBarAndDockingController.PropertiesBar.AllowLinkLighting = false; this.mainBarAndDockingController.PropertiesBar.DefaultGlyphSize = new System.Drawing.Size(16, 16); this.mainBarAndDockingController.PropertiesBar.DefaultLargeGlyphSize = new System.Drawing.Size(32, 32); // // barSubItemPanels // resources.ApplyResources(this.barSubItemPanels, "barSubItemPanels"); this.barSubItemPanels.HideWhenEmpty = true; this.barSubItemPanels.Id = 7; this.barSubItemPanels.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.barContainerPanels, true)}); this.barSubItemPanels.Name = "barSubItemPanels"; // // barContainerStatusMessages // resources.ApplyResources(this.barContainerStatusMessages, "barContainerStatusMessages"); this.barContainerStatusMessages.Id = 27; this.barContainerStatusMessages.MergeType = DevExpress.XtraBars.BarMenuMerge.MergeItems; this.barContainerStatusMessages.Name = "barContainerStatusMessages"; // // barCheckItemNormal // this.barCheckItemNormal.Alignment = DevExpress.XtraBars.BarItemLinkAlignment.Right; this.barCheckItemNormal.AllowGlyphSkinning = DevExpress.Utils.DefaultBoolean.True; this.barCheckItemNormal.BindableChecked = true; resources.ApplyResources(this.barCheckItemNormal, "barCheckItemNormal"); this.barCheckItemNormal.Checked = true; this.barCheckItemNormal.GroupIndex = 1180782442; this.barCheckItemNormal.Id = 16; this.barCheckItemNormal.Name = "barCheckItemNormal"; this.barCheckItemNormal.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.SmallWithoutText; // // barCheckItemReading // this.barCheckItemReading.Alignment = DevExpress.XtraBars.BarItemLinkAlignment.Right; this.barCheckItemReading.AllowGlyphSkinning = DevExpress.Utils.DefaultBoolean.True; resources.ApplyResources(this.barCheckItemReading, "barCheckItemReading"); this.barCheckItemReading.GroupIndex = 1180782442; this.barCheckItemReading.Id = 17; this.barCheckItemReading.Name = "barCheckItemReading"; this.barCheckItemReading.RibbonStyle = DevExpress.XtraBars.Ribbon.RibbonItemStyles.SmallWithoutText; // // barSubItemNavigationPane // resources.ApplyResources(this.barSubItemNavigationPane, "barSubItemNavigationPane"); this.barSubItemNavigationPane.Id = 18; this.barSubItemNavigationPane.Name = "barSubItemNavigationPane"; // // defaultPage // this.defaultPage.Groups.AddRange(new DevExpress.XtraBars.Ribbon.RibbonPageGroup[] { this.ribbonGroupViewsHistoryNavigation, this.ribbonGroupObjectsCreation, this.ribbonGroupSave, this.ribbonGroupEdit, this.ribbonGroupRecordEdit, this.ribbonGroupOpenObject, this.ribbonGroupWorkflow, this.ribbonGroupView, this.ribbonGroupDefault, this.ribbonGroupRecordsNavigation, this.ribbonGroupFilters, this.ribbonGroupSearch, this.ribbonGroupFullTextSearch}); this.defaultPage.Name = "defaultPage"; resources.ApplyResources(this.defaultPage, "defaultPage"); // // ribbonGroupViewsHistoryNavigation // this.ribbonGroupViewsHistoryNavigation.AllowTextClipping = false; this.ribbonGroupViewsHistoryNavigation.ItemLinks.Add(this.barContainerViewsHistoryNavigation); this.ribbonGroupViewsHistoryNavigation.Name = "ribbonGroupViewsHistoryNavigation"; this.ribbonGroupViewsHistoryNavigation.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupViewsHistoryNavigation, "ribbonGroupViewsHistoryNavigation"); // // ribbonGroupObjectsCreation // this.ribbonGroupObjectsCreation.AllowTextClipping = false; this.ribbonGroupObjectsCreation.ItemLinks.Add(this.barContainerObjectsCreation); this.ribbonGroupObjectsCreation.Name = "ribbonGroupObjectsCreation"; this.ribbonGroupObjectsCreation.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupObjectsCreation, "ribbonGroupObjectsCreation"); // // ribbonGroupSave // this.ribbonGroupSave.AllowTextClipping = false; this.ribbonGroupSave.ItemLinks.Add(this.barContainerSave); this.ribbonGroupSave.Name = "ribbonGroupSave"; this.ribbonGroupSave.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupSave, "ribbonGroupSave"); // // ribbonGroupEdit // this.ribbonGroupEdit.AllowTextClipping = false; this.ribbonGroupEdit.ItemLinks.Add(this.barContainerEdit); this.ribbonGroupEdit.ItemLinks.Add(this.barContainerUndoRedo); this.ribbonGroupEdit.Name = "ribbonGroupEdit"; this.ribbonGroupEdit.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupEdit, "ribbonGroupEdit"); // // ribbonGroupRecordEdit // this.ribbonGroupRecordEdit.AllowTextClipping = false; this.ribbonGroupRecordEdit.ItemLinks.Add(this.barContainerRecordEdit); this.ribbonGroupRecordEdit.Name = "ribbonGroupRecordEdit"; this.ribbonGroupRecordEdit.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupRecordEdit, "ribbonGroupRecordEdit"); // // ribbonGroupOpenObject // this.ribbonGroupOpenObject.AllowTextClipping = false; this.ribbonGroupOpenObject.ItemLinks.Add(this.barContainerOpenObject); this.ribbonGroupOpenObject.Name = "ribbonGroupOpenObject"; this.ribbonGroupOpenObject.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupOpenObject, "ribbonGroupOpenObject"); // // ribbonGroupWorkflow // this.ribbonGroupWorkflow.AllowTextClipping = false; this.ribbonGroupWorkflow.ItemLinks.Add(this.barContainerWorkflow); this.ribbonGroupWorkflow.Name = "ribbonGroupWorkflow"; this.ribbonGroupWorkflow.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupWorkflow, "ribbonGroupWorkflow"); // // ribbonGroupView // this.ribbonGroupView.AllowTextClipping = false; this.ribbonGroupView.ItemLinks.Add(this.barContainerView); this.ribbonGroupView.ItemLinks.Add(this.barContainerReports); this.ribbonGroupView.Name = "ribbonGroupView"; this.ribbonGroupView.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupView, "ribbonGroupView"); // // ribbonGroupDefault // this.ribbonGroupDefault.AllowTextClipping = false; this.ribbonGroupDefault.ItemLinks.Add(this.barContainerDefault); this.ribbonGroupDefault.Name = "ribbonGroupDefault"; this.ribbonGroupDefault.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupDefault, "ribbonGroupDefault"); // // ribbonGroupRecordsNavigation // this.ribbonGroupRecordsNavigation.AllowTextClipping = false; this.ribbonGroupRecordsNavigation.ItemLinks.Add(this.barContainerRecordsNavigation); this.ribbonGroupRecordsNavigation.Name = "ribbonGroupRecordsNavigation"; this.ribbonGroupRecordsNavigation.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupRecordsNavigation, "ribbonGroupRecordsNavigation"); // // ribbonGroupFilters // this.ribbonGroupFilters.AllowTextClipping = false; this.ribbonGroupFilters.ItemLinks.Add(this.barContainerFilters); this.ribbonGroupFilters.Name = "ribbonGroupFilters"; this.ribbonGroupFilters.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupFilters, "ribbonGroupFilters"); // // ribbonGroupSearch // this.ribbonGroupSearch.AllowTextClipping = false; this.ribbonGroupSearch.ItemLinks.Add(this.barContainerSearch); this.ribbonGroupSearch.Name = "ribbonGroupSearch"; this.ribbonGroupSearch.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupSearch, "ribbonGroupSearch"); // // ribbonGroupFullTextSearch // this.ribbonGroupFullTextSearch.AllowTextClipping = false; this.ribbonGroupFullTextSearch.ItemLinks.Add(this.barContainerFullTextSearch); this.ribbonGroupFullTextSearch.Name = "ribbonGroupFullTextSearch"; this.ribbonGroupFullTextSearch.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupFullTextSearch, "ribbonGroupFullTextSearch"); // // viewPage // this.viewPage.Groups.AddRange(new DevExpress.XtraBars.Ribbon.RibbonPageGroup[] { this.ribbonGroupViewsNavigation, this.ribbonGroupAppearance, this.ribbonGroupWindows, this.defaultPageGroup}); this.viewPage.Name = "viewPage"; resources.ApplyResources(this.viewPage, "viewPage"); // // ribbonGroupViewsNavigation // this.ribbonGroupViewsNavigation.AllowTextClipping = false; this.ribbonGroupViewsNavigation.ItemLinks.Add(this.barContainerViewsNavigation); this.ribbonGroupViewsNavigation.ItemLinks.Add(this.barSubItemNavigationPane); this.ribbonGroupViewsNavigation.MergeOrder = 0; this.ribbonGroupViewsNavigation.Name = "ribbonGroupViewsNavigation"; this.ribbonGroupViewsNavigation.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupViewsNavigation, "ribbonGroupViewsNavigation"); // // ribbonGroupAppearance // this.ribbonGroupAppearance.AllowTextClipping = false; this.ribbonGroupAppearance.ItemLinks.Add(this.ribbonGallerySkins); this.ribbonGroupAppearance.MergeOrder = 1; this.ribbonGroupAppearance.Name = "ribbonGroupAppearance"; this.ribbonGroupAppearance.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupAppearance, "ribbonGroupAppearance"); // // ribbonGroupWindows // this.ribbonGroupWindows.AllowTextClipping = false; this.ribbonGroupWindows.ItemLinks.Add(this.barContainerWindows); this.ribbonGroupWindows.MergeOrder = 2; this.ribbonGroupWindows.Name = "ribbonGroupWindows"; this.ribbonGroupWindows.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupWindows, "ribbonGroupWindows"); // // defaultPageGroup // this.defaultPageGroup.AllowTextClipping = false; this.defaultPageGroup.ItemLinks.Add(this.barSubItemPanels); this.defaultPageGroup.MergeOrder = 3; this.defaultPageGroup.Name = "defaultPageGroup"; this.defaultPageGroup.ShowCaptionButton = false; resources.ApplyResources(this.defaultPageGroup, "defaultPageGroup"); // // toolsPage // this.toolsPage.Groups.AddRange(new DevExpress.XtraBars.Ribbon.RibbonPageGroup[] { this.ribbonGroupTools, this.ribbonGroupOptions, this.ribbonGroupDiagnostic}); this.toolsPage.Name = "toolsPage"; resources.ApplyResources(this.toolsPage, "toolsPage"); // // ribbonGroupTools // this.ribbonGroupTools.AllowTextClipping = false; this.ribbonGroupTools.ItemLinks.Add(this.barContainerTools); this.ribbonGroupTools.Name = "ribbonGroupTools"; this.ribbonGroupTools.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupTools, "ribbonGroupTools"); // // ribbonGroupOptions // this.ribbonGroupOptions.AllowTextClipping = false; this.ribbonGroupOptions.ItemLinks.Add(this.barContainerOptions); this.ribbonGroupOptions.Name = "ribbonGroupOptions"; this.ribbonGroupOptions.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupOptions, "ribbonGroupOptions"); // // ribbonGroupDiagnostic // this.ribbonGroupDiagnostic.AllowTextClipping = false; this.ribbonGroupDiagnostic.ItemLinks.Add(this.barContainerDiagnostic); this.ribbonGroupDiagnostic.Name = "ribbonGroupDiagnostic"; this.ribbonGroupDiagnostic.ShowCaptionButton = false; resources.ApplyResources(this.ribbonGroupDiagnostic, "ribbonGroupDiagnostic"); // // windowPage // this.windowPage.Name = "windowPage"; resources.ApplyResources(this.windowPage, "windowPage"); // // ribbonStatusBar // this.ribbonStatusBar.ItemLinks.Add(this.barContainerStatusMessages); this.ribbonStatusBar.ItemLinks.Add(this.barCheckItemNormal); this.ribbonStatusBar.ItemLinks.Add(this.barCheckItemReading); this.ribbonStatusBar.ItemLinks.Add(this.barContainerNotifications); resources.ApplyResources(this.ribbonStatusBar, "ribbonStatusBar"); this.ribbonStatusBar.Name = "ribbonStatusBar"; this.ribbonStatusBar.Ribbon = this.ribbonControl; // // officeNavigationBar // resources.ApplyResources(this.officeNavigationBar, "officeNavigationBar"); this.officeNavigationBar.MenuManager = this.ribbonControl.Manager; this.officeNavigationBar.Name = "officeNavigationBar"; this.officeNavigationBar.NavigationClient = this.navBarControl; // // dockManager // this.dockManager.Controller = this.mainBarAndDockingController; this.dockManager.Form = this; this.dockManager.TopZIndexControls.AddRange(new string[] { "DevExpress.XtraBars.Navigation.OfficeNavigationBar", "DevExpress.ExpressApp.Win.Templates.Ribbon.XafRibbonControlV2", "DevExpress.XtraBars.Ribbon.RibbonStatusBar"}); // // documentManager // this.documentManager.BarAndDockingController = this.mainBarAndDockingController; this.documentManager.ClientControl = this.viewSitePanel; this.documentManager.MenuManager = this.ribbonControl.Manager; this.documentManager.ShowThumbnailsInTaskBar = DevExpress.Utils.DefaultBoolean.False; this.documentManager.View = this.noDocumentsView; this.documentManager.ViewCollection.AddRange(new DevExpress.XtraBars.Docking2010.Views.BaseView[] { this.noDocumentsView}); // // viewSiteManager // this.viewSiteManager.ViewSiteControl = this.viewSitePanel; // // transitionManager // transition.Control = this.mainContainer; transition.ShowWaitingIndicator = DevExpress.Utils.DefaultBoolean.False; slideFadeTransition.Parameters.Background = System.Drawing.Color.Empty; slideFadeTransition.Parameters.EffectOptions = DevExpress.Utils.Animation.PushEffectOptions.FromRight; slideFadeTransition.Parameters.FrameInterval = 3000; transition.TransitionType = slideFadeTransition; this.transitionManager.Transitions.Add(transition); // // modelSynchronizationManager // this.modelSynchronizationManager.ModelSynchronizableComponents.Add(this.formStateModelSynchronizer); this.modelSynchronizationManager.ModelSynchronizableComponents.Add(this.navBarControlModelSynchronizer); this.modelSynchronizationManager.ModelSynchronizableComponents.Add(this.officeNavigationBarCustomizationModelSynchronizer); // // formStateModelSynchronizer // this.formStateModelSynchronizer.Form = this; // // navBarControlModelSynchronizer // this.navBarControlModelSynchronizer.NavBarControl = this.navBarControl; // // officeNavBarModelSynchronizer // this.officeNavigationBarCustomizationModelSynchronizer.OfficeNavigationBar = this.officeNavigationBar; // // contextMenu // this.contextMenu.ItemLinks.Add(this.barContainerObjectsCreation, true); this.contextMenu.ItemLinks.Add(this.barContainerSave, true); this.contextMenu.ItemLinks.Add(this.barContainerEdit, true); this.contextMenu.ItemLinks.Add(this.barContainerRecordEdit, true); this.contextMenu.ItemLinks.Add(this.barContainerOpenObject, true); this.contextMenu.ItemLinks.Add(this.barContainerPrint, true); this.contextMenu.ItemLinks.Add(this.barContainerView, true); this.contextMenu.ItemLinks.Add(this.barContainerExport, true); this.contextMenu.ItemLinks.Add(this.barContainerMenu, true); this.contextMenu.Name = "contextMenu"; this.contextMenu.Ribbon = this.ribbonControl; this.actionContainersManager.Template = this; // // OutlookStyleMainRibbonDynamicActionContainer // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.mainContainer); this.Controls.Add(this.officeNavigationBar); this.Controls.Add(this.ribbonStatusBar); this.Controls.Add(this.ribbonControl); this.Name = "OutlookStyleMainRibbonDynamicActionContainer"; this.Ribbon = this.ribbonControl; this.StatusBar = this.ribbonStatusBar; this.mainContainer.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.viewSitePanel)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.separatorControl)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.navBarControl)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.navBarSingleChoiceActionControl)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.ribbonControl)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerViewsHistoryNavigation)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerObjectsCreation)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerFile)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerSave)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerPrint)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerEdit)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerUndoRedo)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerOpenObject)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerExport)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerRecordEdit)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerWorkflow)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerView)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerReports)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerDefault)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerPanels)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerRecordsNavigation)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerFilters)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerSearch)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerFullTextSearch)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerViewsNavigation)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerWindows)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerTools)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerOptions)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerDiagnostic)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerExit)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerAbout)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerMenu)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barActionContainerNotifications)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.ribbonChooseSkinActionControl)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.applicationMenu)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.mainBarAndDockingController)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.officeNavigationBar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dockManager)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.documentManager)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.noDocumentsView)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.contextMenu)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private DevExpress.XtraBars.BarAndDockingController mainBarAndDockingController; private DevExpress.XtraBars.Docking.DockManager dockManager; private DevExpress.ExpressApp.Win.Templates.Ribbon.XafRibbonControlV2 ribbonControl; private DevExpress.XtraBars.Ribbon.RibbonStatusBar ribbonStatusBar; private DevExpress.XtraEditors.PanelControl viewSitePanel; private DevExpress.ExpressApp.Win.Templates.Navigation.XafNavBarControl navBarControl; private DevExpress.XtraEditors.XtraUserControl mainContainer; private DevExpress.XtraBars.BarSubItem barSubItemPanels; private DevExpress.XtraBars.Ribbon.RibbonPage defaultPage; private DevExpress.XtraBars.Ribbon.RibbonPage viewPage; private DevExpress.XtraBars.Ribbon.RibbonPage toolsPage; private DevExpress.XtraBars.Ribbon.RibbonPage windowPage; private DevExpress.XtraBars.Ribbon.ApplicationMenu applicationMenu; private DevExpress.XtraBars.Ribbon.RibbonPageGroup defaultPageGroup; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupObjectsCreation; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupSave; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupAppearance; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupEdit; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupOpenObject; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupViewsNavigation; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupRecordEdit; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupWorkflow; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupRecordsNavigation; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupViewsHistoryNavigation; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupSearch; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupFullTextSearch; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupFilters; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupView; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupDefault; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupTools; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupDiagnostic; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupOptions; private DevExpress.XtraBars.Ribbon.RibbonPageGroup ribbonGroupWindows; private DevExpress.XtraBars.BarLinkContainerExItem barContainerViewsHistoryNavigation; private DevExpress.XtraBars.BarLinkContainerExItem barContainerObjectsCreation; private DevExpress.XtraBars.BarLinkContainerExItem barContainerFile; private DevExpress.XtraBars.BarLinkContainerExItem barContainerSave; private DevExpress.XtraBars.BarLinkContainerExItem barContainerPrint; private DevExpress.XtraBars.BarLinkContainerExItem barContainerEdit; private DevExpress.XtraBars.BarLinkContainerExItem barContainerUndoRedo; private DevExpress.XtraBars.BarLinkContainerExItem barContainerOpenObject; private DevExpress.XtraBars.BarLinkContainerExItem barContainerExport; private DevExpress.XtraBars.BarLinkContainerExItem barContainerRecordEdit; private DevExpress.XtraBars.BarLinkContainerExItem barContainerWorkflow; private DevExpress.XtraBars.BarLinkContainerExItem barContainerView; private DevExpress.XtraBars.BarLinkContainerExItem barContainerReports; private DevExpress.XtraBars.BarLinkContainerExItem barContainerDefault; private DevExpress.XtraBars.BarLinkContainerExItem barContainerPanels; private DevExpress.XtraBars.BarLinkContainerExItem barContainerRecordsNavigation; private DevExpress.XtraBars.BarLinkContainerExItem barContainerFilters; private DevExpress.XtraBars.BarLinkContainerExItem barContainerSearch; private DevExpress.XtraBars.BarLinkContainerExItem barContainerFullTextSearch; private DevExpress.XtraBars.BarLinkContainerExItem barContainerViewsNavigation; private DevExpress.XtraBars.BarLinkContainerExItem barContainerWindows; private DevExpress.XtraBars.BarLinkContainerExItem barContainerTools; private DevExpress.XtraBars.BarLinkContainerExItem barContainerOptions; private DevExpress.XtraBars.BarLinkContainerExItem barContainerDiagnostic; private DevExpress.XtraBars.BarLinkContainerExItem barContainerExit; private DevExpress.XtraBars.BarLinkContainerExItem barContainerAbout; private DevExpress.XtraBars.BarLinkContainerExItem barContainerMenu; private DevExpress.XtraBars.BarLinkContainerExItem barContainerNotifications; private DevExpress.XtraBars.BarLinkContainerExItem barContainerStatusMessages; private DevExpress.XtraBars.RibbonGalleryBarItem ribbonGallerySkins; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerViewsNavigation; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerViewsHistoryNavigation; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerObjectsCreation; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerFile; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerSave; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerPrint; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerEdit; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerUndoRedo; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerOpenObject; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerExport; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerRecordEdit; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerWorkflow; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerDefault; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerPanels; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerRecordsNavigation; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerFilters; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerSearch; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerFullTextSearch; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerWindows; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerTools; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerOptions; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerDiagnostic; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerExit; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerView; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerReports; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerAbout; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerMenu; private DevExpress.ExpressApp.Win.Templates.Bars.ActionControls.BarLinkActionControlContainer barActionContainerNotifications; private DevExpress.ExpressApp.Win.Templates.Ribbon.ActionControls.RibbonChooseSkinActionControl ribbonChooseSkinActionControl; private DevExpress.ExpressApp.Win.Templates.Navigation.NavBarSingleChoiceActionControl navBarSingleChoiceActionControl; private DevExpress.XtraBars.Navigation.OfficeNavigationBar officeNavigationBar; private DevExpress.XtraBars.Docking2010.DocumentManager documentManager; private DevExpress.XtraBars.Docking2010.Views.NoDocuments.NoDocumentsView noDocumentsView; private DevExpress.ExpressApp.Win.Templates.ViewSiteManager viewSiteManager; private DevExpress.Utils.Animation.TransitionManager transitionManager; private DevExpress.ExpressApp.Win.Templates.ModelSynchronizationManager modelSynchronizationManager; private DevExpress.ExpressApp.Win.Core.FormStateModelSynchronizer formStateModelSynchronizer; private DevExpress.ExpressApp.Win.Templates.Navigation.NavBarControlModelSynchronizer navBarControlModelSynchronizer; private DevExpress.ExpressApp.Win.Templates.Navigation.OfficeNavigationBarCustomizationModelSynchronizer officeNavigationBarCustomizationModelSynchronizer; private DevExpress.XtraBars.PopupMenu contextMenu; private DevExpress.XtraBars.BarCheckItem barCheckItemNormal; private DevExpress.XtraBars.BarCheckItem barCheckItemReading; private DevExpress.XtraBars.BarSubItem barSubItemNavigationPane; private DevExpress.XtraEditors.SeparatorControl separatorControl; private DevExpress.ExpressApp.Win.Templates.ActionContainersManager actionContainersManager; } }
64.700084
193
0.703535
[ "MPL-2.0" ]
cuongpv88/XAF.ElasticSearch
BYteWare.XAF.ElasticSearch.Win/Template/OutlookStyleMainRibbonDynamicActionContainer.Designer.cs
77,448
C#
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class ChallengeDecoder { public const ushort BLOCK_LENGTH = 16; public const ushort TEMPLATE_ID = 7; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 4; private ChallengeDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public ChallengeDecoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public ChallengeDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int CorrelationIdId() { return 1; } public static int CorrelationIdSinceVersion() { return 0; } public static int CorrelationIdEncodingOffset() { return 0; } public static int CorrelationIdEncodingLength() { return 8; } public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public long CorrelationId() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int ClusterSessionIdId() { return 2; } public static int ClusterSessionIdSinceVersion() { return 0; } public static int ClusterSessionIdEncodingOffset() { return 8; } public static int ClusterSessionIdEncodingLength() { return 8; } public static string ClusterSessionIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long ClusterSessionIdNullValue() { return -9223372036854775808L; } public static long ClusterSessionIdMinValue() { return -9223372036854775807L; } public static long ClusterSessionIdMaxValue() { return 9223372036854775807L; } public long ClusterSessionId() { return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian); } public static int EncodedChallengeId() { return 3; } public static int EncodedChallengeSinceVersion() { return 0; } public static string EncodedChallengeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int EncodedChallengeHeaderLength() { return 4; } public int EncodedChallengeLength() { int limit = _parentMessage.Limit(); return (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); } public int GetEncodedChallenge(IMutableDirectBuffer dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public int GetEncodedChallenge(byte[] dst, int dstOffset, int length) { int headerLength = 4; int limit = _parentMessage.Limit(); int dataLength = (int)unchecked((uint)_buffer.GetInt(limit, ByteOrder.LittleEndian)); int bytesCopied = Math.Min(length, dataLength); _parentMessage.Limit(limit + headerLength + dataLength); _buffer.GetBytes(limit + headerLength, dst, dstOffset, bytesCopied); return bytesCopied; } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[Challenge](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("CorrelationId="); builder.Append(CorrelationId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='clusterSessionId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("ClusterSessionId="); builder.Append(ClusterSessionId()); builder.Append('|'); //Token{signal=BEGIN_VAR_DATA, name='encodedChallenge', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=6, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("EncodedChallenge="); builder.Append(EncodedChallengeLength() + " raw bytes"); Limit(originalLimit); return builder; } } }
30.104575
416
0.659032
[ "Apache-2.0" ]
FrancisChung/Aeron.NET
src/Adaptive.Cluster/Codecs/ChallengeDecoder.cs
9,212
C#
namespace FourRoads.TelligentCommunity.Splash.Logic { public struct SplashConfigurationDetails { public string Password; public bool CreateAccount; public bool RemoveHeader; public bool RemoveFooter; } }
24.7
51
0.696356
[ "MIT" ]
4-Roads/FourRoads.TelligentCommunity
src/code/FourRoads.TelligentCommunity.Splash/Logic/SplashConfigurationDetails.cs
247
C#
using System; using Ray.Infrastructure.Extensions; using Ray.Serilog.Sinks.Batched; using Serilog.Events; namespace Ray.Serilog.Sinks.PushPlusBatched { public class PushPlusBatchedSink : BatchedSink { private readonly string _token; private readonly string _topic; private readonly string _channel; private readonly string _webhook; public PushPlusBatchedSink( string token, string topic, string channel, string webhook, Predicate<LogEvent> predicate, bool sendBatchesAsOneMessages, string outputTemplate, IFormatProvider formatProvider, LogEventLevel minimumLogEventLevel ) : base(predicate, sendBatchesAsOneMessages, outputTemplate, formatProvider, minimumLogEventLevel) { _token = token; _topic = topic; _channel = channel; _webhook = webhook; } public override void Emit(LogEvent logEvent) { if (_token.IsNullOrEmpty()) return; base.Emit(logEvent); } protected override PushService PushService => new PushPlusApiClient( _token, _topic, channel: _channel, webhook: _webhook); public override void Dispose() { //todo } } }
27.288462
109
0.589852
[ "MIT" ]
RayWangQvQ/Ray.AutoTask
framework/Ray.Serilog.Sinks/Ray.Serilog.Sinks.PushPlusBatched/PushPlusBatchedSink.cs
1,421
C#
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("NetResponder")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NetResponder")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("bb485682-ced9-442c-9f42-437412a7fb18")] [assembly: AssemblyVersion("1.0.*")]
33.2
56
0.761044
[ "MIT" ]
BlueSkeye/NetResponder
Properties/AssemblyInfo.cs
501
C#
using System.Collections.Generic; namespace parent_bMedecine.BusinessManagement.Patient { /// <summary> /// IPatientService interface /// </summary> public interface IPatientDataService { /// <summary> /// Retrieve all patients /// </summary> /// <returns>a list of patients</returns> List<ServicePatient.Patient> GetListPatient(); /// <summary> /// Retrieve a unique patient with id /// </summary> /// <param name="id">patient's id</param> /// <returns>a patient if he exists, null otherwise</returns> ServicePatient.Patient GetPatient(int id); /// <summary> /// Add a patient /// </summary> /// <param name="patient">the patient to add</param> /// <returns>true if added, false otherwise</returns> bool AddPatient(ServicePatient.Patient patient); /// <summary> /// Delete a patient /// </summary> /// <param name="id">patient's id</param> /// <returns>true if deleted, false otherwise</returns> bool DeletePatient(int id); } }
30.837838
69
0.57844
[ "MIT" ]
aparenton/mti-wpf
parent_bMedecine/parent_bMedecine/BusinessManagement/Patient/IPatientDataService.cs
1,143
C#
// Copyright (c) TotalSoft. // This source code is licensed under the MIT license. using System; using System.Threading; using System.Threading.Tasks; namespace NBB.Core.Effects { public class GenericSideEffectHandler<TSideEffect, TOutput>: ISideEffectHandler<TSideEffect, TOutput> where TSideEffect : ISideEffect<TOutput> { private readonly Func<TSideEffect, CancellationToken, Task<TOutput>> handlerFn; public GenericSideEffectHandler(Func<TSideEffect, CancellationToken, Task<TOutput>> handlerFn) { this.handlerFn = handlerFn; } public Task<TOutput> Handle(TSideEffect sideEffect, CancellationToken cancellationToken = default) { return handlerFn(sideEffect, cancellationToken); } } }
31.461538
107
0.685819
[ "MIT" ]
VCuzmin/nbb
src/Core/NBB.Core.Effects/GenericSideEffectHandler.cs
820
C#
using System; using ETModel; using UnityEngine; using UnityEngine.UI; namespace ETHotfix { [ObjectSystem] public class UiLobbyComponentSystem : AwakeSystem<UILobbyComponent> { public override void Awake(UILobbyComponent self) { self.Awake(); } } public class UILobbyComponent : Component { private GameObject enterMap; private Text text; public void Awake() { ReferenceCollector rc = this.GetParent<UI>().GameObject.GetComponent<ReferenceCollector>(); GameObject sendBtn = rc.Get<GameObject>("Send"); GameObject sendRpcBtn = rc.Get<GameObject>("" + "SendRpc"); sendBtn.GetComponent<Button>().onClick.Add(this.OnSend); sendRpcBtn.GetComponent<Button>().onClick.Add(this.OnSendRpc); GameObject transfer1Btn = rc.Get<GameObject>("Transfer1"); GameObject transfer2Btn = rc.Get<GameObject>("Transfer2"); transfer1Btn.GetComponent<Button>().onClick.Add(this.OnTransfer1); transfer2Btn.GetComponent<Button>().onClick.Add(this.OnTransfer2); enterMap = rc.Get<GameObject>("EnterMap"); enterMap.GetComponent<Button>().onClick.Add(this.EnterMap); this.text = rc.Get<GameObject>("Text").GetComponent<Text>(); } private void OnSend() { // 发送一个actor消息 ETModel.SessionComponent.Instance.Session.Send(new Actor_Test() { Info = "message client->gate->map->gate->client" }); } private async void OnSendRpc() { try { // 向actor发起一次rpc调用 Actor_TestResponse response = (Actor_TestResponse) await ETModel.SessionComponent.Instance.Session.Call(new Actor_TestRequest() { Request = "request actor test rpc" }); Log.Info($"recv response: {JsonHelper.ToJson(response)}"); } catch (Exception e) { Log.Error(e); } } private async void OnTransfer1() { try { Actor_TransferResponse response = (Actor_TransferResponse) await ETModel.SessionComponent.Instance.Session.Call(new Actor_TransferRequest() {MapIndex = 0}); Log.Info($"传送成功! {JsonHelper.ToJson(response)}"); } catch (Exception e) { Log.Error(e); } } private async void OnTransfer2() { Actor_TransferResponse response = (Actor_TransferResponse)await ETModel.SessionComponent.Instance.Session.Call(new Actor_TransferRequest() { MapIndex = 1 }); Log.Info($"传送成功! {JsonHelper.ToJson(response)}"); } private async void EnterMap() { try { // 加载Unit资源 ResourcesComponent resourcesComponent = ETModel.Game.Scene.GetComponent<ResourcesComponent>(); await resourcesComponent.LoadBundleAsync($"unit.unity3d"); // 加载场景资源 await ETModel.Game.Scene.GetComponent<ResourcesComponent>().LoadBundleAsync("map.unity3d"); // 切换到map场景 using (SceneChangeComponent sceneChangeComponent = ETModel.Game.Scene.AddComponent<SceneChangeComponent>()) { await sceneChangeComponent.ChangeSceneAsync(SceneType.Map); } G2C_EnterMap g2CEnterMap = await ETModel.SessionComponent.Instance.Session.Call(new C2G_EnterMap()) as G2C_EnterMap; PlayerComponent.Instance.MyPlayer.UnitId = g2CEnterMap.UnitId; Game.Scene.AddComponent<OperaComponent>(); Game.Scene.GetComponent<UIComponent>().Remove(UIType.UILobby); } catch (Exception e) { Log.Error(e); } } } }
29.53211
172
0.716372
[ "MIT" ]
594270461/LandlordsCore
Unity/Assets/Hotfix/UI/UILobby/Component/UILobbyComponent.cs
3,293
C#
using System.ComponentModel.DataAnnotations; using System.Text.Json.Serialization; namespace fcu_ucan.Models.User { public class UserViewModel { [JsonPropertyName("Id")] [Display(Name = "使用者識別碼")] public string Id { get; set; } [JsonPropertyName("UserName")] [Display(Name = "使用者名稱")] public string UserName { get; set; } [JsonPropertyName("Email")] [Display(Name = "電子郵件")] public string Email { get; set; } [JsonPropertyName("EmailConfirmed")] [Display(Name = "電子郵件驗證")] public bool EmailConfirmed { get; set; } [JsonPropertyName("PhoneNumber")] [Display(Name = "手機號碼")] public string PhoneNumber { get; set; } [JsonPropertyName("PhoneNumberConfirmed")] [Display(Name = "手機號碼驗證")] public bool PhoneNumberConfirmed { get; set; } [JsonPropertyName("IsEnable")] [Display(Name = "啟用帳戶")] public bool IsEnable { get; set; } [JsonPropertyName("IsRecorder")] [Display(Name = "管理日誌權限")] public bool IsRecorder { get; set; } [JsonPropertyName("IsMember")] [Display(Name = "管理成員權限")] public bool IsMember { get; set; } [JsonPropertyName("IsUser")] [Display(Name = "管理使用者權限")] public bool IsUser { get; set; } [JsonPropertyName("IsUCAN")] [Display(Name = "UCAN 登入權限")] public bool IsUCAN { get; set; } } }
29.923077
54
0.553985
[ "MIT" ]
fcu-ssc/fcu-ucan
fcu-ucan/Models/User/UserViewModel.cs
1,674
C#
using System; using System.Collections.Generic; using System.Linq; using MediatR; using SFA.DAS.Payments.DCFS.Domain; using SFA.DAS.Provider.Events.DataLock.Domain; using SFA.DAS.Provider.Events.DataLock.Domain.Data; namespace SFA.DAS.Provider.Events.DataLock.Application.GetCurrentProviderEvents { public class GetCurrentProviderEventsHandler : IRequestHandler<GetCurrentProviderEventsRequest, GetCurrentProviderEventsResponse> { private readonly IDataLockEventDataRepository _dataLockEventDataRepository; private readonly string _academicYear; private readonly EventSource _eventsSource; public GetCurrentProviderEventsHandler(IDataLockEventDataRepository dataLockEventDataRepository, string yearOfCollection, EventSource eventsSource) { _dataLockEventDataRepository = dataLockEventDataRepository; _academicYear = yearOfCollection; _eventsSource = eventsSource; } public GetCurrentProviderEventsResponse Handle(GetCurrentProviderEventsRequest message) { try { var currentEvents = new List<DataLockEvent>(); var entities = _dataLockEventDataRepository.GetCurrentEvents(message.Ukprn); if (entities != null) { DataLockEvent currentEvent = null; var errors = new List<DataLockEventError>(); var periods = new List<DataLockEventPeriod>(); var commitmentVersions = new List<DataLockEventCommitmentVersion>(); foreach (var entity in entities) { if (currentEvent == null || entity.LearnRefNumber != currentEvent.LearnRefnumber || entity.PriceEpisodeIdentifier != currentEvent.PriceEpisodeIdentifier || entity.CommitmentId != currentEvent.CommitmentId) { if (currentEvent != null) { AddEventToList(currentEvent, errors, periods, commitmentVersions, currentEvents); } errors.Clear(); periods.Clear(); commitmentVersions.Clear(); currentEvent = new DataLockEvent { IlrFileName = entity.IlrFilename, SubmittedDateTime = entity.SubmittedTime, AcademicYear = _academicYear, Ukprn = entity.Ukprn, Uln = entity.Uln, LearnRefnumber = entity.LearnRefNumber, AimSeqNumber = entity.AimSeqNumber, PriceEpisodeIdentifier = entity.PriceEpisodeIdentifier, CommitmentId = entity.CommitmentId, EmployerAccountId = entity.EmployerAccountId, EventSource = _eventsSource, HasErrors = !entity.IsSuccess, IlrStartDate = entity.IlrStartDate, IlrStandardCode = entity.IlrStandardCode, IlrProgrammeType = entity.IlrProgrammeType, IlrFrameworkCode = entity.IlrFrameworkCode, IlrPathwayCode = entity.IlrPathwayCode, IlrTrainingPrice = entity.IlrTrainingPrice, IlrEndpointAssessorPrice = entity.IlrEndpointAssessorPrice, IlrPriceEffectiveFromDate = entity.IlrPriceEffectiveFromDate, IlrPriceEffectiveToDate = entity.IlrPriceEffectiveToDate }; } var collectionPeriod = GetCollectionPeriod(entity.Period); if (!periods.Any(p => p.CollectionPeriod.Month == collectionPeriod.Month && p.CollectionPeriod.Year == collectionPeriod.Year && (int)p.TransactionTypesFlag == entity.TransactionTypesFlag)) { periods.Add(new DataLockEventPeriod { CollectionPeriod = collectionPeriod, CommitmentVersion = entity.CommitmentVersionId, IsPayable = entity.Payable, TransactionType = (TransactionType)entity.TransactionType, TransactionTypesFlag = (TransactionTypeGroup)entity.TransactionTypesFlag }); } if (entity.RuleId != null && !errors.Any(e => e.ErrorCode == entity.RuleId)) { errors.Add(new DataLockEventError { ErrorCode = entity.RuleId, SystemDescription = GetErrorDescription(entity.RuleId) }); } if (!commitmentVersions.Any(v => v.CommitmentVersion == entity.CommitmentVersionId)) { commitmentVersions.Add(new DataLockEventCommitmentVersion { CommitmentVersion = entity.CommitmentVersionId, CommitmentStandardCode = entity.CommitmentStandardCode, CommitmentProgrammeType = entity.CommitmentProgrammeType, CommitmentFrameworkCode = entity.CommitmentFrameworkCode, CommitmentPathwayCode = entity.CommitmentPathwayCode, CommitmentStartDate = entity.CommitmentStartDate, CommitmentNegotiatedPrice = entity.CommitmentNegotiatedPrice, CommitmentEffectiveDate = entity.CommitmentEffectiveDate }); } } if (currentEvent != null) { AddEventToList(currentEvent, errors, periods, commitmentVersions, currentEvents); } } return new GetCurrentProviderEventsResponse { IsValid = true, Items = currentEvents.ToArray() }; } catch (Exception ex) { return new GetCurrentProviderEventsResponse { IsValid = false, Exception = ex }; } } private string GetErrorDescription(string errorCode) { switch (errorCode) { case "DLOCK_01": return "No matching record found in an employer digital account for the UKPRN"; case "DLOCK_02": return "No matching record found in the employer digital account for the ULN"; case "DLOCK_03": return "No matching record found in the employer digital account for the standard code"; case "DLOCK_04": return "No matching record found in the employer digital account for the framework code"; case "DLOCK_05": return "No matching record found in the employer digital account for the programme type"; case "DLOCK_06": return "No matching record found in the employer digital account for the pathway code"; case "DLOCK_07": return "No matching record found in the employer digital account for the negotiated cost of training"; case "DLOCK_08": return "Multiple matching records found in the employer digital account"; case "DLOCK_09": return "The start date for this negotiated price is before the corresponding price start date in the employer digital account"; case "DLOCK_10": return "The employer has stopped payments for this apprentice"; case "DLOCK_11": return "The employer is not currently a levy payer"; default: return errorCode; } } private CollectionPeriod GetCollectionPeriod(int period) { var month = 0; var year = 2000; var name = string.Empty; switch (period) { case 1: name = "R01"; month = 8; year += int.Parse(_academicYear.Substring(0, 2)); break; case 2: name = "R02"; month = 9; year += int.Parse(_academicYear.Substring(0, 2)); break; case 3: name = "R03"; month = 10; year += int.Parse(_academicYear.Substring(0, 2)); break; case 4: name = "R04"; month = 11; year += int.Parse(_academicYear.Substring(0, 2)); break; case 5: name = "R05"; month = 12; year += int.Parse(_academicYear.Substring(0, 2)); break; case 6: name = "R06"; month = 1; year += int.Parse(_academicYear.Substring(2, 2)); break; case 7: name = "R07"; month = 2; year += int.Parse(_academicYear.Substring(2, 2)); break; case 8: name = "R08"; month = 3; year += int.Parse(_academicYear.Substring(2, 2)); break; case 9: name = "R09"; month = 4; year += int.Parse(_academicYear.Substring(2, 2)); break; case 10: name = "R10"; month = 5; year += int.Parse(_academicYear.Substring(2, 2)); break; case 11: name = "R11"; month = 6; year += int.Parse(_academicYear.Substring(2, 2)); break; case 12: name = "R12"; month = 7; year += int.Parse(_academicYear.Substring(2, 2)); break; } return new CollectionPeriod { Name = $"{_academicYear}-{name}", Month = month, Year = year }; } private void AddEventToList(DataLockEvent currentEvent, List<DataLockEventError> errors, List<DataLockEventPeriod> periods, List<DataLockEventCommitmentVersion> commitmentVersions, List<DataLockEvent> currentEvents) { var existingEvent = currentEvents.FirstOrDefault(x => x.LearnRefnumber == currentEvent.LearnRefnumber && x.PriceEpisodeIdentifier == currentEvent.PriceEpisodeIdentifier && x.CommitmentId == currentEvent.CommitmentId); if (existingEvent == null) { currentEvent.Errors = errors.ToArray(); currentEvent.Periods = periods.ToArray(); currentEvent.CommitmentVersions = commitmentVersions.ToArray(); currentEvents.Add(currentEvent); } else { var existingErrors = existingEvent.Errors.ToList(); existingErrors.AddRange(errors); existingEvent.Errors = existingErrors.GroupBy(g => g.ErrorCode).Select(x => x.FirstOrDefault()).ToArray(); var existingPeriods = existingEvent.Periods.ToList(); existingPeriods.AddRange(periods); existingEvent.Periods = existingPeriods.ToArray(); var existingCommitments = existingEvent.CommitmentVersions.ToList(); existingCommitments.AddRange(commitmentVersions); existingEvent.CommitmentVersions = existingCommitments.ToArray(); } } } }
46.907143
188
0.485229
[ "MIT" ]
SkillsFundingAgency/das-providerpayments
src/SharedPipelineComponents/DataLockEvents/SFA.DAS.Provider.Events.DataLock/Application/GetCurrentProviderEvents/GetCurrentProviderEventsHandler.cs
13,136
C#
using AElf.Contracts.Consensus.AEDPoS; using Google.Protobuf; namespace AElf.Kernel.Consensus.AEDPoS { public static class ByteStringExtensions { internal static AElfConsensusHint ToAElfConsensusHint(this ByteString byteString) { var hint = new AElfConsensusHint(); hint.MergeFrom(byteString); return hint; } } }
25.666667
89
0.667532
[ "MIT" ]
IamWenboZhang/AElf
src/AElf.Kernel.Consensus.AEDPoS/Extensions/ByteStringExtensions.cs
385
C#
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Apache.Arrow.Ipc; using System; using System.IO; using System.Threading.Tasks; using Xunit; namespace Apache.Arrow.Tests { public class ArrowFileWriterTests { [Fact] public void Ctor_LeaveOpenDefault_StreamClosedOnDispose() { RecordBatch originalBatch = TestData.CreateSampleRecordBatch(length: 100); var stream = new MemoryStream(); new ArrowFileWriter(stream, originalBatch.Schema).Dispose(); Assert.Throws<ObjectDisposedException>(() => stream.Position); } [Fact] public void Ctor_LeaveOpenFalse_StreamClosedOnDispose() { RecordBatch originalBatch = TestData.CreateSampleRecordBatch(length: 100); var stream = new MemoryStream(); new ArrowFileWriter(stream, originalBatch.Schema, leaveOpen: false).Dispose(); Assert.Throws<ObjectDisposedException>(() => stream.Position); } [Fact] public void Ctor_LeaveOpenTrue_StreamValidOnDispose() { RecordBatch originalBatch = TestData.CreateSampleRecordBatch(length: 100); var stream = new MemoryStream(); new ArrowFileWriter(stream, originalBatch.Schema, leaveOpen: true).Dispose(); Assert.Equal(0, stream.Position); } /// <summary> /// Tests that writing an arrow file will always align the Block lengths /// to 8 bytes. There are asserts in both the reader and writer which will fail /// if this isn't the case. /// </summary> /// <returns></returns> [Fact] public async Task WritesFooterAlignedMulitpleOf8() { RecordBatch originalBatch = TestData.CreateSampleRecordBatch(length: 100); var stream = new MemoryStream(); var writer = new ArrowFileWriter( stream, originalBatch.Schema, leaveOpen: true, // use WriteLegacyIpcFormat, which only uses a 4-byte length prefix // which causes the length prefix to not be 8-byte aligned by default new IpcOptions() { WriteLegacyIpcFormat = true }); writer.WriteRecordBatch(originalBatch); writer.WriteEnd(); stream.Position = 0; await ValidateRecordBatchFile(stream, originalBatch); } /// <summary> /// Tests that writing an arrow file will always align the Block lengths /// to 8 bytes. There are asserts in both the reader and writer which will fail /// if this isn't the case. /// </summary> /// <returns></returns> [Fact] public async Task WritesFooterAlignedMulitpleOf8Async() { RecordBatch originalBatch = TestData.CreateSampleRecordBatch(length: 100); var stream = new MemoryStream(); var writer = new ArrowFileWriter( stream, originalBatch.Schema, leaveOpen: true, // use WriteLegacyIpcFormat, which only uses a 4-byte length prefix // which causes the length prefix to not be 8-byte aligned by default new IpcOptions() { WriteLegacyIpcFormat = true }); await writer.WriteRecordBatchAsync(originalBatch); await writer.WriteEndAsync(); stream.Position = 0; await ValidateRecordBatchFile(stream, originalBatch); } private async Task ValidateRecordBatchFile(Stream stream, RecordBatch recordBatch) { var reader = new ArrowFileReader(stream); int count = await reader.RecordBatchCountAsync(); Assert.Equal(1, count); RecordBatch readBatch = await reader.ReadRecordBatchAsync(0); ArrowReaderVerifier.CompareBatches(recordBatch, readBatch); } } }
39.546218
90
0.638334
[ "Apache-2.0" ]
AI-ML-Projects/arrow
csharp/test/Apache.Arrow.Tests/ArrowFileWriterTests.cs
4,708
C#
namespace android.view { [global::MonoJavaBridge.JavaClass()] public partial class TouchDelegate : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static TouchDelegate() { InitJNI(); } protected TouchDelegate(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onTouchEvent9089; public virtual bool onTouchEvent(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.TouchDelegate._onTouchEvent9089, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.TouchDelegate.staticClass, global::android.view.TouchDelegate._onTouchEvent9089, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _TouchDelegate9090; public TouchDelegate(android.graphics.Rect arg0, android.view.View arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.TouchDelegate.staticClass, global::android.view.TouchDelegate._TouchDelegate9090, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } public static int ABOVE { get { return 1; } } public static int BELOW { get { return 2; } } public static int TO_LEFT { get { return 4; } } public static int TO_RIGHT { get { return 8; } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.TouchDelegate.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/TouchDelegate")); global::android.view.TouchDelegate._onTouchEvent9089 = @__env.GetMethodIDNoThrow(global::android.view.TouchDelegate.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z"); global::android.view.TouchDelegate._TouchDelegate9090 = @__env.GetMethodIDNoThrow(global::android.view.TouchDelegate.staticClass, "<init>", "(Landroid/graphics/Rect;Landroid/view/View;)V"); } } }
36.477612
274
0.756956
[ "MIT" ]
beachmiles/androidmono
jni/MonoJavaBridge/android/generated/android/view/TouchDelegate.cs
2,444
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.ContractsLight; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using BuildXL.Utilities; using JetBrains.Annotations; using BuildXL.Utilities.Configuration; using TypeScript.Net.Binding; using TypeScript.Net.DScript; using TypeScript.Net.Types; namespace BuildXL.FrontEnd.Workspaces.Core { /// <summary> /// Turns module definitions into parsed modules, by parsing and local binding module definition specs. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "CancellationTokenSource could be left without disposing it.")] public class ModuleParsingQueue { private readonly ConcurrentDictionary<ModuleDescriptor, Possible<IWorkspaceModuleResolver>> m_moduleResolvers = new ConcurrentDictionary<ModuleDescriptor, Possible<IWorkspaceModuleResolver>>(); // Incomplete modules, meaning that some of their specs are still queued to be parsed. private readonly ConcurrentDictionary<ModuleDescriptor, ModuleUnderConstruction> m_modulesToBeParsed; // Modules which are complete, meaning that all their specs are already parsed (or failed at parsing) private readonly ConcurrentDictionary<ModuleDescriptor, ParsedModule> m_modulesAlreadyParsed; // The workspace provider to be used for finding spec dependencies private readonly WorkspaceProvider m_workspaceProvider; // The collector that is used for identifying what is a module reference in a spec private readonly IModuleReferenceResolver m_moduleReferenceResolver; // A designated prelude module. May be null if there is not one [CanBeNull] private readonly ModuleDefinition m_designatedPrelude; // Special module that has all configuration files. private readonly ParsedModule m_configurationModule; // Specs to be parsed queue private readonly ActionBlock<SpecWithOwningModule> m_parseQueue; // Spec to be bound queue private readonly ActionBlock<ParsedSpecWithOwningModule> m_bindQueue; // Options for the queue private readonly ModuleParsingQueueOptions m_queueOptions; // Failures found when parsing private readonly ConcurrentQueue<Failure> m_failures; private readonly CancellationTokenSource m_cancellationTokenSource = new CancellationTokenSource(); [NotNull] private readonly ParsingOptions m_parsingOptions; // Set to true when no more module may come. private volatile bool m_enqueingComplete = false; private readonly WorkspaceConfiguration m_workspaceConfiguration; /// <summary> /// Degree of parallelism used by the parsing queue. /// </summary> protected readonly int DegreeOfParallelism; /// <nodoc /> protected CancellationTokenRegistration cancellationTokenChain; /// <summary> /// Creates a module parsing queue. The queue options are specified by the provided queueOptions. /// </summary> public ModuleParsingQueue( [NotNull] WorkspaceProvider workspaceProvider, WorkspaceConfiguration workspaceConfiguration, IModuleReferenceResolver moduleReferenceResolver, ModuleDefinition designatedPrelude, ParsedModule configurationModule) : this(workspaceProvider, workspaceConfiguration, moduleReferenceResolver, designatedPrelude, configurationModule, new ConcurrentDictionary<ModuleDescriptor, ParsedModule>(), new ConcurrentQueue<Failure>()) { Contract.Requires(moduleReferenceResolver != null); } private ModuleParsingQueue( WorkspaceProvider workspaceProvider, WorkspaceConfiguration workspaceConfiguration, IModuleReferenceResolver moduleReferenceResolver, ModuleDefinition designatedPrelude, ParsedModule configurationModule, ConcurrentDictionary<ModuleDescriptor, ParsedModule> alreadyParsedModules, ConcurrentQueue<Failure> failures, bool preserveTrivias = false) { Contract.Requires(workspaceProvider != null); Contract.Requires(workspaceConfiguration != null); Contract.Requires(moduleReferenceResolver != null); Contract.Requires(alreadyParsedModules != null, "alreadyParsedModules != null"); Contract.Requires(failures != null, "failures != null"); m_modulesToBeParsed = new ConcurrentDictionary<ModuleDescriptor, ModuleUnderConstruction>(); m_modulesAlreadyParsed = alreadyParsedModules; m_failures = failures; m_workspaceProvider = workspaceProvider; m_moduleReferenceResolver = moduleReferenceResolver; m_designatedPrelude = designatedPrelude; m_configurationModule = configurationModule; m_workspaceConfiguration = workspaceConfiguration; m_parsingOptions = workspaceConfiguration.ParsingOptions; if (preserveTrivias) { m_parsingOptions = (m_parsingOptions ?? ParsingOptions.DefaultParsingOptions).WithTrivia(true); } DegreeOfParallelism = workspaceConfiguration.MaxDegreeOfParallelismForParsing; // WARNING: this is extremely subtle. // We need to keep a 'registration token' from the chained operation we are doing next to avoid memory leak. // The instance of this class stores the reference to key front-end objects, like resolvers, // that keeps the entire front-end in memory. // CancellationToken.Register registers the call back, that lead to a closure allocation of the current instance. // And this means that the lifetime of this instance is coupled to the lifetime of the the workspaceConfiguration.CancellationToken which is global. // This means that if we won't dispose the resistration we'll keep the entire front-end in memory for the entire app life time. cancellationTokenChain = workspaceConfiguration.CancellationToken.Register(() => m_cancellationTokenSource.Cancel()); m_queueOptions = new ModuleParsingQueueOptions() { CancelOnFirstFailure = workspaceConfiguration.CancelOnFirstFailure, MaxDegreeOfParallelism = DegreeOfParallelism, CancellationToken = m_cancellationTokenSource.Token, }; m_parseQueue = new ActionBlock<SpecWithOwningModule>(ProcessQueuedItemForParsing, m_queueOptions); Action<ParsedSpecWithOwningModule> action = ProcessQueueItemForBinding; m_bindQueue = new ActionBlock<ParsedSpecWithOwningModule>(action, m_queueOptions); } /// <summary> /// Creates a special version of the parsing queue required for paring/binding spec files for fingerprint computation. /// </summary> public static ModuleParsingQueue CraeteFingerprintComputationQueue( WorkspaceProvider workspaceProvider, WorkspaceConfiguration workspaceConfiguration, IModuleReferenceResolver moduleReferenceResolver) { return new FingerprintComputationParsingQueue(workspaceProvider, workspaceConfiguration, moduleReferenceResolver); } /// <summary> /// Creates a parsing queue for parsing specs in a regular BuildXL invocation. /// </summary> public static ModuleParsingQueue Create( [NotNull]WorkspaceProvider workspaceProvider, [NotNull]WorkspaceConfiguration workspaceConfiguration, [NotNull]IModuleReferenceResolver moduleReferenceResolver, [CanBeNull]ModuleDefinition designatedPrelude, [CanBeNull]ParsedModule configurationModule) { Contract.Requires(workspaceProvider != null); return new ModuleParsingQueue( workspaceProvider, workspaceConfiguration, moduleReferenceResolver, designatedPrelude, configurationModule); } /// <summary> /// Creates a queue that starts with some already parsed module and a pending module under construction /// </summary> public static ModuleParsingQueue CreateIncrementalQueue( WorkspaceProvider workspaceProvider, WorkspaceConfiguration workspaceConfiguration, IModuleReferenceResolver moduleReferenceResolver, ModuleDefinition designatedPrelude, ParsedModule configurationModule, IEnumerable<ParsedModule> parsedModules, IEnumerable<Failure> failures) { Contract.Requires(workspaceProvider != null); Contract.Requires(moduleReferenceResolver != null); Contract.Requires(parsedModules != null); Contract.Requires(failures != null); var parsedModulesDictionary = new ConcurrentDictionary<ModuleDescriptor, ParsedModule>(parsedModules.Select(parsedModule => new KeyValuePair<ModuleDescriptor, ParsedModule>(parsedModule.Descriptor, parsedModule))); var failureBag = new ConcurrentQueue<Failure>(failures); // For IDE mode it is very crucial to preserve trivias. For instance, without it, there is no way to check that the current position is inside a comment. var queue = new ModuleParsingQueue( workspaceProvider, workspaceConfiguration, moduleReferenceResolver, designatedPrelude, configurationModule, parsedModulesDictionary, failureBag, preserveTrivias: true); return queue; } /// <summary> /// Process a partially constructed module /// </summary> public Task<Workspace> ProcessIncrementalAsync(ModuleUnderConstruction moduleUnderConstruction) { Contract.Requires(moduleUnderConstruction != null); Contract.Requires(!moduleUnderConstruction.IsModuleComplete()); // Add the module to be parsed as is var definition = moduleUnderConstruction.Definition; Contract.Assert(!m_modulesToBeParsed.ContainsKey(definition.Descriptor)); m_modulesToBeParsed[definition.Descriptor] = moduleUnderConstruction; // Now schedule all the pending specs // It is extremely important to get specs in order to preserve determinism. var pendingSpecs = moduleUnderConstruction.GetPendingSpecPathsOrderedByPath(m_workspaceProvider.PathTable); foreach (var spec in pendingSpecs) { m_parseQueue.Post(new SpecWithOwningModule(spec.path, definition)); } return EnqueuingFinishedAndWaitForCompletion(); } /// <nodoc /> public virtual Possible<ISourceFile>[] ParseAndBindSpecs(SpecWithOwningModule[] specs) { throw new NotImplementedException("Please use 'FingerprintComputationParsingQueue'."); } /// <nodoc /> public Task<Workspace> ProcessAsync(IEnumerable<ModuleDefinition> moduleDefinitions) { Contract.Requires(moduleDefinitions != null); // Add all requested modules to the parsing queue foreach (var moduleDefinition in moduleDefinitions) { EnqueueModuleForParsing(moduleDefinition); } return EnqueuingFinishedAndWaitForCompletion(); } private async Task<Workspace> EnqueuingFinishedAndWaitForCompletion() { // No more new module definition may be added for processing EnqueuingCompleted(); try { await m_parseQueue.Completion; } catch (TaskCanceledException) { // Expected. This means that at least one task failed parsing } // Parsing is complete. Just need to wait for pending items to finish binding. m_bindQueue.Complete(); try { await m_bindQueue.Completion; } catch (TaskCanceledException) { // Expected. This means that at least one task failed binding } // Need to check if the queue reparsed prelude or configuration module. ParsedModule prelude = GetProcessedPreludeOrDefault(); ParsedModule configurationModule = GetProcessedConfigurationModuleOrDefault(); // The workspace is ready to be constructed. So at this point we can run some workspace-level validations. var workspaceFailures = WorkspaceValidator.ValidateParsedModules(m_modulesAlreadyParsed.Values, m_workspaceProvider.PathTable); // Create the result. Observe that if the task is cancelled, we don't propagate it // but reflect it in the result. return new Workspace( m_workspaceProvider, m_workspaceConfiguration, GetAllSourceModules(prelude, configurationModule), m_failures.Union(workspaceFailures), preludeModule: prelude, configurationModule: configurationModule); } private IEnumerable<ParsedModule> GetAllSourceModules(ParsedModule prelude, ParsedModule configurationModule) { var result = new HashSet<ParsedModule>(m_modulesAlreadyParsed.Values); if (prelude != null) { result.Remove(prelude); } if (configurationModule != null) { result.Remove(configurationModule); } return result; } /// <summary> /// Enqueues all the specs of <param name="moduleDefinition"/> for parsing. Actual enqueuing only happens if the module has not been /// completed yet, nor already scheduled. /// </summary> /// <remarks> /// This method can only be called before calling <see cref="EnqueuingCompleted"/> /// </remarks> private void EnqueueModuleForParsing(ModuleDefinition moduleDefinition) { if (m_modulesAlreadyParsed.ContainsKey(moduleDefinition.Descriptor) || m_modulesToBeParsed.ContainsKey(moduleDefinition.Descriptor)) { return; } // If the module has no specs, it is already parsed if (moduleDefinition.Specs.Count == 0) { m_modulesAlreadyParsed[moduleDefinition.Descriptor] = new ParsedModule(moduleDefinition); return; } // Create a module with no specs and add it to the modules-to-be-parsed collection var module = new ModuleUnderConstruction(moduleDefinition); if (!m_modulesToBeParsed.TryAdd(moduleDefinition.Descriptor, module)) { // If the module has already been added by someone else, we just declare the enqueue successful return; } // Now schedule all the specs foreach (var spec in moduleDefinition.Specs) { // Constructor of this class ensures that queue is unbounded. // In cases of bounded queue, posting to a queue can lead to a deadlock // because ActionBlock infrastructure removes item from the queue // only when call back that processes that element finishes its execution. // But in this case, callback can add item to the queue which will lead to a deadlock // when queue is full. m_parseQueue.Post(new SpecWithOwningModule(spec, moduleDefinition)); } } /// <summary> /// Notifies that no new modules will be scheduled for parsing /// </summary> private void EnqueuingCompleted() { m_enqueingComplete = true; // If we are already done parsing everything enqueued so far, we flag the queue as completed. // This is very unlikely, but may be possible. if (m_modulesToBeParsed.IsEmpty) { cancellationTokenChain.Dispose(); m_parseQueue.Complete(); } } /// <summary> /// Parses a <param name="specWithOwningModule"/> and adds it to the set of modules being constructed. /// Additionally, it finds out if the spec has external module dependencies and schedule those for parsing if needed. /// </summary> private async Task ProcessQueuedItemForParsing(SpecWithOwningModule specWithOwningModule) { if (!m_modulesToBeParsed.TryGetValue(specWithOwningModule.OwningModule.Descriptor, out ModuleUnderConstruction owningModule)) { // If the module is no longer under construction, that means that somebody else already completed it // so we just return return; } try { // Tries to parse the spec var maybeParsedFile = await TryParseSpec(specWithOwningModule); ISourceFile parsedFile; if (!maybeParsedFile.Succeeded) { ReportFailureAndCancelParsingIfNeeded(maybeParsedFile.Failure); // If there is a failure, then two things are possible: // 1) The spec was parsed but it contains parsing errors. In this case we add it to the module anyway // 2) Another type of failure happened (e.g. the module resolver for that spec could not be found). In this case // we notify that a failure happened so we can keep track of when a module under construction is complete var parsingFailure = maybeParsedFile.Failure as ParsingFailure; if (parsingFailure != null) { parsedFile = parsingFailure.SourceFile; } else { owningModule.ParsingFailed(); return; } } else { parsedFile = maybeParsedFile.Result; } // We enqueue the spec external dependencies and update the parsed file external dependencies var enqueueResult = await EnqueueSpecDependenciesIfAny(owningModule, parsedFile); if (!enqueueResult.Succeeded) { ReportFailureAndCancelParsingIfNeeded(enqueueResult.Failure); } // Now that we are done parsing the spec, we add it to the module-to-be // It is important to add the file to the module after scheduling dependencies, since scheduling // also updates the source file external references. Otherwise, some other thread // may complete the module and update all its internal references at the same time, which // is not thread safe var addResult = owningModule.AddParsedSpec(specWithOwningModule.Path, parsedFile); if (addResult != ModuleUnderConstruction.AddParsedSpecResult.SpecIsCandidateForInjectingQualifiers) { ScheduleSourceFileBinding(new ParsedSpecWithOwningModule(parsedFile: parsedFile, owningModule: specWithOwningModule.OwningModule)); } } finally { // If the module is completed and there are no more modules to complete, we are done CheckForCompletionAndSignalQueueIfDone(owningModule); } } private void ScheduleSourceFileBinding(ParsedSpecWithOwningModule parsedSpecWithOwningModule) { var parsedFile = parsedSpecWithOwningModule.ParsedFile; // We can safely schedule binding for the spec. // Don't need to bind if parse errors are present and we cancel on failure. if (parsedFile.ParseDiagnostics.Count == 0 || !m_queueOptions.CancelOnFirstFailure) { m_bindQueue.Post(parsedSpecWithOwningModule); } } /// <summary> /// Adds the failure to the set of failures and, if early bail out is specified, sends a cancellation /// </summary> private void ReportFailureAndCancelParsingIfNeeded(params Failure[] failures) { foreach (var failure in failures) { m_failures.Enqueue(failure); } if (m_queueOptions.CancelOnFirstFailure) { m_cancellationTokenSource.Cancel(); } } private void CheckForCompletionAndSignalQueueIfDone(ModuleUnderConstruction owningModule) { // Now that all dependencies of the owning module have been scheduled, // we check if the module for which we just added a spec is complete if (owningModule.IsModuleFirstTimeComplete()) { var moduleId = owningModule.Definition.Descriptor; // We create a parsed module out of a module under construction. // Observe many threads can try to create the same completed module. But that's ok, the method is thread safe // and always return the same instance. // It is important to notice that we should add this module to m_modulesAlreadyParsed before removing it from // m_modulesToBeParsed. This is so no producer will think the module is not there at any point in time (which // would cause the producer to try to schedule that module again) var success = owningModule.TryCreateCompletedModule(m_moduleReferenceResolver, m_workspaceConfiguration, m_queueOptions.CancelOnFirstFailure, out ParsedModule module, out Failure[] failures); if (success) { m_modulesAlreadyParsed[moduleId] = module; // Now the module is completed and we can bind the changed file as well. var modifiedSourceFile = owningModule.GetSourceFileForInjectingQualifiers(); if (modifiedSourceFile != null) { ScheduleSourceFileBinding(new ParsedSpecWithOwningModule(parsedFile: modifiedSourceFile, owningModule: owningModule.Definition)); } } else { // This is a bogus module we put here when failures occurr. This guarantees that modules // are not scheduled more than once (detailed reasons above). When there are failures // we want to report them only once, so leave that to whoever successfully removes // the module from m_modulesToBeParsed to report them. // Observe that this (empty) module will be left in case of failures, but that's not // likely to be a problem m_modulesAlreadyParsed[moduleId] = new ParsedModule(owningModule.Definition, hasFailures: true); } // If removing fails, that means that somebody else successfully removed the module, so we do nothing // If removing succeeds, we are responsible for signaling if the queue is done if (m_modulesToBeParsed.TryRemove(moduleId, out ModuleUnderConstruction dummy)) { if (!success) { ReportFailureAndCancelParsingIfNeeded(failures); } // Now we decide if we are done with parsing the transitive closure. // This happens when the set of modules to be parsed is empty // and EnqueuingCompleted has been called. // Observe that it is important that we first add all dependencies to be parsed // before removing a completed module. This ensures // that if anybody sees an empty collection, we are done for sure if (m_modulesToBeParsed.IsEmpty && m_enqueingComplete) { cancellationTokenChain.Dispose(); m_parseQueue.Complete(); } } } } /// <summary> /// Discover external module dependencies and enqueue them if necessary /// </summary> /// <remarks> /// The parsed file gets updated with the external module references as they are discovered. /// </remarks> private async Task<Possible<bool>> EnqueueSpecDependenciesIfAny(ModuleUnderConstruction owningModule, ISourceFile parsedFile) { var allSpecifiers = m_moduleReferenceResolver.GetExternalModuleReferences(parsedFile); foreach (var moduleName in allSpecifiers) { // Get the module definition from the resolver and enqueue it. Since we don't deal with versions yet at the // import level, there should be exactly one module definition with that name var maybeModuleDefinition = await m_workspaceProvider.FindUniqueModuleDefinitionWithName(moduleName); if (!maybeModuleDefinition.Succeeded) { return maybeModuleDefinition.Failure; } var moduleDefinition = maybeModuleDefinition.Result; // Since the referenced module has been found, we update the parsed file with the reference. This // information is later used by the checker. if (!m_moduleReferenceResolver.TryUpdateExternalModuleReference(parsedFile, moduleDefinition, out var failure)) { return failure; } // Update the owning module advertising that the found module was referenced owningModule.AddReferencedModule(moduleDefinition.Descriptor, moduleName.ReferencedFrom); EnqueueModuleForParsing(moduleDefinition); } return true; } private Possible<IWorkspaceModuleResolver> GetOrFindModuleResolver(AbsolutePath pathToSpec, ModuleDescriptor descriptor) { if (!m_moduleResolvers.TryGetValue(descriptor, out Possible<IWorkspaceModuleResolver> result)) { result = m_workspaceProvider.FindResolverAsync(pathToSpec).GetAwaiter().GetResult(); m_moduleResolvers.TryAdd(descriptor, result); } return result; } /// <nodoc /> protected async Task<Possible<ISourceFile>> TryParseSpec(SpecWithOwningModule specWithOwningModule) { var pathToSpec = specWithOwningModule.Path; var maybeResolver = GetOrFindModuleResolver(pathToSpec, specWithOwningModule.OwningModule.Descriptor); // TODO: if the spec we are parsing belongs to the prelude, we override the automatic export namespace configuration for that spec to false. This is a temporary hack! // Rationale: A top-level export is one of the ways to split internal vs external modules. With this DScript-specific // change around automatic namespace export, we've lost the ability to distinguish this as soon as an // inner member is exported. This means that the DS prelude is identified as an external module and therefore not merged. // A better solution: turn the DScript prelude into a true external module, where all declarations are exported. // but merge all those in the checker (where the prelude is nicely identified as such) as globals, so there is no // need to explicitly import the prelude anywhere (checked this already, and it works). Not doing it now because // that would mean a breaking change in the prelude that the typescript-based type checker won't be able to deal with // today. // If we're processing the prelude, then we need to use prelude-specific parsing options. // withQualifierFunction needs to be generated when the owning module is a V2 one // TODO: consider splitting the parsing options into UserConfigurableParsingOptions and ParsingOptions // The first one is the one that should be exposed beyond this class var parsingOptions = specWithOwningModule.OwningModule.Descriptor == m_designatedPrelude?.Descriptor ? ParsingOptions.GetPreludeParsingOptions(m_parsingOptions.EscapeIdentifiers) : m_parsingOptions .WithFailOnMissingSemicolons(true) .WithGenerateWithQualifierFunctionForEveryNamespace(specWithOwningModule.OwningModule.ResolutionSemantics == NameResolutionSemantics.ImplicitProjectReferences); // Intentionally switched from monadic syntax (with maybe.Then) to avoid additional closure allocations. if (!maybeResolver.Succeeded) { return maybeResolver.Failure; } var maybeParsedFile = await maybeResolver.Result.TryParseAsync(pathToSpec, specWithOwningModule.OwningModule.ModuleConfigFile, parsingOptions); // Check if there are any diagnostics reported by the parser if (!maybeParsedFile.Succeeded) { return maybeParsedFile.Failure; } var parsedFile = maybeParsedFile.Result; return parsedFile.ParseDiagnostics.Count != 0 ? new ParsingFailure(specWithOwningModule.OwningModuleDescriptor, parsedFile) : new Possible<ISourceFile>(parsedFile); } private ParsedModule GetProcessedPreludeOrDefault() { // If there is a designated prelude module, we identify it for the workspace ParsedModule prelude = null; if (m_designatedPrelude != null) { m_modulesAlreadyParsed.TryGetValue(m_designatedPrelude.Descriptor, out prelude); } return prelude; } private ParsedModule GetProcessedConfigurationModuleOrDefault() { ParsedModule result = m_configurationModule; if (m_configurationModule != null) { if (m_modulesAlreadyParsed.TryGetValue(m_configurationModule.Descriptor, out var parsedConfigurationModule)) { result = parsedConfigurationModule; } } return result; } private void ProcessQueueItemForBinding(ParsedSpecWithOwningModule parsedSpecWithOwningModule) { BindSourceFile(parsedSpecWithOwningModule); var parsedFile = parsedSpecWithOwningModule.ParsedFile; if (parsedFile.BindDiagnostics.Count != 0) { ReportFailureAndCancelParsingIfNeeded( new BindingFailure(parsedSpecWithOwningModule.OwningModule.Descriptor, parsedFile)); } } /// <nodoc /> protected void BindSourceFile(ParsedSpecWithOwningModule parsedSpecWithOwningModule) { var sourceFile = parsedSpecWithOwningModule.ParsedFile; // Don't need to bind if the file is already bound (incremental case) if (sourceFile.State == SourceFileState.Bound) { return; } var specPathString = parsedSpecWithOwningModule.ParsedFile.Path.AbsolutePath; using (m_workspaceProvider.Statistics.SpecBinding.Start(specPathString)) { Binder.Bind(sourceFile, CompilerOptions.Empty); m_workspaceProvider.Statistics.SourceFileSymbols.Increment(sourceFile.SymbolCount, specPathString); } // Once binding is done, we can compute the binding fingerprint, // that is required for filtered scenarios. if (sourceFile.ParseDiagnostics.Count == 0 && sourceFile.BindDiagnostics.Count == 0 && m_workspaceConfiguration.ConstructFingerprintDuringParsing) { using (m_workspaceProvider.Statistics.SpecComputeFingerprint.Start()) { sourceFile.ComputeBindingFingerprint(m_workspaceProvider.SymbolTable); } } } } }
48.48017
208
0.626494
[ "MIT" ]
MatisseHack/BuildXL
Public/Src/FrontEnd/Sdk/Workspaces/Core/ModuleParsingQueue.cs
34,227
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Threading.Tasks; using NewLife.Log; using NewLife.Model; using NewLife.Serialization; using System.Net.NetworkInformation; #if NET40_OR_GREATER using System.Management; using Microsoft.VisualBasic.Devices; using Microsoft.Win32; #endif namespace NewLife { /// <summary>机器信息</summary> /// <remarks> /// 文档 https://www.yuque.com/smartstone/nx/machine_info /// /// 刷新信息成本较高,建议采用单例模式 /// </remarks> public class MachineInfo { #region 属性 /// <summary>系统名称</summary> public String OSName { get; set; } /// <summary>系统版本</summary> public String OSVersion { get; set; } /// <summary>产品名称。制造商</summary> public String Product { get; set; } /// <summary>处理器型号</summary> public String Processor { get; set; } /// <summary>处理器序列号</summary> public String CpuID { get; set; } /// <summary>硬件唯一标识</summary> public String UUID { get; set; } /// <summary>系统标识</summary> public String Guid { get; set; } /// <summary>磁盘序列号</summary> public String DiskID { get; set; } /// <summary>内存总量</summary> public UInt64 Memory { get; set; } /// <summary>可用内存</summary> public UInt64 AvailableMemory { get; private set; } /// <summary>CPU占用率</summary> public Single CpuRate { get; private set; } /// <summary>网络上行速度。字节每秒,初始化后首次读取为0</summary> public UInt64 UplinkSpeed { get; set; } /// <summary>网络下行速度。字节每秒,初始化后首次读取为0</summary> public UInt64 DownlinkSpeed { get; set; } /// <summary>温度</summary> public Double Temperature { get; set; } /// <summary>电池剩余</summary> public Double Battery { get; set; } #endregion #region 构造 /// <summary>当前机器信息。默认null,在RegisterAsync后才能使用</summary> public static MachineInfo Current { get; set; } private static Task<MachineInfo> _task; /// <summary>异步注册一个初始化后的机器信息实例</summary> /// <returns></returns> public static Task<MachineInfo> RegisterAsync() { if (_task != null) return _task; return _task = Task.Factory.StartNew(() => { var set = Setting.Current; var dataPath = set.DataPath; if (dataPath.IsNullOrEmpty()) dataPath = "Data"; // 文件缓存,加快机器信息获取 var file = Path.GetTempPath().CombinePath("machine_info.json"); var file2 = dataPath.CombinePath("machine_info.json").GetBasePath(); if (Current == null) { var f = file; if (!File.Exists(f)) f = file2; if (File.Exists(f)) { try { //XTrace.WriteLine("Load MachineInfo {0}", f); Current = File.ReadAllText(f).ToJsonEntity<MachineInfo>(); } catch { } } } var mi = Current ?? new MachineInfo(); mi.Init(); Current = mi; //// 定时刷新 //if (msRefresh > 0) mi._timer = new TimerX(s => mi.Refresh(), null, msRefresh, msRefresh) { Async = true }; // 注册到对象容器 ObjectContainer.Current.AddSingleton(mi); try { var json = mi.ToJson(true); File.WriteAllText(file.EnsureDirectory(true), json); File.WriteAllText(file2.EnsureDirectory(true), json); } catch { } return mi; }); } /// <summary>获取当前信息,如果未设置则等待异步注册结果</summary> /// <returns></returns> public static MachineInfo GetCurrent() => Current ?? RegisterAsync().Result; /// <summary>从对象容器中获取一个已注册机器信息实例</summary> /// <returns></returns> public static MachineInfo Resolve() => ObjectContainer.Current.Resolve<MachineInfo>(); #endregion #region 方法 /// <summary>刷新</summary> public void Init() { var osv = Environment.OSVersion; if (OSVersion.IsNullOrEmpty()) OSVersion = osv.Version + ""; if (OSName.IsNullOrEmpty()) OSName = (osv + "").TrimStart("Microsoft").TrimEnd(OSVersion).Trim(); if (Guid.IsNullOrEmpty()) Guid = ""; try { #if __CORE__ if (Runtime.Windows) LoadWindowsInfo(); else if (Runtime.Linux) LoadLinuxInfo(); #else if (Runtime.Windows) LoadWindowsInfoFx(); else if (Runtime.Linux) LoadLinuxInfo(); #endif } catch (Exception ex) { if (XTrace.Log.Level <= LogLevel.Debug) XTrace.WriteException(ex); } // window+netcore 不方便读取注册表,随机生成一个guid,借助文件缓存确保其不变 if (Guid.IsNullOrEmpty()) Guid = "0-" + System.Guid.NewGuid().ToString(); if (UUID.IsNullOrEmpty()) UUID = "0-" + System.Guid.NewGuid().ToString(); try { Refresh(); } catch { } } private void LoadWindowsInfoFx() { #if !__CORE__ var machine_guid = ""; var reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Cryptography"); if (reg != null) machine_guid = reg.GetValue("MachineGuid") + ""; if (machine_guid.IsNullOrEmpty()) { reg = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); if (reg != null) machine_guid = reg.GetValue("MachineGuid") + ""; } var ci = new ComputerInfo(); try { Memory = ci.TotalPhysicalMemory; // 系统名取WMI可能出错 OSName = ci.OSFullName.TrimStart("Microsoft").Trim(); OSVersion = ci.OSVersion; } catch { var reg2 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"); if (reg2 != null) { OSName = reg2.GetValue("ProductName") + ""; OSVersion = reg2.GetValue("ReleaseId") + ""; } } Processor = GetInfo("Win32_Processor", "Name"); CpuID = GetInfo("Win32_Processor", "ProcessorId"); var uuid = GetInfo("Win32_ComputerSystemProduct", "UUID"); Product = GetInfo("Win32_ComputerSystemProduct", "Name"); DiskID = GetInfo("Win32_DiskDrive", "SerialNumber"); // UUID取不到时返回 FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF if (!uuid.IsNullOrEmpty() && !uuid.EqualIgnoreCase("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF")) UUID = uuid; //// 可能因WMI导致读取UUID失败 //if (UUID.IsNullOrEmpty()) //{ // var reg3 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"); // if (reg3 != null) UUID = reg3.GetValue("ProductId") + ""; //} if (!machine_guid.IsNullOrEmpty()) Guid = machine_guid; //// 读取主板温度,不太准。标准方案是ring0通过IOPort读取CPU温度,太难在基础类库实现 //var str = GetInfo("Win32_TemperatureProbe", "CurrentReading"); //if (!str.IsNullOrEmpty()) //{ // Temperature = str.SplitAsInt().Average(); //} //else //{ // str = GetInfo("MSAcpi_ThermalZoneTemperature", "CurrentTemperature", "root/wmi"); // if (!str.IsNullOrEmpty()) Temperature = (str.SplitAsInt().Average() - 2732) / 10.0; //} //// 电池剩余 //str = GetInfo("Win32_Battery", "EstimatedChargeRemaining"); //if (!str.IsNullOrEmpty()) Battery = str.SplitAsInt().Average() / 100.0; #endif } private void LoadWindowsInfo() { var str = ""; var os = ReadWmic("os", "Caption", "Version"); if (os != null) { if (os.TryGetValue("Caption", out str)) OSName = str.TrimStart("Microsoft").Trim(); if (os.TryGetValue("Version", out str)) OSVersion = str; } var csproduct = ReadWmic("csproduct", "Name", "UUID"); if (csproduct != null) { if (csproduct.TryGetValue("Name", out str)) Product = str; if (csproduct.TryGetValue("UUID", out str)) UUID = str; } var disk = ReadWmic("diskdrive", "serialnumber"); if (disk != null) { if (disk.TryGetValue("serialnumber", out str)) DiskID = str?.Trim(); } // 不要在刷新里面取CPU负载,因为运行wmic会导致CPU负载很不准确,影响测量 var cpu = ReadWmic("cpu", "Name", "ProcessorId", "LoadPercentage"); if (cpu != null) { if (cpu.TryGetValue("Name", out str)) Processor = str; if (cpu.TryGetValue("ProcessorId", out str)) CpuID = str; if (cpu.TryGetValue("LoadPercentage", out str)) CpuRate = (Single)(str.ToDouble() / 100); } // 从注册表读取 MachineGuid str = Execute("reg", @"query HKLM\SOFTWARE\Microsoft\Cryptography /v MachineGuid"); if (!str.IsNullOrEmpty() && str.Contains("REG_SZ")) Guid = str.Substring("REG_SZ", null).Trim(); //var temp = ReadWmic(@"/namespace:\\root\wmi path MSAcpi_ThermalZoneTemperature", "CurrentTemperature"); //if (temp != null) //{ // if (temp.TryGetValue("CurrentTemperature", out str)) Temperature = (str.SplitAsInt().Average() - 2732) / 10.0; //} //var battery = ReadWmic("path win32_battery", "EstimatedChargeRemaining"); //if (battery != null) //{ // if (battery.TryGetValue("EstimatedChargeRemaining", out str)) Battery = str.SplitAsInt().Average() / 100.0; //} } private void LoadLinuxInfo() { var str = GetLinuxName(); if (!str.IsNullOrEmpty()) OSName = str; // 树莓派的Hardware无法区分P0/P4 var dic = ReadInfo("/proc/cpuinfo"); if (dic != null) { if (dic.TryGetValue("Hardware", out str) || dic.TryGetValue("cpu model", out str) || dic.TryGetValue("model name", out str)) Processor = str; if (dic.TryGetValue("Model", out str)) Product = str; if (dic.TryGetValue("Serial", out str)) CpuID = str; } var mid = "/etc/machine-id"; if (!File.Exists(mid)) mid = "/var/lib/dbus/machine-id"; if (TryRead(mid, out var value)) Guid = value; var file = "/sys/class/dmi/id/product_uuid"; if (TryRead(file, out value)) UUID = value; file = "/sys/class/dmi/id/product_name"; if (TryRead(file, out value)) Product = value; var disks = GetFiles("/dev/disk/by-id", true); if (disks.Count == 0) disks = GetFiles("/dev/disk/by-uuid", false); if (disks.Count > 0) DiskID = disks.Join(","); var dmi = Execute("dmidecode")?.SplitAsDictionary(":", "\n"); if (dmi != null) { if (dmi.TryGetValue("ID", out str)) CpuID = str.Replace(" ", null); if (dmi.TryGetValue("UUID", out str)) UUID = str; if (dmi.TryGetValue("Product Name", out str)) Product = str; //if (TryFind(dmi, new[] { "Serial Number" }, out str)) Guid = str; } // 从release文件读取产品 var prd = GetProductByRelease(); if (!prd.IsNullOrEmpty()) Product = prd; //// 电池剩余 //if (TryRead("/sys/class/power_supply/BAT0/energy_now", out var energy_now) && // TryRead("/sys/class/power_supply/BAT0/energy_full", out var energy_full)) //{ // Battery = energy_now.ToDouble() / energy_full.ToDouble(); //} //else if (TryRead("/sys/class/power_supply/battery/capacity", out var capacity)) //{ // Battery = capacity.ToDouble() / 100.0; //} } private ICollection<String> _excludes = new List<String>(); /// <summary>获取实时数据,如CPU、内存、温度</summary> public void Refresh() { if (Runtime.Windows) { MEMORYSTATUSEX ms = default; ms.Init(); if (GlobalMemoryStatusEx(ref ms)) { Memory = ms.ullTotalPhys; AvailableMemory = ms.ullAvailPhys; } } // 特别识别Linux发行版 else if (Runtime.Linux) { var dic = ReadInfo("/proc/meminfo"); if (dic != null) { if (dic.TryGetValue("MemTotal", out var str)) Memory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024; if (dic.TryGetValue("MemAvailable", out str) || dic.TryGetValue("MemFree", out str)) AvailableMemory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024; } // respberrypi + fedora if (TryRead("/sys/class/thermal/thermal_zone0/temp", out var value) || TryRead("/sys/class/hwmon/hwmon0/temp1_input", out value) || TryRead("/sys/class/hwmon/hwmon0/temp2_input", out value) || TryRead("/sys/class/hwmon/hwmon0/device/hwmon/hwmon0/temp2_input", out value) || TryRead("/sys/devices/virtual/thermal/thermal_zone0/temp", out value)) Temperature = value.ToDouble() / 1000; // A2温度获取,Ubuntu 16.04 LTS, Linux 3.4.39 else if (TryRead("/sys/class/hwmon/hwmon0/device/temp_value", out value)) Temperature = value.Substring(null, ":").ToDouble(); // 电池剩余 if (TryRead("/sys/class/power_supply/BAT0/energy_now", out var energy_now) && TryRead("/sys/class/power_supply/BAT0/energy_full", out var energy_full)) { Battery = energy_now.ToDouble() / energy_full.ToDouble(); } else if (TryRead("/sys/class/power_supply/battery/capacity", out var capacity)) { Battery = capacity.ToDouble() / 100.0; } //var upt = Execute("uptime"); //if (!upt.IsNullOrEmpty()) //{ // str = upt.Substring("load average:"); // if (!str.IsNullOrEmpty()) CpuRate = (Single)str.Split(",")[0].ToDouble(); //} //file = "/proc/loadavg"; //if (File.Exists(file)) CpuRate = (Single)File.ReadAllText(file).Substring(null, " ").ToDouble() / Environment.ProcessorCount; var file = "/proc/stat"; if (File.Exists(file)) { // CPU指标:user,nice, system, idle, iowait, irq, softirq // cpu 57057 0 14420 1554816 0 443 0 0 0 0 using var reader = new StreamReader(file); var line = reader.ReadLine(); if (!line.IsNullOrEmpty() && line.StartsWith("cpu")) { var vs = line.TrimStart("cpu").Trim().Split(" "); var current = new SystemTime { IdleTime = vs[3].ToLong(), TotalTime = vs.Take(7).Select(e => e.ToLong()).Sum().ToLong(), }; var idle = current.IdleTime - (_systemTime?.IdleTime ?? 0); var total = current.TotalTime - (_systemTime?.TotalTime ?? 0); _systemTime = current; CpuRate = total == 0 ? 0 : ((Single)(total - idle) / total); } } } if (Runtime.Windows) { GetSystemTimes(out var idleTime, out var kernelTime, out var userTime); var current = new SystemTime { IdleTime = idleTime.ToLong(), TotalTime = kernelTime.ToLong() + userTime.ToLong(), }; var idle = current.IdleTime - (_systemTime?.IdleTime ?? 0); var total = current.TotalTime - (_systemTime?.TotalTime ?? 0); _systemTime = current; CpuRate = total == 0 ? 0 : ((Single)(total - idle) / total); #if __CORE__ if (!_excludes.Contains(nameof(Temperature))) { var temp = ReadWmic(@"/namespace:\\root\wmi path MSAcpi_ThermalZoneTemperature", "CurrentTemperature"); if (temp != null && temp.Count > 0) { if (temp.TryGetValue("CurrentTemperature", out var str)) Temperature = (str.SplitAsInt().Average() - 2732) / 10.0; } else _excludes.Add(nameof(Temperature)); } if (!_excludes.Contains(nameof(Battery))) { var battery = ReadWmic("path win32_battery", "EstimatedChargeRemaining"); if (battery != null && battery.Count > 0) { if (battery.TryGetValue("EstimatedChargeRemaining", out var str)) Battery = str.SplitAsInt().Average() / 100.0; } else _excludes.Add(nameof(Battery)); } #else if (!_excludes.Contains(nameof(Temperature))) { // 读取主板温度,不太准。标准方案是ring0通过IOPort读取CPU温度,太难在基础类库实现 var str = GetInfo("Win32_TemperatureProbe", "CurrentReading"); if (!str.IsNullOrEmpty()) { Temperature = str.SplitAsInt().Average(); } else { str = GetInfo("MSAcpi_ThermalZoneTemperature", "CurrentTemperature", "root/wmi"); if (!str.IsNullOrEmpty()) Temperature = (str.SplitAsInt().Average() - 2732) / 10.0; } if (str.IsNullOrEmpty()) _excludes.Add(nameof(Temperature)); } if (!_excludes.Contains(nameof(Battery))) { // 电池剩余 var str = GetInfo("Win32_Battery", "EstimatedChargeRemaining"); if (!str.IsNullOrEmpty()) Battery = str.SplitAsInt().Average() / 100.0; else _excludes.Add(nameof(Battery)); } #endif } RefreshSpeed(); } private DateTime _lastTime; private Int64 _lastSent; private Int64 _lastReceived; /// <summary>刷新网络速度</summary> public void RefreshSpeed() { var sent = 0L; var received = 0L; foreach (var ni in NetworkInterface.GetAllNetworkInterfaces()) { #if NET40 var st = ni.GetIPv4Statistics(); #else var st = ni.GetIPStatistics(); #endif sent += st.BytesSent; received += st.BytesReceived; } if (_lastTime.Year > 2000) { var interval = (DateTime.Now - _lastTime).TotalMilliseconds; UplinkSpeed = (UInt64)((sent - _lastSent) * 1000 / interval); DownlinkSpeed = (UInt64)((received - _lastReceived) * 1000 / interval); } _lastSent = sent; _lastReceived = received; _lastTime = DateTime.Now; } #endregion #region 辅助 /// <summary>获取Linux发行版名称</summary> /// <returns></returns> public static String GetLinuxName() { var fr = "/etc/redhat-release"; if (TryRead(fr, out var value)) return value; var dr = "/etc/debian-release"; if (TryRead(dr, out value)) return value; var sr = "/etc/os-release"; if (TryRead(sr, out value)) return value?.SplitAsDictionary("=", "\n", true)["PRETTY_NAME"].Trim(); var uname = Execute("uname", "-sr")?.Trim(); if (!uname.IsNullOrEmpty()) return uname; return null; } private static String GetProductByRelease() { var di = "/etc/".AsDirectory(); if (!di.Exists) return null; foreach (var fi in di.GetFiles("*-release")) { if (!fi.Name.EqualIgnoreCase("redhat-release", "debian-release", "os-release", "system-release")) { var dic = File.ReadAllText(fi.FullName).SplitAsDictionary("=", "\n", true); if (dic.TryGetValue("BOARD", out var str)) return str; if (dic.TryGetValue("BOARD_NAME", out str)) return str; } } return null; } private static Boolean TryRead(String fileName, out String value) { value = null; if (!File.Exists(fileName)) return false; try { value = File.ReadAllText(fileName)?.Trim(); if (value.IsNullOrEmpty()) return false; } catch { return false; } return true; } private static IDictionary<String, String> ReadInfo(String file, Char separate = ':') { if (file.IsNullOrEmpty() || !File.Exists(file)) return null; var dic = new Dictionary<String, String>(StringComparer.OrdinalIgnoreCase); using var reader = new StreamReader(file); while (!reader.EndOfStream) { // 按行读取 var line = reader.ReadLine(); if (line != null) { // 分割 var p = line.IndexOf(separate); if (p > 0) { var key = line.Substring(0, p).Trim(); var value = line.Substring(p + 1).Trim(); dic[key] = value; } } } return dic; } private static String Execute(String cmd, String arguments = null) { try { var psi = new ProcessStartInfo(cmd, arguments) { // UseShellExecute 必须 false,以便于后续重定向输出流 UseShellExecute = false, RedirectStandardOutput = true }; var process = Process.Start(psi); if (!process.WaitForExit(3_000)) { process.Kill(); return null; } return process.StandardOutput.ReadToEnd(); } catch { return null; } } /// <summary>通过WMIC命令读取信息</summary> /// <param name="type"></param> /// <param name="keys"></param> /// <returns></returns> public static IDictionary<String, String> ReadWmic(String type, params String[] keys) { var dic = new Dictionary<String, String>(StringComparer.OrdinalIgnoreCase); var args = $"{type} get {keys.Join(",")} /format:list"; var str = Execute("wmic", args)?.Trim(); if (str.IsNullOrEmpty()) return dic; var ss = str.Split(Environment.NewLine); foreach (var item in ss) { var ks = item.Split("="); if (ks != null && ks.Length >= 2) { var k = ks[0].Trim(); var v = ks[1].Trim(); if (dic.TryGetValue(k, out var val)) dic[k] = val + "," + v; else dic[k] = v; } } // 排序,避免多个磁盘序列号时,顺序变动 foreach (var item in dic) { if (item.Value.Contains(',')) dic[item.Key] = item.Value.Split(',').OrderBy(e => e).Join(); } return dic; } #endregion #region 内存 [DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern Boolean GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer); internal struct MEMORYSTATUSEX { internal UInt32 dwLength; internal UInt32 dwMemoryLoad; internal UInt64 ullTotalPhys; internal UInt64 ullAvailPhys; internal UInt64 ullTotalPageFile; internal UInt64 ullAvailPageFile; internal UInt64 ullTotalVirtual; internal UInt64 ullAvailVirtual; internal UInt64 ullAvailExtendedVirtual; internal void Init() => dwLength = checked((UInt32)Marshal.SizeOf(typeof(MEMORYSTATUSEX))); } #endregion #region 磁盘 /// <summary>获取指定目录所在盘可用空间,默认当前目录</summary> /// <param name="path"></param> /// <returns>返回可用空间,字节,获取失败返回-1</returns> public static Int64 GetFreeSpace(String path = null) { if (path.IsNullOrEmpty()) path = "."; var driveInfo = new DriveInfo(Path.GetPathRoot(path.GetFullPath())); if (driveInfo == null || !driveInfo.IsReady) return -1; try { return driveInfo.AvailableFreeSpace; } catch { return -1; } } /// <summary>获取指定目录下文件名,支持去掉后缀的去重,主要用于Linux</summary> /// <param name="path"></param> /// <param name="trimSuffix"></param> /// <returns></returns> public static ICollection<String> GetFiles(String path, Boolean trimSuffix = false) { var list = new List<String>(); if (path.IsNullOrEmpty()) return list; var di = path.AsDirectory(); if (!di.Exists) return list; var list2 = di.GetFiles().Select(e => e.Name).ToList(); foreach (var item in list2) { var line = item?.Trim(); if (!line.IsNullOrEmpty()) { if (trimSuffix) { if (!list2.Any(e => e != line && line.StartsWith(e))) list.Add(line); } else { list.Add(line); } } } return list; } #endregion #region Windows辅助 [DllImport("kernel32.dll", SetLastError = true)] private static extern Boolean GetSystemTimes(out FILETIME idleTime, out FILETIME kernelTime, out FILETIME userTime); private struct FILETIME { public UInt32 Low; public UInt32 High; public FILETIME(Int64 time) { Low = (UInt32)time; High = (UInt32)(time >> 32); } public Int64 ToLong() => (Int64)(((UInt64)High << 32) | Low); } private class SystemTime { public Int64 IdleTime; public Int64 TotalTime; } private SystemTime _systemTime; #if NET40_OR_GREATER /// <summary>获取WMI信息</summary> /// <param name="path"></param> /// <param name="property"></param> /// <param name="nameSpace"></param> /// <returns></returns> public static String GetInfo(String path, String property, String nameSpace = null) { // Linux Mono不支持WMI if (Runtime.Mono) return ""; var bbs = new List<String>(); try { var wql = $"Select {property} From {path}"; var cimobject = new ManagementObjectSearcher(nameSpace, wql); var moc = cimobject.Get(); foreach (var mo in moc) { var val = mo?.Properties?[property]?.Value; if (val != null) bbs.Add(val.ToString().Trim()); } } catch (Exception ex) { if (XTrace.Log.Level <= LogLevel.Debug) XTrace.WriteLine("WMI.GetInfo({0})失败!{1}", path, ex.Message); return ""; } bbs.Sort(); return bbs.Distinct().Join(); } #endif #endregion } }
35.66787
143
0.487213
[ "MIT" ]
NewLifeX/X
NewLife.Core/Common/MachineInfo.cs
30,798
C#
using Akka.Actor; using Akka.DependencyInjection; using Akka.Event; using Akka.Logger.Serilog; using Akka.Util; using OpenTTD.Actors.Server; using Domain.Models; using Domain.ValueObjects; using Microsoft.Extensions.DependencyInjection; using OpenTTD.DataAccess; using OpenTTD.Services; namespace OpenTTD.Actors.Coordinator; public sealed record ServerAdd(ServerCredentials Credentials); public sealed record ServerConnect(ServerId ServerId); public sealed record ServerDisconnect(ServerId ServerId); public sealed record ServerRemove(ServerId ServerId); public sealed record ServerAdded(ServerId Id); public sealed class CoordinatorActor : ReceiveActor { private readonly IServiceScopeFactory _scopeFactory; private readonly ILoggingAdapter _logger = Context.GetLogger<SerilogLoggingAdapter>(); private readonly Dictionary<ServerId, (ServerCredentials Credentials, IActorRef Ref)> _servers = new(); public CoordinatorActor(IServiceScopeFactory scopeFactory) { _scopeFactory = scopeFactory; ReceiveAsync<ServerAdd>(async msg => { using var scope = scopeFactory.CreateScope(); var serverService = scope.ServiceProvider.GetRequiredService<IServerConfigurationService>(); var db = scope.ServiceProvider.GetRequiredService<AdminClientContext>(); try { var serverIdRes = await serverService.AddServerAsync(msg.Credentials); if (!serverIdRes.IsSuccess) { var (ip, port) = msg.Credentials.NetworkAddress; _logger.Error(serverIdRes.Exception, "Error while adding server {Ip}:{Port}", ip, port); Sender.Tell(Result.Failure<ServerAdded>(new ArgumentException("Server already exists"))); return; } var serverId = serverIdRes.Value; AddServerActor(serverId, msg.Credentials); await db.SaveChangesAsync(); _logger.Info( "Server added: {NetworkAddress} with an id {Guid}", msg.Credentials.NetworkAddress, serverId.Value); } catch (Exception exn) { var (ip, port) = msg.Credentials.NetworkAddress; _logger.Error(exn, "Error while adding server {Ip}:{Port}", ip, port); } finally { scope.Dispose(); } }); Receive<ServerConnect>(msg => { if (_servers.TryGetValue(msg.ServerId, out var data)) { data.Ref.Tell(new Connect()); _logger.Info( "Server {ServerId} will be connected", msg.ServerId.Value); } else { _logger.Warning( "Server {ServerId} was not found while connecting", msg.ServerId.Value); } }); Receive<ServerDisconnect>(msg => { if (_servers.TryGetValue(msg.ServerId, out var data)) { data.Ref.Tell(new Disconnect()); _logger.Info( "Server {ServerId} will be disconnected", msg.ServerId.Value); } else { _logger.Warning( "Server {ServerId} was not found while disconnecting", msg.ServerId.Value); } }); ReceiveAsync<ServerRemove>(async msg => { using var scope = scopeFactory.CreateScope(); var serverService = scope.ServiceProvider.GetRequiredService<IServerConfigurationService>(); var db = scope.ServiceProvider.GetRequiredService<AdminClientContext>(); try { var serverIdRes = await serverService.DeleteServerAsync(msg.ServerId); if (!serverIdRes.IsSuccess) { _logger.Error(serverIdRes.Exception, "Error while removing server {ServerId}", msg.ServerId.Value); return; } var serverId = serverIdRes.Value; if (_servers.TryGetValue(serverId, out var data)) { data.Ref.Tell(PoisonPill.Instance); _servers.Remove(msg.ServerId); } else { _logger.Warning( "Server {ServerId} was not found while removing", msg.ServerId.Value); } await db.SaveChangesAsync(); _logger.Info( "Server {ServerId} has been removed", serverId.Value); } catch (Exception exn) { _logger.Error(exn, "Error while removing server {ServerId}", msg.ServerId.Value); } finally { scope.Dispose(); } }); } protected override async void PreStart() { using var scope = _scopeFactory.CreateScope(); var serverService = scope.ServiceProvider.GetRequiredService<IServerConfigurationService>(); try { var configurationsResult = await serverService.GetConfigurationsAsync(); if (!configurationsResult.IsSuccess) { _logger.Error(configurationsResult.Exception, "Error while {PreStart} for {CoordinatorActor}", nameof(PreStart), nameof(CoordinatorActor)); } configurationsResult.Value.ForEach(cfg => AddServerActor( cfg.Id, new ServerCredentials { Name = cfg.Name, NetworkAddress = new NetworkAddress(cfg.IpAddress, cfg.Port), Password = cfg.Password, Version = cfg.Version }) ); } catch (Exception exn) { _logger.Error(exn, "Error while {PreStart} for {CoordinatorActor}", nameof(PreStart), nameof(CoordinatorActor)); } finally { base.PreStart(); } } private void AddServerActor(ServerId serverId, ServerCredentials credentials) { var serverProps = DependencyResolver.For(Context.System).Props<ServerActor>(serverId, credentials); var serverRef = Context.ActorOf(serverProps); _servers.Add(serverId, (credentials, serverRef)); Sender.Tell(Result.Success(new ServerAdded(serverId))); } }
33.792453
109
0.521078
[ "MIT" ]
TG-OpenTTD/tgServicesAndApps
src/OpenTTD/OpenTTD.Actors/Coordinator/CoordinatorActor.cs
7,166
C#
using Hl7.Fhir.WebApi; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Net.Http.Headers; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Hl7.Fhir.NetCoreApi.STU3 { public class FhirFormatParameterFilter : IResultFilter { public void OnResultExecuted(ResultExecutedContext context) { } public void OnResultExecuting(ResultExecutingContext context) { // Look for the _format parameter on the query var query = context.HttpContext.Request.Query; if (query?.ContainsKey("_format") == true) { if (String.Compare(query["_format"], "xml", true) == 0) context.HttpContext.Request.Headers[HeaderNames.Accept] = new string[] { FhirMediaType.XmlResource }; if (String.Compare(query["_format"], "json", true) == 0) context.HttpContext.Request.Headers[HeaderNames.Accept] = new string[] { FhirMediaType.JsonResource }; } } } }
34.709677
122
0.639405
[ "BSD-3-Clause" ]
brianpos/FhirFederator
Hl7.Fhir.NetCoreApi/FormatParameterFilter.cs
1,078
C#
using LiveHAPI.Shared.Interfaces.Model; namespace LiveHAPI.Shared.ValueObject.Meta { public class RelationshipTypeInfo: IRelationshipType { public string Id { get; set; } public string Name { get; set; } public string Description { get; set; } } }
25.909091
56
0.670175
[ "MIT" ]
palladiumkenya/livehapi
LiveHAPI.Shared/ValueObject/Meta/RelationshipTypeInfo.cs
287
C#
using System.Collections.Generic; namespace Procurement.ViewModel { public class SetTabBuyoutViewModel { private static List<string> orbTypes = new List<string>() { "Chaos Orb", "Vaal Orb", "Exalted Orb", "Divine Orb", "Orb of Fusing", "Orb of Alchemy", "Orb of Alteration", "Gemcutter's Prism", "Orb of Chance", "Cartographer's Chisel", "Orb of Scouring", "Orb of Regret", "Regal Orb", "Jeweller's Orb", "Chromatic Orb", "Blessed Orb" }; public List<string> OrbTypes { get { return orbTypes; } } private PricingInfo buyoutInfo; public PricingInfo BuyoutInfo { get { return buyoutInfo; } set { buyoutInfo = value; } } public SetTabBuyoutViewModel() { this.buyoutInfo = new PricingInfo(); } } }
24.488372
65
0.479582
[ "Artistic-2.0" ]
Brian-K-Smith/Procurement
Procurement/ViewModel/SetTabBuyoutViewModel.cs
1,055
C#
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.S3.Model { /// <summary> /// The response for the PutBucketAccelerateConfiguration operation. /// <para>Adds an object to a bucket.</para> /// </summary> public partial class PutBucketAccelerateConfigurationResponse : AmazonWebServiceResponse { } }
30.228571
92
0.730624
[ "Apache-2.0" ]
AltairMartinez/aws-sdk-unity-net
src/Services/S3/Custom/Model/PutBucketAccelerateConfiguarationResponse.cs
1,058
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SuperSocket.SocketBase; namespace SuperSocket.QuickStart.BroadcastService { public class BroadcastSession : AppSession<BroadcastSession> { public string DeviceNumber { get; set; } public new BroadcastServer AppServer { get { return (BroadcastServer)base.AppServer; } } public override void HandleException(Exception e) { } } }
22.458333
65
0.627087
[ "BSD-3-Clause" ]
3rdandUrban-dev/Nuxleus
src/external/SuperSocket/mainline/QuickStart/BroadcastService/BroadcastSession.cs
541
C#
 // Copyright (C) 2015-2017 Luca Piccioni // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using Khronos; // ReSharper disable InheritdocConsiderUsage namespace OpenGL { /// <summary> /// Exception thrown by Gl class. /// </summary> public sealed class GlException : KhronosException { #region Constructors /// <summary> /// Construct a GlException. /// </summary> /// <param name="errorCode"> /// A <see cref="ErrorCode"/> that specifies the error code. /// </param> public GlException(ErrorCode errorCode) : base((int)errorCode, GetErrorMessage(errorCode)) { } #endregion #region Error Messages /// <summary> /// Returns a description of the error code. /// </summary> /// <param name="errorCode"> /// A <see cref="ErrorCode"/> that specifies the error code. /// </param> /// <returns> /// It returns a description of <paramref name="errorCode"/>, asssuming that is a value returned /// by <see cref="Egl.GetError"/>. /// </returns> private static string GetErrorMessage(ErrorCode errorCode) { switch (errorCode) { default: return $"unknown error code {errorCode}"; case OpenGL.ErrorCode.NoError: return "no error"; case OpenGL.ErrorCode.InvalidEnum: return "invalid enumeration"; case OpenGL.ErrorCode.InvalidFramebufferOperation: return "invalid framebuffer operation"; case OpenGL.ErrorCode.InvalidOperation: return "invalid operation"; case OpenGL.ErrorCode.InvalidValue: return "invalid value"; case OpenGL.ErrorCode.OutOfMemory: return "out of memory"; case OpenGL.ErrorCode.StackOverflow: return "stack overflow"; case OpenGL.ErrorCode.StackUnderflow: return "stack underflow"; // GL_ARB_imaging case OpenGL.ErrorCode.TableTooLarge: return "table too large"; // GL_EXT_texture case OpenGL.ErrorCode.TextureTooLargeExt: return "texture too large"; } } #endregion } }
30.693878
98
0.709774
[ "MIT" ]
MagmaiKH/OpenGL.Net
OpenGL.Net/GlException.cs
3,010
C#
// ----------------------------------------------------------------------------------- // // GRABCASTER LTD CONFIDENTIAL // ___________________________ // // Copyright © 2013 - 2016 GrabCaster Ltd. All rights reserved. // This work is registered with the UK Copyright Service: Registration No:284701085 // // // NOTICE: All information contained herein is, and remains // the property of GrabCaster Ltd and its suppliers, // if any. The intellectual and technical concepts contained // herein are proprietary to GrabCaster Ltd // and its suppliers and may be covered by UK and Foreign Patents, // patents in process, and are protected by trade secret or copyright law. // Dissemination of this information or reproduction of this material // is strictly forbidden unless prior written permission is obtained // from GrabCaster Ltd. // // ----------------------------------------------------------------------------------- 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("ETW")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ETW")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f10b069c-8c2d-4ef6-b196-98ad8f712959")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.508475
87
0.690581
[ "MIT" ]
debiaggi/GrabCaster
Triggers/ETW/Properties/AssemblyInfo.cs
2,276
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Net.Http.Headers; using System.Text; namespace System.Net.Http { public class HttpResponseMessage : IDisposable { private const HttpStatusCode defaultStatusCode = HttpStatusCode.OK; private HttpStatusCode _statusCode; private HttpResponseHeaders _headers; private string _reasonPhrase; private HttpRequestMessage _requestMessage; private Version _version; private HttpContent _content; private bool _disposed; public Version Version { get { return _version; } set { #if !PHONE if (value == null) { throw new ArgumentNullException(nameof(value)); } #endif CheckDisposed(); _version = value; } } public HttpContent Content { get { return _content; } set { CheckDisposed(); if (HttpEventSource.Log.IsEnabled()) { if (value == null) { HttpEventSource.ContentNull(this); } else { HttpEventSource.Associate(this, value); } } _content = value; } } public HttpStatusCode StatusCode { get { return _statusCode; } set { if (((int)value < 0) || ((int)value > 999)) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposed(); _statusCode = value; } } public string ReasonPhrase { get { if (_reasonPhrase != null) { return _reasonPhrase; } // Provide a default if one was not set. return HttpStatusDescription.Get(StatusCode); } set { if ((value != null) && ContainsNewLineCharacter(value)) { throw new FormatException(SR.net_http_reasonphrase_format_error); } CheckDisposed(); _reasonPhrase = value; // It's OK to have a 'null' reason phrase. } } public HttpResponseHeaders Headers { get { if (_headers == null) { _headers = new HttpResponseHeaders(); } return _headers; } } public HttpRequestMessage RequestMessage { get { return _requestMessage; } set { CheckDisposed(); if (HttpEventSource.Log.IsEnabled() && (value != null)) HttpEventSource.Associate(this, value); _requestMessage = value; } } public bool IsSuccessStatusCode { get { return ((int)_statusCode >= 200) && ((int)_statusCode <= 299); } } public HttpResponseMessage() : this(defaultStatusCode) { } public HttpResponseMessage(HttpStatusCode statusCode) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", "StatusCode: " + (int)statusCode + ", ReasonPhrase: '" + _reasonPhrase + "'"); if (((int)statusCode < 0) || ((int)statusCode > 999)) { throw new ArgumentOutOfRangeException(nameof(statusCode)); } _statusCode = statusCode; _version = HttpUtilities.DefaultResponseVersion; if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null); } public HttpResponseMessage EnsureSuccessStatusCode() { if (!IsSuccessStatusCode) { // Disposing the content should help users: If users call EnsureSuccessStatusCode(), an exception is // thrown if the response status code is != 2xx. I.e. the behavior is similar to a failed request (e.g. // connection failure). Users don't expect to dispose the content in this case: If an exception is // thrown, the object is responsible fore cleaning up its state. if (_content != null) { _content.Dispose(); } throw new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_message_not_success_statuscode, (int)_statusCode, ReasonPhrase)); } return this; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("StatusCode: "); sb.Append((int)_statusCode); sb.Append(", ReasonPhrase: '"); sb.Append(ReasonPhrase ?? "<null>"); sb.Append("', Version: "); sb.Append(_version); sb.Append(", Content: "); sb.Append(_content == null ? "<null>" : _content.GetType().ToString()); sb.Append(", Headers:\r\n"); sb.Append(HeaderUtilities.DumpHeaders(_headers, _content == null ? null : _content.Headers)); return sb.ToString(); } private bool ContainsNewLineCharacter(string value) { foreach (char character in value) { if ((character == HttpRuleParser.CR) || (character == HttpRuleParser.LF)) { return true; } } return false; } #region IDisposable Members protected virtual void Dispose(bool disposing) { // The reason for this type to implement IDisposable is that it contains instances of types that implement // IDisposable (content). if (disposing && !_disposed) { _disposed = true; if (_content != null) { _content.Dispose(); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().ToString()); } } } }
29.952991
197
0.495506
[ "MIT" ]
OceanYan/corefx
src/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs
7,009
C#
#nullable enable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DotVVM.Framework.Hosting; namespace DotVVM.Framework.Controls.Infrastructure { public class GlobalizeResource : DotvvmControl { protected internal override void OnPreRender(IDotvvmRequestContext context) { context.ResourceManager.AddCurrentCultureGlobalizationResource(); base.OnPreRender(context); } } }
25.3
83
0.737154
[ "Apache-2.0" ]
AMBULATUR/dotvvm
src/DotVVM.Framework/Controls/Infrastructure/GlobalizeResource.cs
508
C#
using System; using System.IO; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; namespace Cosmos.Encryption.Core { /// <summary> /// Abstrace Symmetric/SymmetricEncyptionBase encryption. /// Reference: Seay Xu /// https://github.com/godsharp/GodSharp.Encryption/blob/master/src/GodSharp.Shared/Encryption/Symmetric/XES.cs /// Editor: AlexLEWIS /// </summary> // ReSharper disable once InconsistentNaming public abstract class SymmetricEncyptionBase { /// <summary> /// 用于整理获得真实 key / iv 的方法 /// </summary> protected static Func<string, Func<string, Func<Encoding, Func<int, byte[]>>>> ComputeRealValueFunc() => originString => salt => encoding => size => { if (string.IsNullOrWhiteSpace(originString)) { return new byte[0]; } if (encoding == null) { encoding = Encoding.UTF8; } var len = size / 8; if (string.IsNullOrWhiteSpace(salt)) { var retBytes = new byte[len]; Array.Copy(encoding.GetBytes(originString.PadRight(len)), retBytes, len); return retBytes; } var saltBytes = encoding.GetBytes(salt); var rfcOriginStringData = new Rfc2898DeriveBytes(encoding.GetBytes(originString), saltBytes, 1000); return rfcOriginStringData.GetBytes(len); }; protected static byte[] NiceEncryptCore<TCryptoServiceProvider>(byte[] sourceBytes, byte[] keyBytes, byte[] ivBytes) where TCryptoServiceProvider : SymmetricAlgorithm, new() { using (var provider = new TCryptoServiceProvider()) { provider.Key = keyBytes; provider.IV = ivBytes; using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, provider.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(sourceBytes, 0, sourceBytes.Length); cs.FlushFinalBlock(); return ms.ToArray(); } } } } protected static byte[] NiceDecryptCore<TCryptoServiceProvider>(byte[] encryptBytes, byte[] keyBytes, byte[] ivBytes) where TCryptoServiceProvider : SymmetricAlgorithm, new() { using (var provider = new TCryptoServiceProvider()) { provider.Key = keyBytes; provider.IV = ivBytes; using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, provider.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(encryptBytes, 0, encryptBytes.Length); cs.FlushFinalBlock(); return ms.ToArray(); } } } } } }
41.666667
125
0.57
[ "MIT" ]
chinayou25/Cosmos
Encryption/src/Cosmos.Encryption/Core/SymmetricEncyptionBase.cs
3,024
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ShellDll { //http://msdn.microsoft.com/en-us/library/windows/desktop/dd378457%28v=vs.85%29.aspx public enum KnownFolderIds { [KnownFolderGuid("{008ca0b1-55b4-4c56-b8a8-4de4b299d3be}")] [DefaultPath(@"%APPDATA%\Microsoft\Windows\AccountPictures")] [FolderCategory(KnownFolderCategory.PerUser)] [DisplayName("Account Pictures")] [MinVersion(OSVersions.Windows8)] AccountPictures, [KnownFolderGuid("{de61d971-5ebc-4f02-a3a9-6c82895e5c04}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Get Programs")] AddNewPrograms, [KnownFolderGuid("{724EF170-A42D-4FEF-9F26-B60E846FBA4F}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%APPDATA%\Microsoft\Windows\Start Menu\Programs\Administrative Tools")] [DisplayName("Administrative Tools")] [Csidl(ShellAPI.CSIDL.CSIDL_ADMINTOOLS)] [SpecialFolder(Environment.SpecialFolder.AdminTools)] AdminTools, [KnownFolderGuid("{A3918781-E5F2-4890-B3D9-A7E54332328C}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%LOCALAPPDATA%\Microsoft\Windows\Application Shortcuts")] [DisplayName("Application Shortcuts")] [MinVersion(OSVersions.Windows8)] ApplicationShortcuts, [KnownFolderGuid("{1e87508d-89c2-42f0-8a7e-645a0f50ca58}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Applications")] [MinVersion(OSVersions.Windows8)] AppsFolder, [KnownFolderGuid("{a305ce99-f527-492b-8b1a-7e76fa98d6e4}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Installed Updates")] AppUpdates, [KnownFolderGuid("{AB5FB87B-7CE2-4F83-915D-550846C9537B}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\Pictures\Camera Roll")] [DisplayName("Camera Roll")] [MinVersion(OSVersions.Windows81)] CameraRoll, [KnownFolderGuid("{9E52AB10-F80D-49DF-ACB8-4330F5687855}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%LOCALAPPDATA%\Microsoft\Windows\Burn\Burn")] [DisplayName("Temporary Burn Folder")] [Csidl(ShellAPI.CSIDL.CSIDL_CDBURN_AREA)] [SpecialFolder(Environment.SpecialFolder.CDBurning)] CDBurning, [KnownFolderGuid("{df7266ac-9274-4867-8d55-3bd661de872d}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Programs and Features")] ChangeRemovePrograms, [KnownFolderGuid("{D0384E7D-BAC3-4797-8F14-CBA229B392B5}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\Administrative Tools")] [DisplayName("Administrative Tools")] [Csidl(ShellAPI.CSIDL.CSIDL_COMMON_ADMINTOOLS)] [SpecialFolder(Environment.SpecialFolder.CommonAdminTools)] CommonAdminTools, [KnownFolderGuid("{C1BAE2D0-10DF-4334-BEDD-7AA20B227A9D}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%ALLUSERSPROFILE%\OEM Links")] [DisplayName("OEM Links")] [Csidl(ShellAPI.CSIDL.CSIDL_COMMON_OEM_LINKS)] [SpecialFolder(Environment.SpecialFolder.CommonOemLinks)] CommonOEMLinks, [KnownFolderGuid("{0139D44E-6AFE-49F2-8690-3DAFCAE6FFB8}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs")] [DisplayName("Programs")] [Csidl(ShellAPI.CSIDL.CSIDL_COMMON_PROGRAMS)] [SpecialFolder(Environment.SpecialFolder.CommonPrograms)] CommonPrograms, [KnownFolderGuid("{A4115719-D62E-491D-AA7C-E74B8BE3B067}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu")] [DisplayName("Start Menu")] [Csidl(ShellAPI.CSIDL.CSIDL_COMMON_STARTMENU)] [SpecialFolder(Environment.SpecialFolder.CommonStartMenu)] CommonStartMenu, [KnownFolderGuid("{82A5EA35-D9CD-47C5-9629-E15D2F714E6E}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\StartUp")] [DisplayName("Startup")] [Csidl(ShellAPI.CSIDL.CSIDL_COMMON_STARTUP)] [Csidl(ShellAPI.CSIDL.CSIDL_COMMON_ALTSTARTUP)] [SpecialFolder(Environment.SpecialFolder.CommonStartup)] CommonStartup, [KnownFolderGuid("{B94237E7-57AC-4347-9151-B08C6C32D1F7}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%ALLUSERSPROFILE%\Microsoft\Windows\Templates")] [DisplayName("Templates")] [Csidl(ShellAPI.CSIDL.CSIDL_COMMON_TEMPLATES)] [SpecialFolder(Environment.SpecialFolder.CommonTemplates)] CommonTemplates, [KnownFolderGuid("{0AC0837C-BBF8-452A-850D-79D08E667CA7}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Computer")] [Csidl(ShellAPI.CSIDL.CSIDL_DRIVES)] [SpecialFolder(Environment.SpecialFolder.MyComputer)] ComputerFolder, [KnownFolderGuid("{4bfefb45-347d-4006-a5be-ac0cb0567192}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Conflicts")] [MinVersion(OSVersions.WindowsVista)] ConflictFolder, [KnownFolderGuid("{6F0CD92B-2E97-45D1-88FF-B0D186B8DEDD}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Network Connections")] [Csidl(ShellAPI.CSIDL.CSIDL_CONNECTIONS)] ConnectionsFolder, [KnownFolderGuid("{56784854-C6CB-462b-8169-88E350ACB882}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\Contacts")] [DisplayName("Contacts")] [MinVersion(OSVersions.WindowsVista)] Contacts, [KnownFolderGuid("{82A74AEB-AEB4-465C-A014-D097EE346D63}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Control Panel")] [Csidl(ShellAPI.CSIDL.CSIDL_CONTROLS)] ControlPanelFolder, [KnownFolderGuid("{2B0F765D-C0E9-4171-908E-08A611B84FF6}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%APPDATA%\Microsoft\Windows\Cookies")] [DisplayName("Cookies")] [Csidl(ShellAPI.CSIDL.CSIDL_COOKIES)] [SpecialFolder(Environment.SpecialFolder.Cookies)] Cookies, [KnownFolderGuid("{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\Desktop")] [DisplayName("Desktop")] [Csidl(ShellAPI.CSIDL.CSIDL_DESKTOP)] [Csidl(ShellAPI.CSIDL.CSIDL_DESKTOPDIRECTORY)] [SpecialFolder(Environment.SpecialFolder.Desktop)] [SpecialFolder(Environment.SpecialFolder.DesktopDirectory)] Desktop, [KnownFolderGuid("{5CE4A5E9-E4EB-479D-B89F-130C02886155}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"")] [DisplayName("DeviceMetadataStore")] [MinVersion(OSVersions.Windows7)] DeviceMetadataStore, [KnownFolderGuid("{FDD39AD0-238F-46AF-ADB4-6C85480369C7}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\My Documents")] [DisplayName("Documents")] [Csidl(ShellAPI.CSIDL.CSIDL_MYDOCUMENTS)] [Csidl(ShellAPI.CSIDL.CSIDL_PERSONAL)] [SpecialFolder(Environment.SpecialFolder.MyDocuments)] [SpecialFolder(Environment.SpecialFolder.Personal)] Documents, [KnownFolderGuid("{7B0DB17D-9CD2-4A93-9733-46CC89022E7C}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%APPDATA%\Microsoft\Windows\Libraries\Documents.library-ms")] [DisplayName("Documents")] [MinVersion(OSVersions.Windows7)] DocumentsLibrary, [KnownFolderGuid("{374DE290-123F-4565-9164-39C4925E467B}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\Downloads")] [DisplayName("Downloads")] Downloads, [KnownFolderGuid("{1777F761-68AD-4D8A-87BD-30B759FA33DD}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\Favorites")] [DisplayName("Favorites")] [Csidl(ShellAPI.CSIDL.CSIDL_FAVORITES)] [Csidl(ShellAPI.CSIDL.CSIDL_COMMON_FAVORITES)] [SpecialFolder(Environment.SpecialFolder.Favorites)] Favorites, [KnownFolderGuid("{FD228CB7-AE11-4AE3-864C-16F3910AB8FE}")] [FolderCategory(KnownFolderCategory.Fixed)] [DefaultPath(@"%windir%\Fonts")] [DisplayName("Fonts")] [Csidl(ShellAPI.CSIDL.CSIDL_FONTS)] [SpecialFolder(Environment.SpecialFolder.Fonts)] Fonts, [KnownFolderGuid("{CAC52C1A-B53D-4edc-92D7-6B2E8AC19434}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Games")] Games, [KnownFolderGuid("{054FAE61-4DD8-4787-80B6-090220C4B700}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%LOCALAPPDATA%\Microsoft\Windows\GameExplorer")] [DisplayName("GameExplorer")] [MinVersion(OSVersions.WindowsVista)] GameTasks, [KnownFolderGuid("{D9DC8A3B-B784-432E-A781-5A1130A75963}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%LOCALAPPDATA%\Microsoft\Windows\History")] [DisplayName("History")] [Csidl(ShellAPI.CSIDL.CSIDL_HISTORY)] [SpecialFolder(Environment.SpecialFolder.History)] History, [KnownFolderGuid("{52528A6B-B9E3-4ADD-B60D-588C2DBA842D}")] [FolderCategory(KnownFolderCategory.Virtual)] [DefaultPath(@"Homegroup")] [MinVersion(OSVersions.Windows7)] HomeGroup, [KnownFolderGuid("{9B74B6A3-0DFD-4f11-9E78-5F7800F2E772}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("%USERNAME%")] [MinVersion(OSVersions.Windows8)] HomeGroupCurrentUser, [KnownFolderGuid("{BCB5256F-79F6-4CEE-B725-DC34E402FD46}")] [FolderCategory(KnownFolderCategory.PerUser)] [DisplayName("ImplicitAppShortcuts")] [MinVersion(OSVersions.Windows7)] ImplicitAppShortcuts, [KnownFolderGuid("{352481E8-33BE-4251-BA85-6007CAEDCF9D}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%LOCALAPPDATA%\Microsoft\Windows\Temporary Internet Files")] [DefaultPath(@"%USERPROFILE%\Local Settings\Temporary Internet Files")] [DisplayName("Temporary Internet Files")] [Csidl(ShellAPI.CSIDL.CSIDL_INTERNET_CACHE)] [SpecialFolder(Environment.SpecialFolder.InternetCache)] InternetCache, [KnownFolderGuid("{4D9F7874-4E0C-4904-967B-40B0D20C3E4B}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("The Internet")] [Csidl(ShellAPI.CSIDL.CSIDL_INTERNET)] InternetFolder, [KnownFolderGuid("{1B3EA5DC-B587-4786-B4EF-BD1DC332AEAE}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%APPDATA%\Microsoft\Windows\Libraries")] [DisplayName("Libraries")] [MinVersion(OSVersions.Windows7)] Libraries, [KnownFolderGuid("{bfb9d5e0-c6a9-404c-b2b2-ae6db6af4968}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\Links")] [DisplayName("Links")] Links, [KnownFolderGuid("{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%LOCALAPPDATA%")] [DefaultPath(@"%USERPROFILE%\AppData\Local")] [DisplayName("Local")] [Csidl(ShellAPI.CSIDL.CSIDL_LOCAL_APPDATA)] [SpecialFolder(Environment.SpecialFolder.LocalApplicationData)] LocalAppData, [KnownFolderGuid("{A520A1A4-1780-4FF6-BD18-167343C5AF16}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\AppData\LocalLow")] [DisplayName("LocalLow")] LocalAppDataLow, [KnownFolderGuid("{2A00375E-224C-49DE-B8D1-440DF7EF3DDC}")] [FolderCategory(KnownFolderCategory.Fixed)] [DefaultPath(@"%windir%\resources\0409")] [Csidl(ShellAPI.CSIDL.CSIDL_RESOURCES_LOCALIZED)] [SpecialFolder(Environment.SpecialFolder.LocalizedResources)] LocalizedResourcesDir, [KnownFolderGuid("{4BD8D571-6D19-48D3-BE97-422220080E43}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\Music")] [DefaultPath(@"%USERPROFILE%\My Documents\My Music")] [DisplayName("Music")] [Csidl(ShellAPI.CSIDL.CSIDL_MYMUSIC)] [SpecialFolder(Environment.SpecialFolder.MyMusic)] Music, [KnownFolderGuid("{2112AB0A-C86A-4FFE-A368-0DE96E47012E}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%APPDATA%\Microsoft\Windows\Libraries\Music.library-ms")] [DisplayName("Music")] [MinVersion(OSVersions.Windows7)] MusicLibrary, [KnownFolderGuid("{C5ABBF53-E17F-4121-8900-86626FC2C973}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%APPDATA%\Microsoft\Windows\Network Shortcuts")] [DisplayName("Network Shortcuts")] [Csidl(ShellAPI.CSIDL.CSIDL_NETHOOD)] [SpecialFolder(Environment.SpecialFolder.NetworkShortcuts)] NetHood, [KnownFolderGuid("{D20BEEC4-5CA8-4905-AE3B-BF251EA09B53}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Network")] [Csidl(ShellAPI.CSIDL.CSIDL_NETWORK)] [Csidl(ShellAPI.CSIDL.CSIDL_COMPUTERSNEARME)] NetworkFolder, [KnownFolderGuid("{2C36C0AA-5812-4b87-BFD0-4CD0DFB19B39}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%LOCALAPPDATA%\Microsoft\Windows Photo Gallery\Original Images")] [DisplayName("Original Images")] [MinVersion(OSVersions.WindowsVista)] OriginalImages, [KnownFolderGuid("{69D2CF90-FC33-4FB7-9A0C-EBB0F0FCB43C}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\Pictures\Slide Shows")] [DisplayName("Slide Shows")] [MinVersion(OSVersions.WindowsVista)] PhotoAlbums, [KnownFolderGuid("{A990AE9F-A03B-4E80-94BC-9912D7504104}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%APPDATA%\Microsoft\Windows\Libraries\Pictures.library-ms")] [DisplayName("Pictures")] [MinVersion(OSVersions.Windows7)] PicturesLibrary, [KnownFolderGuid("{33E28130-4E1E-4676-835A-98395C3BC3BB}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\Pictures")] [DefaultPath(@"%USERPROFILE%\My Documents\My Pictures")] [DisplayName("Pictures")] [Csidl(ShellAPI.CSIDL.CSIDL_MYPICTURES)] [SpecialFolder(Environment.SpecialFolder.MyPictures)] Pictures, [KnownFolderGuid("{DE92C1C7-837F-4F69-A3BB-86E631204A23}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\Music\Playlists")] [DisplayName("Playlists")] Playlists, [KnownFolderGuid("{76FC4E2D-D6AD-4519-A663-37BD56068185}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Printers")] [Csidl(ShellAPI.CSIDL.CSIDL_PRINTERS)] PrintersFolder, [KnownFolderGuid("{9274BD8D-CFD1-41C3-B35E-B13F55A758F4}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%APPDATA%\Microsoft\Windows\Printer Shortcuts")] [DefaultPath(@"%USERPROFILE%\PrintHood")] [DisplayName("Printer Shortcuts")] [Csidl(ShellAPI.CSIDL.CSIDL_PRINTHOOD)] [SpecialFolder(Environment.SpecialFolder.PrinterShortcuts)] [MinVersion(OSVersions.Windows81)] PrintHood, [KnownFolderGuid("{5E6C858F-0E22-4760-9AFE-EA3317B67173}")] [FolderCategory(KnownFolderCategory.Fixed)] [DefaultPath(@"%USERPROFILE%")] [DefaultPath(@"%SystemDrive%\Users\%USERNAME%")] [DefaultPath(@"%SystemDrive%\Documents")] [DisplayName("%USERNAME%")] [Csidl(ShellAPI.CSIDL.CSIDL_PROFILE)] [SpecialFolder(Environment.SpecialFolder.UserProfile)] Profile, [KnownFolderGuid("{62AB5D82-FDC1-4DC3-A9DD-070D1D495D97}")] [FolderCategory(KnownFolderCategory.Fixed)] [DefaultPath(@"%ALLUSERSPROFILE%")] [DefaultPath(@"%ProgramData%")] [DefaultPath(@"%SystemDrive%\ProgramData")] [DefaultPath(@"%ALLUSERSPROFILE%\Application Data")] [DisplayName("ProgramData")] [Csidl(ShellAPI.CSIDL.CSIDL_COMMON_APPDATA)] [SpecialFolder(Environment.SpecialFolder.CommonApplicationData)] ProgramData, [KnownFolderGuid("{905e63b6-c1bf-494e-b29c-65b732d3d21a}")] [FolderCategory(KnownFolderCategory.Fixed)] [DefaultPath(@"%ProgramFiles%")] [DefaultPath(@"%SystemDrive%\Program Files")] [DisplayName("Program Files")] [Csidl(ShellAPI.CSIDL.CSIDL_PROGRAM_FILES)] [SpecialFolder(Environment.SpecialFolder.ProgramFiles)] ProgramFiles, [KnownFolderGuid("{6D809377-6AF0-444b-8957-A3773F02200E}")] [FolderCategory(KnownFolderCategory.Fixed)] [DefaultPath(@"%ProgramFiles%")] [DefaultPath(@"%SystemDrive%\Program Files")] [DisplayName("Program Files")] ProgramFilesX64, [KnownFolderGuid("{7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}")] [FolderCategory(KnownFolderCategory.Fixed)] [DefaultPath(@"%ProgramFiles%")] [DefaultPath(@"%SystemDrive%\Program Files")] [DisplayName("Program Files")] [Csidl(ShellAPI.CSIDL.CSIDL_PROGRAM_FILESX86)] [SpecialFolder(Environment.SpecialFolder.ProgramFilesX86)] ProgramFilesX86, [KnownFolderGuid("{F7F1ED05-9F6D-47A2-AAAE-29D317C6F066}")] [FolderCategory(KnownFolderCategory.Fixed)] [DefaultPath(@"%ProgramFiles%\Common Files")] [DisplayName("Common Files")] [Csidl(ShellAPI.CSIDL.CSIDL_PROGRAM_FILES_COMMON)] [SpecialFolder(Environment.SpecialFolder.CommonProgramFiles)] ProgramFilesCommon, [KnownFolderGuid("{6365D5A7-0F0D-45E5-87F6-0DA56B6A4F7D}")] [FolderCategory(KnownFolderCategory.Fixed)] [DefaultPath(@"%ProgramFiles%\Common Files")] [DisplayName("Common Files")] ProgramFilesCommonX64, [KnownFolderGuid("{DE974D24-D9C6-4D3E-BF91-F4455120B917}")] [FolderCategory(KnownFolderCategory.Fixed)] [DefaultPath(@"%ProgramFiles%\Common Files")] [DisplayName("Common Files")] [Csidl(ShellAPI.CSIDL.CSIDL_PROGRAM_FILES_COMMONX86)] [SpecialFolder(Environment.SpecialFolder.CommonProgramFilesX86)] ProgramFilesCommonX86, [KnownFolderGuid("{A77F5D77-2E2B-44C3-A6A2-ABA601054A51}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%APPDATA%\Microsoft\Windows\Start Menu\Programs")] [DisplayName("Programs")] [Csidl(ShellAPI.CSIDL.CSIDL_PROGRAMS)] [SpecialFolder(Environment.SpecialFolder.Programs)] Programs, [KnownFolderGuid("{DFDF76A2-C82A-4D63-906A-5644AC457385}")] [FolderCategory(KnownFolderCategory.Fixed)] [DefaultPath(@"%PUBLIC%")] [DefaultPath(@"%SystemDrive%\Users\Public")] [DisplayName("Public")] [MinVersion(OSVersions.WindowsVista)] Public, [KnownFolderGuid("{C4AA340D-F20F-4863-AFEF-F87EF2E6BA25}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%PUBLIC%\Desktop")] [DefaultPath(@"%ALLUSERSPROFILE%\Desktop")] [DisplayName("Public Desktop")] [Csidl(ShellAPI.CSIDL.CSIDL_COMMON_DESKTOPDIRECTORY)] [SpecialFolder(Environment.SpecialFolder.CommonDesktopDirectory)] PublicDesktop, [KnownFolderGuid("{ED4824AF-DCE4-45A8-81E2-FC7965083634}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%PUBLIC%\Documents")] [DefaultPath(@"%ALLUSERSPROFILE%\Documents")] [DisplayName("Public Documents")] [Csidl(ShellAPI.CSIDL.CSIDL_COMMON_DOCUMENTS)] [SpecialFolder(Environment.SpecialFolder.CommonDocuments)] PublicDocuments, [KnownFolderGuid("{3D644C9B-1FB8-4f30-9B45-F670235F79C0}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%PUBLIC%\Downloads")] [DisplayName("Public Downloads")] [MinVersion(OSVersions.WindowsVista)] PublicDownloads, [KnownFolderGuid("{DEBF2536-E1A8-4c59-B6A2-414586476AEA}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%ALLUSERSPROFILE%\Microsoft\Windows\GameExplorer")] [DisplayName("GameExplorer")] [MinVersion(OSVersions.WindowsVista)] PublicGameTasks, [KnownFolderGuid("{48DAF80B-E6CF-4F4E-B800-0E69D84EE384}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%ALLUSERSPROFILE%\Microsoft\Windows\Libraries")] [DisplayName("Libraries")] [MinVersion(OSVersions.Windows7)] PublicLibraries, [KnownFolderGuid("{3214FAB5-9757-4298-BB61-92A9DEAA44FF}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%PUBLIC%\Music")] [DefaultPath(@"%ALLUSERSPROFILE%\Documents\My Music")] [DisplayName("Public Music")] [Csidl(ShellAPI.CSIDL.CSIDL_COMMON_MUSIC)] [SpecialFolder(Environment.SpecialFolder.CommonMusic)] PublicMusic, [KnownFolderGuid("{B6EBFB86-6907-413C-9AF7-4FC2ABF07CC5}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%PUBLIC%\Pictures")] [DefaultPath(@"%ALLUSERSPROFILE%\Documents\My Pictures")] [DisplayName("Public Pictures")] [Csidl(ShellAPI.CSIDL.CSIDL_COMMON_PICTURES)] [SpecialFolder(Environment.SpecialFolder.CommonPictures)] PublicPictures, [KnownFolderGuid("{E555AB60-153B-4D17-9F04-A5FE99FC15EC}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%ALLUSERSPROFILE%\Microsoft\Windows\Ringtones")] [DisplayName("Ringtones")] [MinVersion(OSVersions.Windows7)] PublicRingtones, [KnownFolderGuid("{0482af6c-08f1-4c34-8c90-e17ec98b1e17}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%PUBLIC%\AccountPictures")] [DisplayName("Public Account Pictures")] [MinVersion(OSVersions.Windows8)] PublicUserTiles, [KnownFolderGuid("{2400183A-6185-49FB-A2D8-4A392A602BA3}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%PUBLIC%\Videos")] [DefaultPath(@"%ALLUSERSPROFILE%\Documents\My Videos")] [DisplayName("Public Videos")] [Csidl(ShellAPI.CSIDL.CSIDL_COMMON_VIDEO)] [SpecialFolder(Environment.SpecialFolder.CommonVideos)] PublicVideos, [KnownFolderGuid("{52a4f021-7b75-48a9-9f6b-4b87a210bc8f}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%APPDATA%\Microsoft\Internet Explorer\Quick Launch")] [DisplayName("Quick Launch")] QuickLaunch, [KnownFolderGuid("{AE50C081-EBD2-438A-8655-8A092E34987A}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%APPDATA%\Microsoft\Windows\Recent")] [DisplayName("Recent Items")] [Csidl(ShellAPI.CSIDL.CSIDL_RECENT)] [SpecialFolder(Environment.SpecialFolder.Recent)] Recent, //[MinVersion(OSVersions.Windows7)] //RecordedTV, [KnownFolderGuid("{1A6FDBA2-F42D-4358-A798-B74D745926C5}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%PUBLIC%\RecordedTV.library-ms")] [DisplayName("Recorded TV")] [MinVersion(OSVersions.Windows7)] RecordedTVLibrary, [KnownFolderGuid("{B7534046-3ECB-4C18-BE4E-64CD4CB7D6AC}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Recycle Bin")] [Csidl(ShellAPI.CSIDL.CSIDL_BITBUCKET)] RecycleBinFolder, [KnownFolderGuid("{8AD10C31-2ADB-4296-A8F7-E4701232C972}")] [FolderCategory(KnownFolderCategory.Fixed)] [DefaultPath(@"%windir%\Resources")] [DisplayName("Resources")] [Csidl(ShellAPI.CSIDL.CSIDL_RESOURCES)] [SpecialFolder(Environment.SpecialFolder.Resources)] ResourceDir, [KnownFolderGuid("{C870044B-F49E-4126-A9C3-B52A1FF411E8}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%LOCALAPPDATA%\Microsoft\Windows\Ringtones")] [DisplayName("Ringtones")] [MinVersion(OSVersions.Windows7)] Ringtones, [KnownFolderGuid("{3EB685DB-65F9-4CF6-A03A-E3EF65729F3D}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%APPDATA%")] [DefaultPath(@"%USERPROFILE%\AppData\Roaming")] [DefaultPath(@"%USERPROFILE%\Application Data")] [DisplayName("Roaming")] [Csidl(ShellAPI.CSIDL.CSIDL_APPDATA)] [SpecialFolder(Environment.SpecialFolder.ApplicationData)] RoamingAppData, [KnownFolderGuid("{AAA8D5A5-F1D6-4259-BAA8-78E7EF60835E}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%LOCALAPPDATA%\Microsoft\Windows\RoamedTileImages")] [DisplayName("RoamedTileImages")] [MinVersion(OSVersions.Windows8)] RoamedTileImages, [KnownFolderGuid("{00BCFC5A-ED94-4e48-96A1-3F6217F21990}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%LOCALAPPDATA%\Microsoft\Windows\RoamingTiles")] [DisplayName("RoamingTiles")] [MinVersion(OSVersions.Windows8)] RoamingTiles, [KnownFolderGuid("{B250C668-F57D-4EE1-A63C-290EE7D1AA1F}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%PUBLIC%\Music\Sample Music")] [DisplayName("Sample Music")] SampleMusic, [KnownFolderGuid("{C4900540-2379-4C75-844B-64E6FAF8716B}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%PUBLIC%\Pictures\Sample Pictures")] [DisplayName("Sample Pictures")] SamplePictures, [KnownFolderGuid("{15CA69B3-30EE-49C1-ACE1-6B5EC372AFB5}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%PUBLIC%\Music\Sample Playlists")] [DisplayName("Sample Playlists")] [MinVersion(OSVersions.WindowsVista)] SamplePlaylists, [KnownFolderGuid("{859EAD94-2E85-48AD-A71A-0969CB56A6CD}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%PUBLIC%\Videos\Sample Videos")] [DisplayName("Sample Videos")] SampleVideos, [KnownFolderGuid("{4C5C32FF-BB9D-43b0-B5B4-2D72E54EAAA4}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\Saved Games")] [DisplayName("Saved Games")] [MinVersion(OSVersions.WindowsVista)] SavedGames, [KnownFolderGuid("{7d1d3a04-debb-4115-95cf-2f29da2920da}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\Searches")] [DisplayName("Searches")] SavedSearches, [KnownFolderGuid("{b7bede81-df94-4682-a7d8-57a52620b86f}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\Pictures\Screenshots")] [DisplayName("Screenshots")] [MinVersion(OSVersions.Windows8)] Screenshots, [KnownFolderGuid("{ee32e446-31ca-4aba-814f-a5ebd2fd6d5e}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Offline Files")] SEARCH_CSC, [KnownFolderGuid("{0D4C3DB6-03A3-462F-A0E6-08924C41B5D4}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%LOCALAPPDATA%\Microsoft\Windows\ConnectedSearch\History")] [DisplayName("History")] [MinVersion(OSVersions.Windows81)] SearchHistory, [KnownFolderGuid("{190337d1-b8ca-4121-a639-6d472d16972a}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Search Results")] SearchHome, [KnownFolderGuid("{98ec0e18-2098-4d44-8644-66979315a281}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Microsoft Office Outlook")] SEARCH_MAPI, [KnownFolderGuid("{7E636BFE-DFA9-4D5E-B456-D7B39851D8A9}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%LOCALAPPDATA%\Microsoft\Windows\ConnectedSearch\Templates")] [DisplayName("Templates")] [MinVersion(OSVersions.Windows81)] SearchTemplates, [KnownFolderGuid("{8983036C-27C0-404B-8F08-102D10DCFD74}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%APPDATA%\Microsoft\Windows\SendTo")] [DefaultPath(@"%USERPROFILE%\SendTo")] [DisplayName("SendTo")] [Csidl(ShellAPI.CSIDL.CSIDL_SENDTO)] [SpecialFolder(Environment.SpecialFolder.SendTo)] SendTo, [KnownFolderGuid("{7B396E54-9EC5-4300-BE0A-2482EBAE1A26}")] [FolderCategory(KnownFolderCategory.Common)] [DefaultPath(@"%ProgramFiles%\Windows Sidebar\Gadgets")] [DisplayName("Gadgets")] [MinVersion(OSVersions.Windows7)] SidebarDefaultParts, [KnownFolderGuid("{A75D362E-50FC-4fb7-AC2C-A8BEAA314493}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%LOCALAPPDATA%\Microsoft\Windows Sidebar\Gadgets")] [DisplayName("Gadgets")] [MinVersion(OSVersions.Windows7)] SidebarParts, [KnownFolderGuid("{A52BBA46-E9E1-435f-B3D9-28DAA648C0F6}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\OneDrive")] [DisplayName("OneDrive")] [MinVersion(OSVersions.Windows81)] SkyDrive, [KnownFolderGuid("{767E6811-49CB-4273-87C2-20F355E1085B}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\OneDrive\Pictures\Camera Roll")] [DisplayName("Camera Roll")] [MinVersion(OSVersions.Windows81)] SkyDriveCameraRoll, [KnownFolderGuid("{24D89E24-2F19-4534-9DDE-6A6671FBB8FE}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\OneDrive\Documents")] [DisplayName("Documents")] [MinVersion(OSVersions.Windows81)] SkyDriveDocuments, [KnownFolderGuid("{339719B5-8C47-4894-94C2-D8F77ADD44A6}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\OneDrive\Pictures")] [DisplayName("Pictures")] [MinVersion(OSVersions.Windows81)] SkyDrivePictures, [KnownFolderGuid("{625B53C3-AB48-4EC1-BA1F-A1EF4146FC19}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%APPDATA%\Microsoft\Windows\Start Menu")] [DisplayName("Start Menu")] [Csidl(ShellAPI.CSIDL.CSIDL_STARTMENU)] [SpecialFolder(Environment.SpecialFolder.StartMenu)] StartMenu, [KnownFolderGuid("{B97D20BB-F46A-4C97-BA10-5E3608430854}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%APPDATA%\Microsoft\Windows\Start Menu\Programs\StartUp")] [DefaultPath(@"%USERPROFILE%\Start Menu\Programs\StartUp")] [DisplayName("Startup")] [Csidl(ShellAPI.CSIDL.CSIDL_STARTUP)] [Csidl(ShellAPI.CSIDL.CSIDL_ALTSTARTUP)] [SpecialFolder(Environment.SpecialFolder.Startup)] Startup, [KnownFolderGuid("{43668BF8-C14E-49B2-97C9-747784D784B7}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Sync Center")] [MinVersion(OSVersions.WindowsVista)] SyncManagerFolder, [KnownFolderGuid("{289a9a43-be44-4057-a41b-587a76d7e7f9}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Sync Results")] [MinVersion(OSVersions.WindowsVista)] SyncResultsFolder, [KnownFolderGuid("{0F214138-B1D3-4a90-BBA9-27CBC0C5389A}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Sync Setup")] [MinVersion(OSVersions.WindowsVista)] SyncSetupFolder, [KnownFolderGuid("{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}")] [FolderCategory(KnownFolderCategory.Fixed)] [DefaultPath(@"%windir%\system32")] [DisplayName("system32")] [Csidl(ShellAPI.CSIDL.CSIDL_SYSTEM)] [SpecialFolder(Environment.SpecialFolder.System)] System, [KnownFolderGuid("{D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27}")] [FolderCategory(KnownFolderCategory.Fixed)] [DefaultPath(@"%windir%\system32")] [DisplayName("system32")] [Csidl(ShellAPI.CSIDL.CSIDL_SYSTEMX86)] [SpecialFolder(Environment.SpecialFolder.SystemX86)] SystemX86, [KnownFolderGuid("{A63293E8-664E-48DB-A079-DF759E0509F7}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%APPDATA%\Microsoft\Windows\Templates")] [DefaultPath(@"%USERPROFILE%\Templates")] [DisplayName("Templates")] [Csidl(ShellAPI.CSIDL.CSIDL_TEMPLATES)] [SpecialFolder(Environment.SpecialFolder.Templates)] Templates, //[MinVersion(OSVersions.WindowsVista)] //TreeProperties, [KnownFolderGuid("{9E3995AB-1F9C-4F13-B827-48B24B6C7174}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%APPDATA%\Microsoft\Internet Explorer\Quick Launch\User Pinned")] [DisplayName("User Pinned")] [MinVersion(OSVersions.Windows7)] UserPinned, [KnownFolderGuid("{0762D272-C50A-4BB0-A382-697DCD729B80}")] [FolderCategory(KnownFolderCategory.Fixed)] [DefaultPath(@"%SystemDrive%\Users")] [DisplayName("Users")] [MinVersion(OSVersions.WindowsVista)] UserProfiles, [KnownFolderGuid("{5CD7AEE2-2219-4A67-B85D-6C9CE15660CB}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%LOCALAPPDATA%\Programs")] [DisplayName("Programs")] [MinVersion(OSVersions.Windows7)] UserProgramFiles, [KnownFolderGuid("{BCBD3057-CA5C-4622-B42D-BC56DB0AE516}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%LOCALAPPDATA%\Programs\Common")] [DisplayName("Programs")] [MinVersion(OSVersions.Windows7)] UserProgramFilesCommon, [KnownFolderGuid("{f3ce0f7c-4901-4acc-8648-d5d44b04ef8f}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("%USERNAME%")] UsersFiles, [KnownFolderGuid("{A302545D-DEFF-464b-ABE8-61C8648D939B}")] [FolderCategory(KnownFolderCategory.Virtual)] [DisplayName("Libraries")] [MinVersion(OSVersions.Windows7)] UsersLibraries, [KnownFolderGuid("{18989B1D-99B5-455B-841C-AB7C74E4DDFC}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%USERPROFILE%\Videos")] [DefaultPath(@"%USERPROFILE%\My Documents\My Videos")] [DisplayName("Videos")] [Csidl(ShellAPI.CSIDL.CSIDL_MYVIDEO)] [SpecialFolder(Environment.SpecialFolder.MyVideos)] Videos, [KnownFolderGuid("{491E922F-5643-4AF4-A7EB-4E7A138D8174}")] [FolderCategory(KnownFolderCategory.PerUser)] [DefaultPath(@"%APPDATA%\Microsoft\Windows\Libraries\Videos.library-ms")] [DisplayName("Videos")] [MinVersion(OSVersions.Windows7)] VideosLibrary, [KnownFolderGuid("{F38BF404-1D43-42F2-9305-67DE0B28FC23}")] [FolderCategory(KnownFolderCategory.Fixed)] [DefaultPath(@"%windir%")] [DisplayName("Windows")] [Csidl(ShellAPI.CSIDL.CSIDL_WINDOWS)] [SpecialFolder(Environment.SpecialFolder.Windows)] Windows //[KnownFolderGuid("")] //[FolderCategory(KnownFolderCategory.)] //[DefaultPath(@"")] //[DisplayName("")] //[Csidl(ShellAPI.CSIDL.)] //[SpecialFolder(Environment.SpecialFolder)] //[MinVersion(OSVersions.Windows81)] } }
42.568207
102
0.658033
[ "MIT" ]
philvanzu/Bubbles
Dependencies/XamlFileSystemExplorer/FSExplorer/FileSystemInfoEx/Header/KnownFolder/Enums/KnownFolderIds.cs
37,760
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PaperMarioBattleSystem { /// <summary> /// A BattleEvent that removes an <see cref="IWingedBehavior"/>'s wings when it stops being targeted. /// </summary> public sealed class RemoveWingsBattleEvent : BattleEvent { private IWingedBehavior WingedEntity = null; private BattleEntity Entity = null; public RemoveWingsBattleEvent(IWingedBehavior wingedEntity, BattleEntity entity) { WingedEntity = wingedEntity; Entity = entity; } protected override void OnUpdate() { //Don't do anything with invalid input if (WingedEntity == null || Entity == null) { Debug.LogError($"A null {nameof(IWingedBehavior)} or {nameof(BattleEntity)} has been passed in. Fix this"); End(); return; } //If the entity is no longer targeted, remove its wings and end if (Entity.IsTargeted == false) { WingedEntity.RemoveWings(); End(); } } } }
29.697674
124
0.562255
[ "Unlicense" ]
kimimaru4000/PaperMarioBattleSystem
PaperMarioBattleSystem/PaperMarioBattleSystem/Classes/BattleEvents/RemoveWingsBattleEvent.cs
1,279
C#
using System; using TrueCraft.API.Logic; using TrueCraft.API.World; using TrueCraft.API; using TrueCraft.API.Networking; using TrueCraft.Core.Entities; using TrueCraft.API.Entities; using TrueCraft.API.Server; using TrueCraft.Core.Logic.Blocks; using System.Linq; using fNbt; namespace TrueCraft.Core.Logic { /// <summary> /// Provides common implementations of block logic. /// </summary> public abstract class BlockProvider : IItemProvider, IBlockProvider { public static IBlockRepository BlockRepository { get; set; } public static IItemRepository ItemRepository { get; set; } public virtual void BlockLeftClicked(BlockDescriptor descriptor, BlockFace face, IWorld world, IRemoteClient user) { // This space intentionally left blank } public virtual bool BlockRightClicked(BlockDescriptor descriptor, BlockFace face, IWorld world, IRemoteClient user) { return true; } public virtual void BlockPlaced(BlockDescriptor descriptor, BlockFace face, IWorld world, IRemoteClient user) { // This space intentionally left blank } public virtual void BlockMined(BlockDescriptor descriptor, BlockFace face, IWorld world, IRemoteClient user) { GenerateDropEntity(descriptor, world, user.Server, user.SelectedItem); world.SetBlockID(descriptor.Coordinates, 0); } public void GenerateDropEntity(BlockDescriptor descriptor, IWorld world, IMultiplayerServer server, ItemStack item) { var entityManager = server.GetEntityManagerForWorld(world); var items = new ItemStack[0]; var type = ToolType.None; var material = ToolMaterial.None; var held = ItemRepository.GetItemProvider(item.ID); if (held is ToolItem) { var tool = held as ToolItem; material = tool.Material; type = tool.ToolType; } if ((EffectiveTools & type) > 0) { if ((EffectiveToolMaterials & material) > 0) items = GetDrop(descriptor, item); } foreach (var i in items) { if (i.Empty) continue; var entity = new ItemEntity(new Vector3(descriptor.Coordinates) + new Vector3(0.5), i); entityManager.SpawnEntity(entity); } } public virtual bool IsSupported(BlockDescriptor descriptor, IMultiplayerServer server, IWorld world) { var support = GetSupportDirection(descriptor); if (support != Coordinates3D.Zero) { var supportingBlock = server.BlockRepository.GetBlockProvider(world.GetBlockID(descriptor.Coordinates + support)); if (!supportingBlock.Opaque) return false; } return true; } public virtual void BlockUpdate(BlockDescriptor descriptor, BlockDescriptor source, IMultiplayerServer server, IWorld world) { if (!IsSupported(descriptor, server, world)) { GenerateDropEntity(descriptor, world, server, ItemStack.EmptyStack); world.SetBlockID(descriptor.Coordinates, 0); } } public virtual void BlockScheduledEvent(BlockDescriptor descriptor, IWorld world, object data) { // This space intentionally left blank } protected virtual ItemStack[] GetDrop(BlockDescriptor descriptor, ItemStack item) { short meta = 0; if (this is ICraftingRecipe) meta = (short)((this as ICraftingRecipe).SignificantMetadata ? descriptor.Metadata : 0); return new[] { new ItemStack(descriptor.ID, 1, meta) }; } public virtual void ItemUsedOnEntity(ItemStack item, IEntity usedOn, IWorld world, IRemoteClient user) { // This space intentionally left blank } public virtual void ItemUsedOnNothing(ItemStack item, IWorld world, IRemoteClient user) { // This space intentionally left blank } public virtual void ItemUsedOnBlock(Coordinates3D coordinates, ItemStack item, BlockFace face, IWorld world, IRemoteClient user) { coordinates += MathHelper.BlockFaceToCoordinates(face); var old = world.GetBlockData(coordinates); byte[] overwritable = { AirBlock.BlockID, WaterBlock.BlockID, StationaryWaterBlock.BlockID, LavaBlock.BlockID, StationaryLavaBlock.BlockID }; if (overwritable.Any(b => b == old.ID)) { world.SetBlockID(coordinates, ID); world.SetMetadata(coordinates, (byte)item.Metadata); BlockPlaced(world.GetBlockData(coordinates), face, world, user); if (!IsSupported(world.GetBlockData(coordinates), user.Server, world)) world.SetBlockData(coordinates, old); else { item.Count--; user.Inventory[user.SelectedSlot] = item; } } } public virtual void BlockLoadedFromChunk(BlockDescriptor descriptor, IMultiplayerServer server, IWorld world) { // This space intentionally left blank } public virtual void TileEntityLoadedForClient(BlockDescriptor descriptor, IWorld world, NbtCompound entity, IRemoteClient client) { // This space intentionally left blank } short IItemProvider.ID { get { return ID; } } /// <summary> /// The ID of the block. /// </summary> public abstract byte ID { get; } public virtual Coordinates3D GetSupportDirection(BlockDescriptor descriptor) { return Coordinates3D.Zero; } /// <summary> /// The maximum amount that can be in a single stack of this block. /// </summary> public virtual sbyte MaximumStack { get { return 64; } } /// <summary> /// How resist the block is to explosions. /// </summary> public virtual double BlastResistance { get { return 0; } } /// <summary> /// How resist the block is to player mining/digging. /// </summary> public virtual double Hardness { get { return 0; } } /// <summary> /// The light level emitted by the block. 0 - 15 /// </summary> public virtual byte Luminance { get { return 0; } } /// <summary> /// Whether or not the block is opaque /// </summary> public virtual bool Opaque { get { return true; } } /// <summary> /// Whether or not the block is rendered opaque /// </summary> public virtual bool RenderOpaque { get { return Opaque; } } /// <summary> /// The amount removed from the light level as it passes through this block. /// 255 - Let no light pass through(this may change) /// Notes: /// - This isn't needed for opaque blocks /// - This is needed since some "partial" transparent blocks remove more than 1 level from light passing through such as Ice. /// </summary> public virtual byte LightModifier { get { if (Opaque) return 255; else return 0; } } public virtual bool DiffuseSkyLight { get { return false; } } /// <summary> /// The name of the block as it would appear to players. /// </summary> public virtual string DisplayName { get { return string.Empty; } } public virtual ToolMaterial EffectiveToolMaterials { get { return ToolMaterial.All; } } public virtual ToolType EffectiveTools { get { return ToolType.All; } } public virtual Tuple<int, int> GetTextureMap(byte metadata) { return null; } public virtual BoundingBox? BoundingBox { get { return new BoundingBox(Vector3.Zero, Vector3.One); } } } }
34.642276
137
0.578972
[ "MIT" ]
manio143/TrueCraft
TrueCraft.Core/Logic/BlockProvider.cs
8,524
C#
using UnityEngine; using UnityEngine.UI; using System.Collections; using UnityEngine.InputSystem; public class TouchController : MonoBehaviour { // PUBLIC public delegate void TouchDelegate(Vector2 value); public event TouchDelegate TouchEvent; public delegate void TouchStateDelegate(bool touchPresent); public event TouchStateDelegate TouchStateEvent; // PRIVATE [SerializeField] private RectTransform joystickArea; private bool touchPresent = false; private Vector2 movementVector; private PlayerAction _input; public Vector2 GetTouchPosition { get { return movementVector;} } private void Awake() { _input = new PlayerAction(); } private void OnEnable() { _input.Enable(); } private void OnDisable() { _input.Disable(); } private void Start() { _input.TouchScreen.TouchInput.started += ctx => StartTouch(ctx); _input.TouchScreen.TouchInput.canceled += ctx => EndTouch(ctx); } private void StartTouch(InputAction.CallbackContext ctx) { Debug.Log(Vector2.Distance(_input.TouchScreen.TouchPosition.ReadValue<Vector2>(), Camera.main.WorldToScreenPoint(joystickArea.position))); if (Vector2.Distance(_input.TouchScreen.TouchPosition.ReadValue<Vector2>(), Camera.main.WorldToScreenPoint(joystickArea.position)) < 80f) { touchPresent = true; if (TouchStateEvent != null) TouchStateEvent(touchPresent); } } private void EndTouch(InputAction.CallbackContext ctx) { touchPresent = false; movementVector = joystickArea.anchoredPosition = Vector2.zero; if (TouchStateEvent != null) TouchStateEvent(touchPresent); } public void BeginDrag() { touchPresent = true; if(TouchStateEvent != null) TouchStateEvent(touchPresent); } public void EndDrag() { touchPresent = false; movementVector = joystickArea.anchoredPosition = Vector2.zero; if(TouchStateEvent != null) TouchStateEvent(touchPresent); } public void OnValueChanged(Vector2 value) { if(touchPresent) { // convert the value between 1 0 to -1 +1 movementVector.x = ((1 - value.x) - 0.5f) * 2f; movementVector.y = ((1 - value.y) - 0.5f) * 2f; if(TouchEvent != null) { TouchEvent(movementVector); } } } }
21.190476
140
0.720899
[ "CC0-1.0" ]
maryphun/Hellfight
Assets/Scripts/TouchController.cs
2,227
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense { internal class Session<TController, TModel, TPresenterSession> : ForegroundThreadAffinitizedObject, ISession<TModel> where TPresenterSession : IIntelliSensePresenterSession where TController : IController<TModel> where TModel : class { public TController Controller { get; } public ModelComputation<TModel> Computation { get; } // The presenter session for the computation we've got going. It's lifetime is tied 1:1 with // the computation. When the computation starts we make a presenter (note: this does not // mean that the user will ever see any UI), and when the computation is stopped, we will // end the presentation session. public TPresenterSession PresenterSession { get; } public Session( TController controller, ModelComputation<TModel> computation, TPresenterSession presenterSession ) : base(computation.ThreadingContext) { this.Controller = controller; this.Computation = computation; this.PresenterSession = presenterSession; // If the UI layer dismisses the presenter, then we want to know about it so we can stop // doing whatever it is we're doing. this.PresenterSession.Dismissed += OnPresenterSessionDismissed; } public TModel InitialUnfilteredModel { get { return this.Computation.InitialUnfilteredModel; } } private void OnPresenterSessionDismissed(object sender, EventArgs e) { AssertIsForeground(); Contract.ThrowIfFalse(ReferenceEquals(this.PresenterSession, sender)); Controller.StopModelComputation(); } public virtual void Stop() { AssertIsForeground(); this.Computation.Stop(); this.PresenterSession.Dismissed -= OnPresenterSessionDismissed; this.PresenterSession.Dismiss(); } public TModel WaitForController() { AssertIsForeground(); return Computation.WaitForController(); } } }
36.239437
101
0.658764
[ "MIT" ]
belav/roslyn
src/EditorFeatures/Core/Implementation/IntelliSense/Session.cs
2,575
C#
/** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/fee/blob/master/LICENSE.txt * @brief 削除管理。コールバックインターフェイス。 */ /** Fee.Deleter */ namespace Fee.Deleter { /** OnDelete_CallBackInterface */ public interface OnDelete_CallBackInterface { /** [Fee.Deleter.OnDelete_CallBackInterface]削除。 */ void OnDelete(); } }
14.88
62
0.704301
[ "MIT" ]
bluebackblue/fee
Script/Deleter/OnDelete_CallBackInterface.cs
418
C#
using JT808.Protocol.Enums; using JT808.Protocol.Extensions; using JT808.Protocol.Formatters; using JT808.Protocol.Interfaces; using JT808.Protocol.MessagePack; using System.Text.Json; namespace JT808.Protocol.MessageBody { /// <summary> /// 终端升级结果通知 /// </summary> public class JT808_0x0108 : JT808Bodies, IJT808MessagePackFormatter<JT808_0x0108>, IJT808Analyze { public override ushort MsgId { get; } = 0x0108; public override string Description => "终端升级结果通知"; /// <summary> /// 升级类型 /// 0:终端,12:道路运输证 IC 卡读卡器,52:北斗卫星定位模块 /// </summary> public JT808UpgradeType UpgradeType { get; set; } /// <summary> /// 升级结果 /// 0:成功,1:失败,2:取消 /// </summary> public JT808UpgradeResult UpgradeResult { get; set; } public JT808_0x0108 Deserialize(ref JT808MessagePackReader reader, IJT808Config config) { JT808_0x0108 jT808_0X0108 = new JT808_0x0108(); jT808_0X0108.UpgradeType = (JT808UpgradeType)reader.ReadByte(); jT808_0X0108.UpgradeResult = (JT808UpgradeResult)reader.ReadByte(); return jT808_0X0108; } public void Serialize(ref JT808MessagePackWriter writer, JT808_0x0108 value, IJT808Config config) { writer.WriteByte((byte)value.UpgradeType); writer.WriteByte((byte)value.UpgradeResult); } public void Analyze(ref JT808MessagePackReader reader, Utf8JsonWriter writer, IJT808Config config) { JT808_0x0108 jT808_0X0108 = new JT808_0x0108(); jT808_0X0108.UpgradeType = (JT808UpgradeType)reader.ReadByte(); jT808_0X0108.UpgradeResult = (JT808UpgradeResult)reader.ReadByte(); writer.WriteString($"[{((byte)jT808_0X0108.UpgradeType).ReadNumber()}]升级类型", jT808_0X0108.UpgradeType.ToString()); writer.WriteString($"[{((byte)jT808_0X0108.UpgradeResult).ReadNumber()}]升级结果", jT808_0X0108.UpgradeResult.ToString()); } } }
38.377358
130
0.6588
[ "MIT" ]
AchaInChina/JT808
src/JT808.Protocol/MessageBody/JT808_0x0108.cs
2,170
C#
#pragma warning disable CS0626 // Method, operator, or accessor is marked external and has no attributes on it using Celeste.Mod; using Celeste.Mod.Core; using Microsoft.Xna.Framework; using Monocle; using MonoMod; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Celeste { class patch_GameLoader : GameLoader { // We're effectively in GameLoader, but still need to "expose" private fields to our mod. private Entity handler; private bool loaded; private bool audioLoaded; private bool audioStarted; private bool dialogLoaded; private bool ready; [MonoModIfFlag("HasIntroSkip")] private bool skipped; private List<MTexture> loadingTextures; private float loadingFrame; private float loadingAlpha; // Add a new field as we need to access the intro coroutine later. private Coroutine introRoutine; public extern void orig_Begin(); public override void Begin() { // Note: You may instinctually call base.Begin(); // DON'T! The original method is orig_Begin orig_Begin(); // Assume that the intro routine is the first added coroutine. foreach (Coroutine c in handler.Components) { introRoutine = c; break; } if (CoreModule.Settings.LaunchWithoutIntro && introRoutine != null) { SkipIntro(); } } public extern void orig_Update(); public override void Update() { if (!ready) { bool inputDisabled = MInput.Disabled; MInput.Disabled = false; if (Input.Pause.Pressed || Input.ESC.Pressed) { if (Input.MenuDown.Check) { Celeste.PlayMode = Celeste.PlayModes.Debug; // Late-enable commands. This is normally set by Celeste.Initialize. Engine.Commands.Enabled = true; } SkipIntro(); } MInput.Disabled = inputDisabled; } // Note: You may instinctually call base.Update(); // DON'T! The original method is orig_Update orig_Update(); } [MonoModReplace] private void LoadThread() { Console.WriteLine("GAME DISPLAYED : " + Stopwatch.ElapsedMilliseconds + "ms"); MInput.Disabled = true; Audio.Init(); // Original code loads audio banks here. /* Audio.Banks.Master = Audio.Banks.Load("Master Bank", true); Audio.Banks.Music = Audio.Banks.Load("music", false); Audio.Banks.Sfxs = Audio.Banks.Load("sfx", false); Audio.Banks.UI = Audio.Banks.Load("ui", false); */ Settings.Instance.ApplyVolumes(); audioLoaded = true; Fonts.Load(); // Luckily, the textures for the fonts are preloaded. Dialog.Load(); dialogLoaded = true; MInput.Disabled = false; if (!GFX.LoadedMainContent) { throw new Exception("GFX not loaded!"); } GFX.LoadData(); // Load all related GFX metadata. AreaData.Load(); if (!CoreModule.Settings.NonThreadedGL) { GFX.MountainTerrain = ObjModel.Create(Path.Combine(Engine.ContentDirectory, "Overworld", "mountain.obj")); GFX.MountainBuildings = ObjModel.Create(Path.Combine(Engine.ContentDirectory, "Overworld", "buildings.obj")); GFX.MountainCoreWall = ObjModel.Create(Path.Combine(Engine.ContentDirectory, "Overworld", "mountain_wall.obj")); } // Otherwise loaded in CoreModule.LoadContent Console.WriteLine("LOADED : " + Stopwatch.ElapsedMilliseconds + "ms"); Stopwatch.Stop(); Stopwatch = null; loaded = true; } [MonoModIfFlag("HasIntroSkip")] private void SkipIntro() { skipped = true; } // If we're on a version < 1.1.9.2, relink all SkipIntro calls to SkipIntroOld. [MonoModIfFlag("LacksIntroSkip")] [MonoModHook("System.Void Celeste.GameLoader::SkipIntro()")] private void SkipIntroOld() { introRoutine.Cancel(); introRoutine = null; handler.Add(new Coroutine(FastIntroRoutine())); } [MonoModIfFlag("LacksIntroSkip")] public IEnumerator FastIntroRoutine() { if (!loaded) { loadingTextures = GFX.Overworld.GetAtlasSubtextures("loading/"); Image img = new Image(loadingTextures[0]); img.CenterOrigin(); img.Scale = Vector2.One * 0.5f; handler.Add(img); while (!loaded || loadingAlpha > 0f) { loadingFrame += Engine.DeltaTime * 10f; loadingAlpha = Calc.Approach(loadingAlpha, loaded ? 0f : 1f, Engine.DeltaTime * 4f); img.Texture = loadingTextures[(int) (loadingFrame % loadingTextures.Count)]; img.Color = Color.White * Ease.CubeOut(loadingAlpha); img.Position = new Vector2(1792f, 1080f - 128f * Ease.CubeOut(loadingAlpha)); yield return null; } img = null; } Engine.Scene = new OverworldLoader(Overworld.StartMode.Titlescreen, Snow); } } }
34.612121
128
0.567151
[ "MIT" ]
SSZero88/SteveMod
Everest/Celeste.Mod.mm/Patches/GameLoader.cs
5,713
C#
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Linq; using System.Linq.Expressions; using System.Collections.Generic; using Telerik.OpenAccess; using Telerik.OpenAccess.Metadata; using Telerik.OpenAccess.Data.Common; using Telerik.OpenAccess.Metadata.Fluent; using Telerik.OpenAccess.Metadata.Fluent.Advanced; using OimsDataModel; namespace OimsDataModel { public partial class Request { private int _o_Id; public virtual int O_Id { get { return this._o_Id; } set { this._o_Id = value; } } private int _o_CreatedBy; public virtual int O_CreatedBy { get { return this._o_CreatedBy; } set { this._o_CreatedBy = value; } } private DateTime _o_CreatedDate; public virtual DateTime O_CreatedDate { get { return this._o_CreatedDate; } set { this._o_CreatedDate = value; } } private int? _o_UpdatedBy; public virtual int? O_UpdatedBy { get { return this._o_UpdatedBy; } set { this._o_UpdatedBy = value; } } private DateTime? _o_UpdatedDate; public virtual DateTime? O_UpdatedDate { get { return this._o_UpdatedDate; } set { this._o_UpdatedDate = value; } } private string _o_Job; public virtual string O_Job { get { return this._o_Job; } set { this._o_Job = value; } } private int _o_Status; public virtual int O_Status { get { return this._o_Status; } set { this._o_Status = value; } } private string _o_Company; public virtual string O_Company { get { return this._o_Company; } set { this._o_Company = value; } } private Company _company; public virtual Company Company { get { return this._company; } set { this._company = value; } } private Requeststatus _requeststatus; public virtual Requeststatus Requeststatus { get { return this._requeststatus; } set { this._requeststatus = value; } } private User _user; public virtual User User { get { return this._user; } set { this._user = value; } } private IList<Sheltersrequest> _sheltersrequests = new List<Sheltersrequest>(); public virtual IList<Sheltersrequest> Sheltersrequests { get { return this._sheltersrequests; } } private IList<Itemsrequest> _itemsrequests = new List<Itemsrequest>(); public virtual IList<Itemsrequest> Itemsrequests { get { return this._itemsrequests; } } private IList<Allocated> _allocateds = new List<Allocated>(); public virtual IList<Allocated> Allocateds { get { return this._allocateds; } } } }
18.823232
82
0.507915
[ "MIT" ]
vssaini/OIMS
OimsDataModel/Request.generated.cs
3,727
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.Diagnostics.CodeAnalysis; #nullable disable namespace Microsoft.VisualStudio.ProjectSystem { [ExcludeFromCodeCoverage] [SuppressMessage("Style", "IDE0016:Use 'throw' expression")] internal partial class Compile { } }
27.666667
161
0.749398
[ "Apache-2.0" ]
JeremyKuhne/project-system
src/Microsoft.VisualStudio.ProjectSystem.Managed/ProjectSystem/Rules/Items/Compile.cs
417
C#
using LogViewer.Services; using LogViewer.ViewModel; using Moq; using NUnit.Framework; namespace LogViewer.Test { [TestFixture] public class MainViewModelTest { [TestCase] public void OpenFile_ReturnFileName_ShouldStartWatch() { string filePath = "sample_log_file"; var fileOpenService = new Mock<IFileOpenService>(); fileOpenService.Setup(t => t.OpenFile()).Returns(filePath); var fileWatcher = new Mock<IFileWatcher>(); var viewModel = new MainViewModel(fileOpenService.Object, fileWatcher.Object); viewModel.OpenFileCommand.Execute(null); fileWatcher.Verify(t => t.Start(filePath), Times.Once); } [TestCase] public void OpenFile_ReturnNull_ShouldNotStartWatch() { string filePath = null; var fileOpenService = new Mock<IFileOpenService>(); fileOpenService.Setup(t => t.OpenFile()).Returns(filePath); var fileWatcher = new Mock<IFileWatcher>(); var viewModel = new MainViewModel(fileOpenService.Object, fileWatcher.Object); viewModel.OpenFileCommand.Execute(null); fileWatcher.VerifyNoOtherCalls(); } } }
30.095238
90
0.636867
[ "MIT" ]
jawahars16/logviewer
LogViewer.Test/MainViewModelTest.cs
1,266
C#
using System; using System.Collections.Generic; using System.Web; using YTS.Tools; using YTS.Web.UI; namespace YTS.Web.tools { /// <summary> /// article_ajax 的摘要说明 /// </summary> public class article_ajax : AbsHttpRequestHandler { public override Dictionary<string, Func<HttpContext, Model.AjaxResult, Model.AjaxResult>> ActionSource() { return new Dictionary<string, Func<HttpContext, Model.AjaxResult, Model.AjaxResult>> { { @"like", Like }, }; } public Model.AjaxResult Like(HttpContext context, Model.AjaxResult ajax) { int channel_id = ConvertTool.ToInt(DTRequest.GetString("channel_id"), 0); if (channel_id <= 0) { return ErrorAjaxResult(ajax, @"频道错误"); } int article_id = ConvertTool.ToInt(DTRequest.GetString("article_id"), 0); if (article_id <= 0) { return ErrorAjaxResult(ajax, @"文章错误"); } BLL.article bllarticle = new BLL.article(); string fieldname = ReflexHelp.Name(() => new Model.article().like_count); bool issu = bllarticle.UpdateField(channel_id, article_id, string.Format("{0} = {0} + 1", fieldname)); if (!issu) { return ErrorAjaxResult(ajax, @"点赞失败!"); } ajax.Status = Model.AjaxResult.StatusValue.Success; ajax.Msg = @"点赞成功!"; return ajax; } } }
34.534884
114
0.579798
[ "Apache-2.0" ]
YellowTulipShow/CSharp
dotnet_framework/YTS.Web/tools/article_ajax.ashx.cs
1,529
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QuartzCore.Blazor.Shared.MongoDB { public class PageInputByDateDto : PageInputDto { public DateTime? StartTime { get; set; } public DateTime? EndTime { get; set; } } }
21.6
50
0.709877
[ "MIT" ]
BaseCoreVueProject/QuartzCore.Blazor
QuartzCore.Blazor/Shared/MongoDB/PageInputByDateDto.cs
326
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Chloe")] [assembly: AssemblyDescription("A lightweight and high-performance Object/Relational Mapping(ORM) library.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Chloe.SqlServer")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a76eacb5-c6da-4cc2-8fe1-9edcc6bf7b46")] [assembly: AssemblyVersion("2.4.0.0")] [assembly: AssemblyFileVersion("2.4.0.0")]
42.12
109
0.777778
[ "Apache-2.0" ]
Davivd659/Chloe
src/DotNetCore/Chloe.SqlServer/Properties/AssemblyInfo.cs
1,055
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Caching; using System.Web.Hosting; using Telerik.Sitefinity.Abstractions.VirtualPath; namespace Telerik.Sitefinity.Frontend.Resources.Resolvers { /// <summary> /// This class implements a resource resolver node that gets resources from the file system. /// </summary> internal class FileSystemResourceResolver : ResourceResolverNode { private readonly static bool enableCacheDependencies; static FileSystemResourceResolver() { var enableCacheDependenciesString = System.Configuration.ConfigurationManager.AppSettings["sf:enableFileSystemCacheDependencies"]; if (enableCacheDependenciesString.IsNullOrEmpty() || !bool.TryParse(enableCacheDependenciesString, out enableCacheDependencies)) { enableCacheDependencies = true; } } /// <summary> /// Initializes a new instance of the <see cref="FileSystemResourceResolver"/> class. /// </summary> /// <remarks>By default resource virtual paths are rooted to the web application root folder.</remarks> public FileSystemResourceResolver() : this(() => "~/") { } /// <summary> /// Initializes a new instance of the <see cref="FileSystemResourceResolver"/> class. /// </summary> /// <param name="rootPathResolver">This delegate is used to root the resource virtual paths to a custom folder.</param> public FileSystemResourceResolver(Func<string> rootPathResolver) : base() { this.rootPathResolver = rootPathResolver; } /// <inheritdoc /> protected override CacheDependency GetCurrentCacheDependency(PathDefinition definition, string virtualPath, IEnumerable virtualPathDependencies, DateTime utcStart) { if (!enableCacheDependencies) return null; var fn = this.GetFileName(definition, virtualPath); if (string.IsNullOrWhiteSpace(fn)) { return null; } var dir = Path.GetDirectoryName(fn); if (!string.IsNullOrWhiteSpace(dir)) { // We can't monitor file changes on non-existing directories. if (Directory.Exists(dir)) { return new CacheDependency(fn, utcStart); } var parentDir = Path.GetDirectoryName(dir); while (!parentDir.IsNullOrEmpty() && !Directory.Exists(parentDir)) { dir = parentDir; parentDir = Path.GetDirectoryName(dir); } if (!string.IsNullOrWhiteSpace(parentDir)) { return new CacheDependency(dir, utcStart); } } return null; } /// <inheritdoc /> protected override bool CurrentExists(PathDefinition definition, string virtualPath) { var fn = this.GetFileName(definition, virtualPath); return fn != null && File.Exists(fn); } /// <inheritdoc /> protected override Stream CurrentOpen(PathDefinition definition, string virtualPath) { return File.OpenRead(this.GetFileName(definition, virtualPath)); } /// <inheritdoc /> protected override IEnumerable<string> GetCurrentFiles(PathDefinition definition, string path) { var mappedPath = this.GetFileName(definition, path); if (mappedPath != null && Directory.Exists(mappedPath)) { return Directory.GetFiles(mappedPath) .Select(f => f.Replace(mappedPath, path)); } return null; } protected override string CurrentGetFileHash(PathDefinition definition, string virtualPath, IEnumerable virtualPathDependencies) { var fileName = this.GetFileName(definition, virtualPath); if (fileName != null) { var questionMarkIndex = fileName.IndexOf("?"); if (questionMarkIndex != -1) fileName = fileName.Sub(0, questionMarkIndex - 1); if (File.Exists(fileName)) { var dateTime = File.GetLastWriteTimeUtc(fileName); return dateTime.GetHashCode().ToString(); } } return null; } /// <summary> /// Gets the filename of the requested resource. /// </summary> /// <param name="definition">The definition.</param> /// <param name="virtualPath">The virtual path.</param> protected virtual string GetFileName(PathDefinition definition, string virtualPath) { var rootPath = this.rootPathResolver(); if (rootPath == null) return null; var vp = VirtualPathUtility.ToAppRelative(virtualPath); var definitionVp = VirtualPathUtility.AppendTrailingSlash(VirtualPathUtility.ToAppRelative(definition.VirtualPath)); if (!vp.StartsWith(definitionVp, StringComparison.OrdinalIgnoreCase)) return null; var relativePath = vp.Substring(definitionVp.Length).Replace('/', '\\'); var mappedPath = Path.Combine(HostingEnvironment.MapPath(rootPath), relativePath); return mappedPath; } private Func<string> rootPathResolver; } }
36.227848
171
0.592243
[ "Apache-2.0" ]
Sitefinity/feather
Telerik.Sitefinity.Frontend/Resources/Resolvers/FileSystemResourceResolver.cs
5,726
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.AwsNative.Events.Inputs { public sealed class ConnectionParameterArgs : Pulumi.ResourceArgs { [Input("isValueSecret")] public Input<bool>? IsValueSecret { get; set; } [Input("key", required: true)] public Input<string> Key { get; set; } = null!; [Input("value", required: true)] public Input<string> Value { get; set; } = null!; public ConnectionParameterArgs() { } } }
26.689655
81
0.651163
[ "Apache-2.0" ]
AaronFriel/pulumi-aws-native
sdk/dotnet/Events/Inputs/ConnectionParameterArgs.cs
774
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Gurkenplayer { /// <summary> /// Manages the MPClient and MPServer instances while providing methods to access them. It makes sure /// that there is only one MPClient or one MPServer instance. The MPManager can only exist one time in /// the program. /// </summary> public class MPManager { // Fields static MPManager instance; bool isProcessMessageThreadRunning = false; MPRoleType mpRole = MPRoleType.None; MPClient mpClient; MPServer mpServer; // The message processing thread can be stopped by setting StopProcessMessageThread in MPManager // or even in MPClient/Server to true. They share this condition. // StopProcessMessageThread is also used by other threads like in the EcoExtBase class. static MPSharedCondition stopProcessMessageThread = new MPSharedCondition(false); // Properties /// <summary> /// Indicates the current status of te ProcessMessageThread. /// </summary> public bool IsProcessMessageThreadRunning { get { return isProcessMessageThreadRunning; } set { isProcessMessageThreadRunning = value; } } /// <summary> /// The condition which stops the ProcessMessage threads of netServer and client. /// </summary> public static MPSharedCondition StopProcessMessageThread { get { return MPManager.stopProcessMessageThread; } set { MPManager.stopProcessMessageThread = value; } } /// <summary> /// The used MPClient of this instance. /// </summary> public MPClient MPClient { get { return mpClient; } private set { mpClient = value; } } /// <summary> /// The used MPServer of this instance. /// </summary> public MPServer MPServer { get { return mpServer; } private set { mpServer = value; } } /// <summary> /// Indicates if the MPServer object is null or not. /// </summary> public bool IsMPServerInitialized { get { return (MPServer != null) ? true : false; } } /// <summary> /// Indicates if the MPClient object is null or not. /// </summary> public bool IsMPClientInitialized { get { return (MPClient != null) ? true : false; } } /// <summary> /// Indicates the current multiplayer role of the user. /// </summary> public MPRoleType MPRole { get { return mpRole; } private set { if (value == MPRoleType.None) { mpRole = MPRoleType.None; } else if (value == MPRoleType.Resetting) { // Use MPRoleType.Resetting or the provided methods to reset the instances. if (mpRole == MPRoleType.Server) { ServerStop(); ServerUninitialize(); } else if (mpRole == MPRoleType.Client) { ClientDisconnect(); ClientUninitialize(); } // MPRole should be set to None in the xUninitialize() methods. // And if not: if (mpRole != MPRoleType.None) mpRole = MPRoleType.None; } else if (value == MPRoleType.Server) { if (mpRole == MPRoleType.Client) { ClientDisconnect(); ClientUninitialize(); } Log.Message("MPRole Property: mpRole >" + mpRole + "< and setting value >" + value + "<"); mpRole = value; } else if (value == MPRoleType.Client) { if (mpRole == MPRoleType.Server) { ServerStop(); ServerUninitialize(); } Log.Message("MPRole Property: mpRole >" + mpRole + "< and setting value >" + value + "<"); mpRole = value; } } } //Singleton public static MPManager Instance { get { return instance ?? (instance = new MPManager()); } } //Constructor private MPManager() { Log.Warning("MPManager was just initialized."); } //Methods /// <summary> /// Resets the MPManager instance. /// </summary> public void Reset() { Log.Message("Resetting MPManager instance."); Log.Message("Resetting MPClient"); ClientUninitialize(); Log.Message("Resetting MPServer"); ServerUninitialize(); instance = new MPManager(); SetMPRole(MPRoleType.None); Log.Message("MPManager instance resetted."); } /// <summary> /// Sets the current MPRole. /// </summary> /// <param name="newMPRoleType">New MPRoleType for MPRole.</param> public void SetMPRole(MPRoleType newMPRoleType) { MPRole = newMPRoleType; } //SERVER// #region netServer stuff /// <summary> /// Initializes the MPServer if it is not already initialized and the MPClient is not initialized. /// </summary> public void ServerInitialize() { if (IsMPClientInitialized) { Log.Warning("Cannot initialize server. Client is already initialized."); return; } if (IsMPServerInitialized) { Log.Warning("Server is already initialized."); return; } Log.Message("Initialize server."); MPServer = new MPServer(StopProcessMessageThread); MPServer.serverLeavingProcessingMessageThread += MPServer_serverLeavingProcessingMessageThreadEvent; MPServer.unhandledMessageReceived += MPServer_unhandledMessageReceivedEvent; MPServer.clientConnected += MPServer_clientConnectedEvent; MPServer.clientDisconnected += MPServer_clientDisconnectedEvent; MPServer.allClientsDisconected += MPServer_allClientsDissconectedEvent; MPServer.clientConnectionRequestApproved += MPServer_clientConnectionRequestApprovedEvent; MPServer.clientConnectionRequestDenied += MPServer_clientConnectionRequestDeniedEvent; SetMPRole(MPRoleType.Server); Log.Message("Server initialized."); } /// <summary> /// Uninitializes the MPServer. Sets it to null. /// </summary> public void ServerUninitialize() { if (!IsMPServerInitialized) { Log.Warning("Server is not initialized. Cannot uninitialize."); return; } Log.Message("Uninitialize server."); ServerStop(); MPServer = null; SetMPRole(MPRoleType.None); Log.Message("Server uninitialized."); } /// <summary> /// Create a new instance of MPServer. /// </summary> public void ServerReset() { if (IsMPClientInitialized) { Log.Warning("Server cannot reset. The client is initialized."); return; } if (!IsMPServerInitialized) { Log.Warning("MPServer is not initialized. There is nothing to reset."); return; } Log.Message("Resetting server."); ServerStop(); ServerInitialize(); Log.Message("Server resetted. New instance created."); } /// <summary> /// Starts the netServer. /// </summary> public void ServerStart() { if (IsMPClientInitialized) { Log.Warning("Cannot start the server. Client is initialized."); return; } if (!IsMPServerInitialized) { Log.Warning("Cannot start the server. The server is not initialized."); return; } Log.Message("Starting server."); MPServer.StartServer(); SetMPRole(MPRoleType.Server); Log.Message("Server started."); } /// <summary> /// Starts the netServer. /// </summary> /// <param name="port">The port to listen on.</param> /// <param name="password">The password of the netServer.</param> /// <param name="maximumPlayerAmount">Maximum amount of players.</param> public void ServerStart(int port, string password, int maximumPlayerAmount) { if (IsMPClientInitialized) { Log.Warning("Cannot start the server. Client is initialized."); return; } if (!IsMPServerInitialized) { Log.Warning("Cannot start the server. The server is not initialized."); return; } Log.Message("Starting server."); MPServer.StartServer(port, password, maximumPlayerAmount); Log.Message("Server started."); } /// <summary> /// Stops the netServer. /// </summary> public void ServerStop() { if (IsMPClientInitialized) { Log.Warning("Cannot stop the server. Client is initilalized"); return; } if (!IsMPServerInitialized) { Log.Warning("Cannot stop the server. Server is not initialized."); return; } Log.Message("Stopping server."); MPServer.Stop(); Log.Message("Server stopped."); } // Server Events #region Server Events /// <summary> /// Fired when the ProcessMessage thread of the MPSever is left. /// </summary> /// <param name="sender">MPServer instance.</param> /// <param name="e"></param> void MPServer_serverLeavingProcessingMessageThreadEvent(object sender, EventArgs e) { Log.Message("Left Server message processing thread!"); IsProcessMessageThreadRunning = false; ServerUninitialize(); } /// <summary> /// Fires when a unhandled message arrives. /// </summary> /// <param name="sender">MPServer object.</param> /// <param name="e">Information about the unhandled object.</param> void MPServer_unhandledMessageReceivedEvent(object sender, ReceivedUnhandledMessageEventArgs e) { Log.Warning(String.Format("Server: Unhandled MessageType/SubType: {0}/{1} ", e.Message.MessageType, e.Type)); } /// <summary> /// Fires when a new client connected. /// </summary> /// <param name="sender">Information about the sender object, the MPServer.</param> /// <param name="e">Information about the received message.</param> void MPServer_clientConnectedEvent(object sender, ReceivedMessageEventArgs e) { Log.Message("Client connected. Client IP: " + e.Message.SenderEndPoint); Log.Error("ConnectionsCount new connected:::" + MPServer.ConnectionsCount.ToString()); } /// <summary> /// Fires when a client disconnected. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void MPServer_clientDisconnectedEvent(object sender, ReceivedMessageEventArgs e) { Log.Message("Client disconnected. Client IP: " + e.Message.SenderEndPoint); Log.Error("ConnectionsCount new disconnect:::" + MPServer.ConnectionsCount.ToString()); } /// <summary> /// Fires when all clients disconnected from the server. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void MPServer_allClientsDissconectedEvent(object sender, EventArgs e) { MPGlobalValues.IsConfigurationFinished = false; } /// <summary> /// Fires when a connection request of a client has been accepted. /// </summary> /// <param name="sender">Sender object, MPServer.</param> /// <param name="e">Containing information about the connection request.</param> void MPServer_clientConnectionRequestApprovedEvent(object sender, ConnectionRequestEventArgs e) { Log.Message(String.Format("New client connected. IP:{0} Username:{1}", e.Message.SenderEndPoint, e.Username)); } /// <summary> /// Fires when a conenction request of a client has been denied because of various reasons. /// </summary> /// <param name="sender">Sender object, MPServer.</param> /// <param name="e">Containing information about the connection request.</param> void MPServer_clientConnectionRequestDeniedEvent(object sender, ConnectionRequestEventArgs e) { Log.Warning(String.Format("Client connection request denied. IP:{0} Username:{1} Password:{2} Note:{3}", e.Message.SenderEndPoint, e.Username, e.Password, e.Note)); } #endregion #endregion //CLIENT// #region netClient stuff /// <summary> /// Initilializes the Client if it is not already initialized and the MPServer is not initialized. /// </summary> public void ClientInitialize() { if (IsMPServerInitialized) { Log.Warning("Cannot initialize the client. Server is initilalized"); return; } if (IsMPClientInitialized) { Log.Warning("Client is already initialized."); } Log.Message("Initializing client."); MPClient = new MPClient(StopProcessMessageThread); MPClient.clientLeavingProcessMessageThread += MPClient_clientLeavingProcessMessageThread; MPClient.clientConnected += MPClient_clientConnectedEvent; MPClient.clientDisconnected += MPClient_clientDisconnectedEvent; mpClient.receivedUnhandledMessage += mpClient_receivedUnhandledMessage; SetMPRole(MPRoleType.Client); Log.Message("Client initialized."); } /// <summary> /// Uninitializes the MPClient. Sets it to null. /// </summary> public void ClientUninitialize() { if (!IsMPClientInitialized) { Log.Warning("There is nothing to uninitialize."); return; } Log.Message("Uninitialize client."); ClientDisconnect(); MPClient = null; SetMPRole(MPRoleType.None); Log.Message("Client uninitialized."); } /// <summary> /// Creates a new instance of MPClient. /// </summary> public void ClientReset() { if (IsMPServerInitialized) { Log.Warning("Could not reset the client. Server is initialized."); return; } if (!IsMPClientInitialized) { Log.Warning("Client is not initialized. There is nothing to reset."); return; } Log.Message("Resetting client"); ClientDisconnect(); ClientInitialize(); Log.Message("Client resetted."); } /// <summary> /// Connect to localhost on port 4230 with no password (""). /// </summary> public void ClientConnect() { if (IsMPServerInitialized) { Log.Warning("Cannot connect client to server. Server is initialized."); return; } if (!IsMPClientInitialized) { Log.Warning("Cannot connect client to server. CLient is not initialized."); } Log.Message("Connecting client."); MPClient.ConnectToServer(); Log.Message("Client connected."); } /// <summary> /// Connects to a remote netServer. /// </summary> /// <param name="ip">The IP address of the netServer.</param> /// <param name="port">The port of the netServer.</param> /// <param name="password">The netServer password.</param> public void ClientConnect(string ip, int port, string password) { if (IsMPServerInitialized) { Log.Warning("Cannot connect client to server. Server is initialized."); return; } if (!IsMPClientInitialized) { Log.Warning("Cannot connect client to server. CLient is not initialized."); } Log.Message("Connecting client."); MPClient.ConnectToServer(ip, port, password); Log.Message("Client connected."); } /// <summary> /// Disconnects from the netServer. /// </summary> public void ClientDisconnect() { if (IsMPServerInitialized) { Log.Warning("Could not disconnect from server. Server is initialized."); return; } if (!IsMPClientInitialized) { Log.Warning("Could not disconnect from the server. Client is not initialized."); return; } Log.Message("Disconnecting from server."); MPClient.DisconnectFromServer(); Log.Message("Disconnected from server."); } // Client Events #region Client Events /// <summary> /// Fires when the process message thread is about to leave. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void MPClient_clientLeavingProcessMessageThread(object sender, EventArgs e) { Log.Message("Left Client message processing thread!"); IsProcessMessageThreadRunning = false; ClientUninitialize(); } /// <summary> /// Fires when the client connected. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void MPClient_clientConnectedEvent(object sender, ReceivedMessageEventArgs e) { Log.Message("You connected. Client IP: " + e.Message.SenderEndPoint); } /// <summary> /// Fires when the client disconnected from the server. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void MPClient_clientDisconnectedEvent(object sender, ReceivedMessageEventArgs e) { Log.Message("You disconnected. Client IP: " + e.Message.SenderEndPoint); } /// <summary> /// Fires when the client received an unhandled message. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void mpClient_receivedUnhandledMessage(object sender, ReceivedUnhandledMessageEventArgs e) { Log.Warning(String.Format("Client: Unhandled MessageType/SubType: {0}/{1} ", e.Message.MessageType, e.Type)); } #endregion #endregion } }
36.246429
176
0.53823
[ "MIT" ]
DaniGTA/Gurkenplayer
Gurkenplayer/MPManager.cs
20,300
C#
using System; using System.Collections.Generic; using System.Text; using Mediachase.Ibn.Core.Business; using Mediachase.Ibn.Data; using Mediachase.IBN.Database; using Mediachase.Ibn.Data.Sql; using Mediachase.IBN.Business; namespace Mediachase.Ibn.Business.Messages { /// <summary> /// Represents ibn client message delivery provider. /// </summary> public class IbnClientMessageDeliveryProvider: MessageDeliveryProvider { #region Const #endregion #region Fields #endregion #region .Ctor /// <summary> /// Initializes a new instance of the <see cref="IbnClientMessageDeliveryProvider"/> class. /// </summary> public IbnClientMessageDeliveryProvider() { } #endregion #region Properties #endregion #region Methods /// <summary> /// Invokes this instance. /// </summary> public override void Invoke() { // Remove Expired RemoveExpiredMessages(); //int maxDeliveryAttempts = 100; // TODO: Read From Config EntityObject[] elements = BusinessManager.List(OutgoingMessageQueueEntity.ClassName, OutgoingMessageUtil.CreateIbnClientMessageDeliveryProviderFilters(), new SortingElement[] { SortingElement.Ascending(OutgoingMessageQueueEntity.FieldCreated) }); foreach (OutgoingMessageQueueEntity element in elements) { try { // Load Ibn Message IbnClientMessageEntity message = (IbnClientMessageEntity)BusinessManager.Load(IbnClientMessageEntity.ClassName, element.IbnClientMessageId.Value); // Send int toOriginalId = DBUser.GetOriginalId(message.ToId); int fromOriginalId = DBUser.GetOriginalId(message.FromId); IMHelper.SendMessage(toOriginalId, fromOriginalId, message.HtmlBody); element.Error = string.Empty; element.DeliveryAttempts++; element.IsDelivered = true; } catch (Exception ex) { element.Error = ex.Message; element.DeliveryAttempts++; // TODO: Save Complete Error Stack || Complete Delivery Log } BusinessManager.Update(element); } // } private void RemoveExpiredMessages() { int expiration = PortalConfig.MdsDeleteOlderMoreThan; if (expiration > 0) { SqlScript sqlScript = new SqlScript(); sqlScript.AppendLine("DELETE FROM [dbo].[cls_IbnClientMessage] WHERE Created < @ExpirationDate"); sqlScript.AddParameter("@ExpirationDate", DateTime.UtcNow.AddMinutes(-expiration)); sqlScript.Execute(); } } #endregion } }
23.873786
151
0.718585
[ "MIT" ]
InstantBusinessNetwork/IBN
Source/Server/Business/Messages/IbnClientMessageDeliveryProvider.cs
2,459
C#
#if !NO_RUNTIME using System; namespace ProtoBuf.Serializers { sealed class UriDecorator : ProtoDecoratorBase { public override bool RequiresOldValue { get { return false; } } public override bool ReturnsValue { get { return true; } } public override Type ExpectedType { get { return typeof(Uri); } } public UriDecorator(IProtoSerializer tail) : base(tail) { } public override void Write(object value, ProtoWriter dest) { Tail.Write(((Uri)value).AbsoluteUri, dest); } public override object Read(object value, ProtoReader source) { Helpers.DebugAssert(value == null); // not expecting incoming string s = (string)Tail.Read(null, source); return s.Length == 0 ? null : new Uri(s); } #if FEAT_COMPILER protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) { ctx.LoadValue(valueFrom); ctx.LoadValue(typeof(Uri).GetProperty("AbsoluteUri")); Tail.EmitWrite(ctx, null); } protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) { Tail.EmitRead(ctx, valueFrom); ctx.CopyValue(); Compiler.CodeLabel @nonEmpty = ctx.DefineLabel(), @end = ctx.DefineLabel(); ctx.LoadValue(typeof(string).GetProperty("Length")); ctx.BranchIfTrue(@nonEmpty, true); ctx.DiscardValue(); ctx.LoadNullRef(); ctx.Branch(@end, true); ctx.MarkLabel(@nonEmpty); ctx.EmitCtor(typeof(Uri), typeof(string)); ctx.MarkLabel(@end); } #endif } } #endif
34.372549
97
0.598403
[ "Apache-2.0" ]
Jessecar96/protobuf-net
protobuf-net/Serializers/UriDecorator.cs
1,755
C#
/* | ``\":. . .:"/`` | BAYKUS Reputation Reporter \\";;;\"~^~"/;;;"// | O( (O)\\|//(O) )O | OOo~~_)\|/(_~~oOO | doO/~/~).Y.(~\~\OOb | dob"_._~ ~_._'d0b | Emre Ekinci | yunusemrem@windowslive.com | | TODO: > API keyleri ve validasyınu düzenle, Hash Checkerdaki gibi > rapor dosyasını plain table 3 yap > sonucu blissadmin kutucuğuna bas ( https://stackoverflow.com/questions/4015324/how-to-make-http-post-web-request FLURRRR ) > projeyi linuxta çalıştır > amblemi düzenle > logger fonksiyonu ekle, herşey loglansın > OOP desing yap > Apı keyleri txt den al > APİ ler ayrı classlar olmalı error handle etmek zor, tempRow.add getCountry,getAsns metotlarından sonra doldurulmalı */ using System; using System.IO; using System.Net; using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Http; using System.Json; using System.Threading.Tasks; using System.Threading; using System.Drawing; using Console = Colorful.Console; using System.Security; using Baykus.Properties; namespace Baykus { public class MainClass { static public string userName; static WebProxy myProxySetting = null; //here our API key-value pairs, there is at least 3 key for each API will be set in Helpers.cs file static public List<ApiKey> ibmApiKeys; static public List<ApiKey> ntApiKeys; static public List<ApiKey> mtApiKeys; static public List<Result> results = new List<Result>(); // rows that will be written on a excel file static public List<List<string>> printers = new List<List<string>>(); // print out to user what happening static public Config speconfig; // ========================================== MAIN FUNC =============================================== // static void Main(string[] args) { var largestW = Console.LargestWindowWidth / 2; string banner = " ".PadRight(largestW) + String.Concat(Resources.owlBanner.Split('\n').Select(ss => ss = ss + " ".PadRight(largestW - ss.Length) + '\n')).Replace("\r", "") + " ".PadRight(largestW) + '\n'; Console.Title = "BAYKUS"; Console.OutputEncoding = Encoding.UTF8; Console.ForegroundColor = Color.LightGray; Console.SetWindowSize(largestW, Console.LargestWindowHeight -1); Console.WriteFormatted(banner, Color.WhiteSmoke); try { speconfig = JsonConvert.DeserializeObject<Config>(Resources.speconfig); } catch (System.Exception ee) { Console.WriteFormatted("\n Config file problem:\n\t" + ee.Message, Color.Red); Console.ReadLine(); return; } Helpers.SetApiKeys(); List<string> IPs = Helpers.getReportedIPs();// read reported IPs from csv myProxySetting = initializeProxyConfigs(); AsyncRequests(IPs); // this will make all needed requests from all APIs asynchronously results = results.OrderBy(ss => ss.ip_apiResult.country).ToList(); Helpers.writeRowsToExcel(results); // responses wrote to the rows List variable, write them to report excel Helpers.WriteSomeMail(results); Helpers.WriteAtarMail(results); Console.ReadLine(); } // ======================================== Network Configs =========================================== // private static WebProxy initializeProxyConfigs() { Console.Write("\n\n │ Initializing proxy configs..."); // setting PROXY config and Network CREDENTIALS // this is standing here (not in its own function) to get proxy settings HttpWebRequest tempReq = (HttpWebRequest)WebRequest.Create("http://google.com"); WebProxy myProxySetting = new WebProxy(); if (tempReq.Proxy != null) { // set grabbed proxy settings to myproxy Console.Write("\n │\t├─ Proxy : {0}", tempReq.Proxy.GetProxy(tempReq.RequestUri)); myProxySetting.Address = tempReq.Proxy.GetProxy(tempReq.RequestUri); } else { Console.Write("\n │\t├─ !No proxy detected.\n\t"); Console.Write("Setting proxy to \"" + speconfig.proxyAdress + "\""); //System.Environment.Exit(1); myProxySetting.Address = new Uri(speconfig.proxyAdress); } // Setting User Creds to pass proxy userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\')[1]; userName = ( userName.Length < 3 || userName.Length > 10 ) == true ? "unknown" : userName; Console.Write("\n │\t├─ Username: {0}", userName); SecureString securePwd = new SecureString(); while (true) { Console.Write("\n │\t├─ Password: "); securePwd = Helpers.darker(); // ask and save user password on the quiet myProxySetting.Credentials = new NetworkCredential(userName, securePwd); var tempResult = Helpers.ExecuteWithTimeLimit(TimeSpan.FromMilliseconds(2000), myProxySetting, "1.1.1.1", makeRequestIp_api); if (tempResult[0] == "FailProxyPass") Console.WriteFormatted("\n │\t\t\tProbably wrong password..", Color.Red); else { Console.WriteFormatted(" >> Passing proxy is OK", Color.Green); break; } } securePwd.Dispose(); return myProxySetting; } // ======================================== Make the Requests ========================================= // static void AsyncRequests(List<string> IPs) { for (int i = 0; i < IPs.Count; i++) { printers.Add(new List<string>() {IPs[i]});} int counter = 0; List<Task> allReq = new List<Task>(); foreach (string IP in IPs) { int[] ipParts = IP.Split(new String[] { "." }, StringSplitOptions.RemoveEmptyEntries).Select(s => int.Parse(s)).ToArray(); // in private ip range if ( ipParts[0] == 10 || (ipParts[0] == 192 && ipParts[1] == 168) || (ipParts[0] == 172 && (ipParts[1] >= 16 && ipParts[1] <= 31))) { results.Add(new Result(counter+1,IP, " ", "PRIVATE IP RANGE", " ", " ")); continue; } int myC = counter; //ASYNC = oneIpRequest(IP, myC); var eachTask = Task.Factory.StartNew(() => OneIpRequests(IP, myC)); allReq.Add(eachTask); counter++; Thread.Sleep(500); } Task.WaitAll(allReq.ToArray()); Console.Write("\n │\n │ DONE _____________________________________________"); return; } /// <summary> /// /// </summary> /// <param name="IPs"></param> /// <returns></returns> static Result OneIpRequests(string ip,int counter) { Result tResult = new Result(counter, ip); string rawIbm = "!NA!"; string rawIpapi = "!NA!"; string rawIp_api = "!NA!"; string rawMd = "!NA!"; string rawNt = "!NA!"; //get api RESPONSES from requests asynchronous, choose whatever //var taskIPAPI = Task.Run(() => rawIpapi = makeRequestIpapi(IP,counter)); var taskIP_API = Task.Run(() => rawIp_api = makeRequestIp_api(ip, counter)); var taskIBM = Task.Run(() => rawIbm = makeRequestIBM(ip, counter)); var taskMD = Task.Run(() => rawMd = makeRequestMDef(ip, counter)); var taskNTRNO = Task.Run(() => rawNt = makeRequestNtrno(ip, counter)); // await makes execution block for further lines Task.WaitAll(taskIBM, taskNTRNO, taskMD, taskIP_API); tResult = new Result(counter, ip, rawIbm, rawIpapi, rawMd, rawNt); lock (results) { // add data to the list of rows that will be written to the output CSV results.Add(tResult); //rows.Last().AddRange(responseIPAPI); //select one of the other IP location API, if the one fails go for the other. Helpers.printStat(printers[counter], counter); } return tResult; } /// <summary> /// see\Resources\resultIp_api.json /// </summary> /// <param name="IP"></param> /// <param name="counter"></param> /// <returns></returns> static string makeRequestIp_api(string IP, int counter) { string apiName = "ip-api"; List<string> tempRow = new List<string>(); string responseIP_API = "!NA!"; try { // create request , read response HttpWebRequest requestIP_API = (HttpWebRequest)WebRequest.Create("http://ip-api.com/json/" + IP); requestIP_API.Proxy = myProxySetting; using (HttpWebResponse response = (HttpWebResponse)requestIP_API.GetResponse()) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { responseIP_API = reader.ReadToEnd(); } } catch (Exception e) { if (e.Message.Contains("Proxy Authentication Required")) return responseIP_API; // with this return value checked, blocks this app to continue else { printers[counter].Add(Helpers.printBad(apiName, "exception", e.Message)); if (e.Message.Contains("Forbidden")) { DUZENLEEEEEEEEEE return responseIP_API; } } } return responseIP_API; } /// <summary> /// see\Resources\resultIpapi.json /// </summary> /// <param name="IP"></param> /// <param name="counter"></param> /// <returns></returns> static List<string> makeRequestIpapi(string IP, int counter) { string apiName = "ipapi"; List<string> tempRow = new List<string>(); string responseIPAPI = ""; try { // create request , read response HttpWebRequest requestIPAPI = (HttpWebRequest)WebRequest.Create("https://ipapi.co/" + IP + "/json/"); requestIPAPI.Proxy = myProxySetting; using (HttpWebResponse response = (HttpWebResponse)requestIPAPI.GetResponse()) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { responseIPAPI = reader.ReadToEnd(); } } catch (Exception e) { printers[counter].Add(Helpers.printBad(apiName, "exception", e.Message)); return new List<string>() { "?", "?" }; } if (responseIPAPI.Contains("error")) printers[counter].Add(Helpers.printBad(apiName, "error", responseIPAPI.ToString())); else if (responseIPAPI == null) printers[counter].Add(Helpers.printBad(apiName, "null returned", responseIPAPI.ToString())); else { try { // process the response if no failure exists dynamic retIPAPIjson = JsonConvert.DeserializeObject(responseIPAPI); // add values to row > country+region,organization tempRow.Add(retIPAPIjson.org.ToString()); tempRow.Add(retIPAPIjson.country_name.ToString() + ", " + retIPAPIjson.region.ToString()); printers[counter].Add(Helpers.printOk(apiName)); return tempRow; } catch (Exception e) { printers[counter].Add(Helpers.printBad(apiName, "exception when parsing", e.Message)); } } return new List<string>() { "?", "?" }; // if any failure occurs, instruction comes to here to return properly } /// <summary> /// see\Resources\resultIBM.json /// </summary> /// <param name="IP"></param> /// <param name="counter"></param> /// <returns></returns> static string makeRequestIBM(string IP, int counter) { int currKeyCounter = 0; string responseIBM = ""; List<string> tempRow = new List<string>(); while (currKeyCounter < ibmApiKeys.Count) { if (ibmApiKeys[currKeyCounter].state == "KeyLimit") { currKeyCounter++; continue; } try { // create request , read response HttpWebRequest requestIBM = (HttpWebRequest)WebRequest.Create("https://api.xforce.ibmcloud.com/ipr/" + IP); requestIBM.Proxy = myProxySetting; string apicreds = ibmApiKeys[currKeyCounter].id + ":" + ibmApiKeys[currKeyCounter].pass; requestIBM.Headers.Add("Authorization", "Basic " + System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(apicreds))); using (HttpWebResponse response = (HttpWebResponse)requestIBM.GetResponse()) { using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) responseIBM = reader.ReadToEnd(); } if(responseIBM.Contains("402") && responseIBM.Contains("error")) { ibmApiKeys[currKeyCounter].state = "KeyLimit"; continue; } } catch (Exception e) { printers[counter].Add(Helpers.printBad("ibm-xforce", "exception", e.Message)); } break; } return responseIBM; } /// <summary> /// see\Resources\resultMD.json /// </summary> /// <param name="IP"></param> /// <param name="counter"></param> /// <returns></returns> static string makeRequestMDef(string IP, int counter) { int currKeyCounter = 0; string apiName = "metadefender"; string responseMDef = ""; while (currKeyCounter < mtApiKeys.Count) { if (mtApiKeys[currKeyCounter].state == "KeyLimit") { currKeyCounter++; continue; } List<string> tempRow = new List<string>(); try {// create request , read response HttpWebRequest requestMETADEF = (HttpWebRequest)WebRequest.Create("http://api.metadefender.com/v1/scan/" + IP); requestMETADEF.Proxy = myProxySetting; requestMETADEF.Headers.Add("apikey: " + mtApiKeys[currKeyCounter].pass); using (HttpWebResponse response = (HttpWebResponse)requestMETADEF.GetResponse()) { using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream)) { responseMDef = reader.ReadToEnd(); } } } } catch (Exception e) { printers[counter].Add(Helpers.printBad(apiName, "exception", e.Message)); if (e.Message.Contains("Forbidden")) { mtApiKeys[currKeyCounter].state = "KeyLimit"; continue; } } break; } return responseMDef; } /// <summary> /// see\Resources\resultNtrno.json /// </summary> /// <param name="IP"></param> /// <param name="counter"></param> /// <returns></returns> static string makeRequestNtrno(string IP, int counter) { int currKeyCounter = 0; string apiName = "neutrino"; string responseNtrno = ""; //becuse of that i cannot figure out how to send API creds as previous patterns, name of this function decleared like this List<string> tempRow = new List<string>(); //now create a client handler which uses that proxy while (currKeyCounter < ntApiKeys.Count) { if (ntApiKeys[currKeyCounter].state == "KeyLimit") { currKeyCounter++; continue; } var httpClientHandler = new HttpClientHandler() { Proxy = myProxySetting, }; try { using (var client = new HttpClient(handler: httpClientHandler, disposeHandler: true)) { var req = new List<KeyValuePair<string, string>>(); req.Add(new KeyValuePair<string, string>("user-id", ntApiKeys[currKeyCounter].id)); req.Add(new KeyValuePair<string, string>("api-key", ntApiKeys[currKeyCounter].pass)); req.Add(new KeyValuePair<string, string>("ip", IP)); var content = new FormUrlEncodedContent(req); var response = client.PostAsync("https://neutrinoapi.com/ip-blocklist", content).Result; responseNtrno = response.Content.ReadAsStringAsync().Result; } } catch (Exception e) { if (e.Message.Contains("The given key was not present in the dictionary") == true) { ntApiKeys[currKeyCounter].state = "KeyLimit"; continue; } } break; } return responseNtrno; } } }
51.495957
150
0.511803
[ "Unlicense" ]
Yuuyake/Baykus
Baykus.cs
19,157
C#
// Display a splash window immediately to improve app responsiveness before // engine is initialized and main window created (only windows) displaySplashWindow("splash.png"); //closeSplashWindow(); //1=keep log file open while writing. 1= save on each log setLogMode(2); // will trace and log to console the invocation and returns of script functions. trace(true); //----------------------------------------------------------------------------- // Load up scripts to initialise subsystems. exec("sys/main.cs"); // The canvas needs to be initialized before any gui scripts are run since // some of the controls assume that the canvas exists at load time. createCanvas("T3Dbones"); // Start rendering and stuff. initRenderManager(); initLightingSystems("Basic Lighting"); // Start PostFX. If you use "Advanced Lighting" above, uncomment this. //initPostEffects(); // Start audio. sfxStartup(); // Provide stubs so we don't get console errors. If you actually want to use // any of these functions, be sure to remove the empty definition here. function onDatablockObjectReceived() {} function onGhostAlwaysObjectReceived() {} function onGhostAlwaysStarted() {} function updateTSShapeLoadProgress() {} //----------------------------------------------------------------------------- // Load console. exec("console/main.cs"); // Load up game code. exec("scripts/main.cs"); // Called when we connect to the local game. function GameConnection::onConnect(%client) { %client.transmitDataBlocks(0); } // Called when all datablocks from above have been transmitted. function GameConnection::onDataBlocksDone(%client) { // Start sending ghosts to the client. %client.activateGhosting(); %client.onEnterGame(); } function quitMe(%make) { quit(); } // Create a local game server and connect to it. new SimGroup(ServerGroup); new GameConnection(ServerConnection); // This calls GameConnection::onConnect. ServerConnection.connectLocal(); onStart(); //----------------------------------------------------------------------------- // Called when the engine is shutting down. function onExit() { // Clean up game objects and so on. onEnd(); // Delete server-side objects and datablocks. ServerGroup.delete(); deleteDataBlocks(); }
30.38961
82
0.644017
[ "MIT" ]
kiyoMatsui/Torque3D
Templates/kiyoBones/game/main.cs
2,264
C#
using System.Collections.Generic; using Essensoft.AspNetCore.Payment.Alipay.Response; namespace Essensoft.AspNetCore.Payment.Alipay.Request { /// <summary> /// alipay.user.account.get /// </summary> public class AlipayUserAccountGetRequest : IAlipayRequest<AlipayUserAccountGetResponse> { #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "alipay.user.account.get"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary(); return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
22.362069
91
0.554356
[ "MIT" ]
Msy1989/payment
src/Essensoft.AspNetCore.Payment.Alipay/Request/AlipayUserAccountGetRequest.cs
2,596
C#
using UnityEngine; using System.Collections; public class CoreyRepopulateScript : MonoBehaviour { protected CoreyGameManagerScript gameManager; //reference to game manager public virtual void Start () { gameManager = GetComponent<CoreyGameManagerScript>(); //getting a refernece to GM component } //Repopulate grid at the top public virtual void AddNewTokensToRepopulateGrid(){ for(int x = 0; x < gameManager.gridWidth; x++){ //looping through the grid GameObject token = gameManager.gridArray[x, gameManager.gridHeight-1]; //find token in position if(token == null){ //if there's no token there, add a token gameManager.AddTokenToPosInGrid(x, gameManager.gridHeight - 1, gameManager.grid); } } } }
33.181818
98
0.749315
[ "Unlicense" ]
madparker/CodeLab2-2017-Match3Repo1
Match3/Assets/Students/cb3628/Scripts/CoreyRepopulateScript.cs
732
C#
namespace minecraft.Application.Bindables; public class BindableLong : BindableNumber<long> { public BindableLong(long defaultValue = default) : base(defaultValue) { } protected override Bindable<long> CreateInstance() => new BindableLong(); }
22.583333
77
0.715867
[ "MIT" ]
devclyde/minecraft-net
application/Bindables/BindableLong.cs
273
C#