content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using Naruto.MongoDB.Object; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Naruto.MongoDB.Interface { /// <summary> /// 张海波 /// 2019-12-1 /// mongo的连接实例工厂获取 /// </summary> public interface IMongoClientFactory : IDisposable { /// <summary> /// 获取mongo 客户端 /// </summary> /// <returns></returns> Task<Tuple<IMongoClient, MongoContext>> GetMongoClientAsync<TMongoContext>() where TMongoContext : MongoContext; /// <summary> /// /// </summary> /// <returns></returns> Tuple<IMongoClient, MongoContext> GetMongoClient<TMongoContext>() where TMongoContext : MongoContext; } }
26.482759
120
0.628906
[ "MIT" ]
zhanghaiboshiwo/Naruto.Data
src/Naruto.MongoDB/Interface/IMongoClientFactory.cs
804
C#
namespace Spectre.Console; /// <summary> /// Represents console capabilities. /// </summary> public sealed class Capabilities : IReadOnlyCapabilities { private readonly IAnsiConsoleOutput _out; /// <summary> /// Gets or sets the color system. /// </summary> public ColorSystem ColorSystem { get; set; } /// <summary> /// Gets or sets a value indicating whether or not /// the console supports VT/ANSI control codes. /// </summary> public bool Ansi { get; set; } /// <summary> /// Gets or sets a value indicating whether or not /// the console support links. /// </summary> public bool Links { get; set; } /// <summary> /// Gets or sets a value indicating whether or not /// this is a legacy console (cmd.exe) on an OS /// prior to Windows 10. /// </summary> /// <remarks> /// Only relevant when running on Microsoft Windows. /// </remarks> public bool Legacy { get; set; } /// <summary> /// Gets a value indicating whether or not /// the output is a terminal. /// </summary> [Obsolete("Use Profile.Out.IsTerminal instead")] public bool IsTerminal => _out.IsTerminal; /// <summary> /// Gets or sets a value indicating whether /// or not the console supports interaction. /// </summary> public bool Interactive { get; set; } /// <summary> /// Gets or sets a value indicating whether /// or not the console supports Unicode. /// </summary> public bool Unicode { get; set; } /// <summary> /// Gets or sets a value indicating whether /// or not the console supports alternate buffers. /// </summary> public bool AlternateBuffer { get; set; } /// <summary> /// Initializes a new instance of the /// <see cref="Capabilities"/> class. /// </summary> internal Capabilities(IAnsiConsoleOutput @out) { _out = @out ?? throw new ArgumentNullException(nameof(@out)); } }
28.314286
69
0.61554
[ "MIT" ]
BlackOfWorld/spectre.console
src/Spectre.Console/Capabilities.cs
1,982
C#
using Microsoft.Extensions.DependencyModel; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace Rabbit.Extensions.Boot { public class RabbitBoot { public static async Task<IHostBuilder> BuildHostBuilderAsync(Action<IHostBuilder> configure = null, Func<AssemblyName, bool> assemblyPredicate = null, Func<TypeInfo, bool> typePredicate = null) { if (typePredicate == null) typePredicate = t => t.Name.EndsWith("Bootstrap"); var types = GetAssemblies(assemblyPredicate).SelectMany(i => i.ExportedTypes.Select(z => z.GetTypeInfo())).Where(typePredicate); IHostBuilder hostBuilder = new HostBuilder(); configure?.Invoke(hostBuilder); return await BuildHostBuilderAsync(hostBuilder, types); } public static async Task<IHostBuilder> BuildHostBuilderAsync(IHostBuilder hostBuilder, IEnumerable<TypeInfo> starterTypes) { if (hostBuilder == null) throw new ArgumentNullException(nameof(hostBuilder)); if (starterTypes == null) throw new ArgumentNullException(nameof(starterTypes)); foreach (var startMethod in starterTypes.OrderByDescending(i => { var priorityProperty = i.GetProperty("Priority"); if (priorityProperty == null) return 20; return (int)priorityProperty.GetValue(null); }).SelectMany(GetStartMethods)) { var parameters = startMethod.GetParameters().Any() ? new object[] { hostBuilder } : null; var result = startMethod.Invoke(null, parameters); if (result is Task task) await task; } return hostBuilder; } private static IEnumerable<Assembly> GetAssemblies(Func<AssemblyName, bool> predicate = null) { var assemblyNames = DependencyContext.Default.RuntimeLibraries.SelectMany(i => i.GetDefaultAssemblyNames(DependencyContext.Default)); if (predicate != null) assemblyNames = assemblyNames.Where(predicate).ToArray(); var assemblies = assemblyNames.Select(i => Assembly.Load(new AssemblyName(i.Name))).ToArray(); return assemblies; } private static IEnumerable<MethodInfo> GetStartMethods(TypeInfo starterType) { bool CheckParameters(MethodBase methodInfo) { var parameters = methodInfo.GetParameters(); switch (parameters.Length) { case 0: return true; case 1 when typeof(IHostBuilder).IsAssignableFrom(parameters[0].ParameterType): return true; default: return false; } } MethodInfo GetStartMethod(string name) { var methodInfo = starterType.GetMethod(name, BindingFlags.Static | BindingFlags.Public); if (methodInfo != null && CheckParameters(methodInfo)) return methodInfo; return null; } foreach (var methodInfo in new[] { "StartAsync", "Start" }.Select(GetStartMethod)) { if (methodInfo != null) yield return methodInfo; } } } }
39.395604
201
0.586611
[ "Apache-2.0" ]
RabbitTeam/Rabbit-Extensions
src/Rabbit.Extensions.Boot/RabbitStarter.cs
3,587
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("WebMarket.Service")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebMarket.Service")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("37d860d9-97d2-43fa-ad98-8a49b4d64468")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.891892
84
0.748217
[ "MIT" ]
davidtang1977/webmarket
WebMarket/WebMarket.Service/Properties/AssemblyInfo.cs
1,405
C#
namespace JokesFunApp.Web.Controllers { using JokesFunApp.Services.DataServices; using JokesFunApp.Services.Models; using JokesFunApp.Services.Models.Home; using Microsoft.AspNetCore.Mvc; using System.Diagnostics; public class HomeController : BaseController { private readonly IJokesService jokesService; public HomeController(IJokesService jokesService) { this.jokesService = jokesService; } public IActionResult Index() { var jokes = this.jokesService.GetRandomJokes(20); var viewModel = new IndexViewModel { Jokes = jokes }; return this.View(viewModel); } public IActionResult Privacy() { return this.View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return this.View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? this.HttpContext.TraceIdentifier }); } } }
25.318182
122
0.608618
[ "MIT" ]
Aleksandrov91/JokesFunApp
src/Web/JokesFunApp.Web/Controllers/HomeController.cs
1,116
C#
namespace DefineClass { using System; class Display { private const byte maxSize = 6; private const byte defaultSize = 3; private const uint defaultColors = 1; private float size; private uint colors; // Parameterless constructor public Display() : this(defaultSize, defaultColors) { } // Constructor with parameters public Display(float inches, uint color) { this.Size = inches; this.Colors = color; } public float Size { get { return this.size; } set { if (value > maxSize) { throw new ArgumentOutOfRangeException("This is GSM, not a tablet..."); } this.size = value; } } public uint Colors { get { return this.colors; } set { this.colors = value; } } } }
20.921569
90
0.448922
[ "MIT" ]
GAlex7/TA
03. CSharpOOP/01. Defining Classes - Part 1/DefineClass/Display.cs
1,069
C#
using System; using System.Net.Http; using System.Threading.Tasks; namespace Blogifier.Shared { public class ProgressiveStreamContent : StreamContent { public event Action<long, double> OnProgress; private readonly System.IO.Stream _stream; private readonly int _maxBuffer = 1024 * 4; public ProgressiveStreamContent(System.IO.Stream stream, int maxBuffer, Action<long, double> onProgress) : base(stream) { _stream = stream; _maxBuffer = maxBuffer; OnProgress += onProgress; } protected async override Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) { var buffer = new byte[_maxBuffer]; var totalLength = _stream.Length; var uploadedByteCount = 0L; var lastPercentage = 0; using (_stream) { while (true) { var length = await _stream.ReadAsync(buffer, 0, _maxBuffer); if (length <= 0) { break; } uploadedByteCount += length; var percentage = (int)(uploadedByteCount * 100 / _stream.Length); await stream.WriteAsync(buffer); if(percentage != lastPercentage && percentage != 100) { OnProgress?.Invoke(uploadedByteCount, percentage); lastPercentage = percentage; await Task.Yield(); } } OnProgress?.Invoke(uploadedByteCount, 100); } } } }
30.719298
127
0.520845
[ "MIT" ]
tdgiertz/Blogifier
src/Blogifier.Shared/ProgressiveStreamContent.cs
1,751
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.ApiManagement.V20190101 { /// <summary> /// Tag Contract details. /// </summary> [AzureNextGenResourceType("azure-nextgen:apimanagement/v20190101:TagByApi")] public partial class TagByApi : Pulumi.CustomResource { /// <summary> /// Tag name. /// </summary> [Output("displayName")] public Output<string> DisplayName { get; private set; } = null!; /// <summary> /// Resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Resource type for API Management resource. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a TagByApi resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public TagByApi(string name, TagByApiArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:apimanagement/v20190101:TagByApi", name, args ?? new TagByApiArgs(), MakeResourceOptions(options, "")) { } private TagByApi(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:apimanagement/v20190101:TagByApi", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:apimanagement:TagByApi"}, new Pulumi.Alias { Type = "azure-nextgen:apimanagement/latest:TagByApi"}, new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20170301:TagByApi"}, new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20180101:TagByApi"}, new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20180601preview:TagByApi"}, new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20191201:TagByApi"}, new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20191201preview:TagByApi"}, new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20200601preview:TagByApi"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing TagByApi resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static TagByApi Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new TagByApi(name, id, options); } } public sealed class TagByApiArgs : Pulumi.ResourceArgs { /// <summary> /// API revision identifier. Must be unique in the current API Management service instance. Non-current revision has ;rev=n as a suffix where n is the revision number. /// </summary> [Input("apiId", required: true)] public Input<string> ApiId { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the API Management service. /// </summary> [Input("serviceName", required: true)] public Input<string> ServiceName { get; set; } = null!; /// <summary> /// Tag identifier. Must be unique in the current API Management service instance. /// </summary> [Input("tagId")] public Input<string>? TagId { get; set; } public TagByApiArgs() { } } }
42.024793
175
0.602557
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/ApiManagement/V20190101/TagByApi.cs
5,085
C#
namespace _04._Iterator { /// <summary> /// The 'Aggregate' interface /// </summary> interface IAbstractCollection { Iterator CreateIterator(); } }
16.454545
34
0.585635
[ "MIT" ]
pirocorp/Databases-Advanced---Entity-Framework
15. DESIGN PATTERNS/03. Behavioral Patterns/04. Iterator/IAbstractCollection.cs
183
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 JsDbg.VisualStudio { 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", "15.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("JsDbg.VisualStudio.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; } } } }
44.390625
174
0.598733
[ "MIT" ]
Amrt1n3zm/JsDbg
server/JsDbg.VisualStudio/Resources.Designer.cs
2,843
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace BaiduMapAPI.APIs.Location { /// <summary> /// 普通IP定位 /// </summary> public class IP : Models.GetRequest<IPResult> { /// <summary> /// 接口地址 /// </summary> public override string URL => "https://api.map.baidu.com/location/ip"; /// <summary> /// 用户上网的IP地址 /// <para>请求中如果不出现或为空,会针对发来请求的IP进行定位。</para> /// <para>如您需要通过IPv6来获取位置信息,请提交工单申请。</para> /// <para><![CDATA[http://lbsyun.baidu.com/apiconsole/fankui]]></para> /// </summary> [Display(Name = "ip")] public string IPAddress { get; set; } /// <summary> /// 返回位置信息的坐标类型 /// <para>设置返回位置信息中,经纬度的坐标类型</para> /// <para>坐标类型,分别如下:</para> /// <list type="number"> /// <item>bd09ll <c>百度经纬度坐标,在国测局坐标基础之上二次加密而来</c></item> /// <item>gcj02 <c>国测局02坐标,在原始GPS坐标基础上,按照国家测绘行业统一要求,加密后的坐标</c></item> /// </list> /// <para><c>注意:百度地图的坐标类型为bd09ll,如果结合百度地图使用,请注意坐标选择</c></para> /// </summary> [Display(Name = "coor")] public Models.Enums.CoordType? Coor { get; set; } } }
30.365854
78
0.561446
[ "MIT" ]
miracleQin/BaiduMapServerAPI.SDK
BaiduMapAPI.SDK/APIs/Location/IP.cs
1,629
C#
using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using PierreVendors.Models; namespace PierreVendors.Tests { [TestClass] public class VendorTests : IDisposable { public void Dispose() { Vendor.ClearAll(); } [TestMethod] public void VendorConstructor_CreatesInstanceOfVendor_Vendor() { Vendor newVendor = new Vendor("Brad's Butter Emporium", "Typically buys a lot of bread to butter"); Assert.AreEqual(typeof(Vendor), newVendor.GetType()); } [TestMethod] public void GetName_ReturnsName_String() { string name = "Brad's Butter Emporium"; Vendor newVendor = new Vendor(name, "Typically buys a lot of bread to butter"); string result = newVendor.Name; Assert.AreEqual(name, result); } [TestMethod] public void GetDescription_ReturnsDescription_String() { string description = "Typically buys a lot of bread to butter"; Vendor newVendor = new Vendor("Brad's Butter Emporium", description); string result = newVendor.Description; Assert.AreEqual(description, result); } [TestMethod] public void GetAll_ReturnsEmptyList_VendorList() { List<Vendor> newList = new List<Vendor> { }; List<Vendor> result = Vendor.GetAll(); CollectionAssert.AreEqual(newList, result); } [TestMethod] public void GetAll_ReturnsVendors_VendorList() { Vendor newVendorA = new Vendor("Brad's Butter Emporium", "Typically buys a lot of bread to butter"); Vendor newVendorB = new Vendor("Sammy's Sandwiches", "Frequently purchases hoagie rolls"); List<Vendor> newList = new List<Vendor> { newVendorA, newVendorB }; List<Vendor> result = Vendor.GetAll(); CollectionAssert.AreEqual(newList, result); } [TestMethod] public void GetId_ReturnsId_Int() { Vendor newVendor = new Vendor("Brad's Butter Emporium", "Typically buys a lot of bread to butter"); int result = newVendor.Id; Assert.AreEqual(1, result); } [TestMethod] public void GetId_ReturnsIdBasedOnPositionInList_Int() { Vendor newVendorA = new Vendor("Brad's Butter Emporium", "Typically buys a lot of bread to butter"); Vendor newVendorB = new Vendor("Sammy's Sandwiches", "Frequently purchases hoagie rolls"); int result = newVendorB.Id; Assert.AreEqual(2, result); } [TestMethod] public void Find_ReturnsCorrectVendor_Vendor() { Vendor newVendorA = new Vendor("Brad's Butter Emporium", "Typically buys a lot of bread to butter"); Vendor newVendorB = new Vendor("Sammy's Sandwiches", "Frequently purchases hoagie rolls"); Vendor result = Vendor.Find(2); Assert.AreEqual(newVendorB, result); } [TestMethod] public void GetOrders_ReturnsEmptyOrders_OrderList() { Vendor newVendor = new Vendor("Brad's Butter Emporium", "Typically buys a lot of bread to butter"); List<Order> newList = new List<Order> { }; List<Order> result = newVendor.Orders; CollectionAssert.AreEqual(newList, result); } [TestMethod] public void AddOrder_AssociatesOrderWithVendor_OrderList() { Order newOrder = new Order("Bread", "10 loaves of bread", 50, "03/05/2021"); List<Order> newList = new List<Order> { newOrder }; Vendor newVendor = new Vendor("Brad's Butter Emporium", "Typically buys a lot of bread to butter"); newVendor.AddOrder(newOrder); List<Order> result = newVendor.Orders; CollectionAssert.AreEqual(newList, result); } } }
34.438095
106
0.683075
[ "MIT" ]
Pingel88/PierreVendors.Solution
PierreVendors.Tests/ModelTests/VendorTests.cs
3,616
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/IPExport.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="IP_MCAST_COUNTER_INFO" /> struct.</summary> public static unsafe partial class IP_MCAST_COUNTER_INFOTests { /// <summary>Validates that the <see cref="IP_MCAST_COUNTER_INFO" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<IP_MCAST_COUNTER_INFO>(), Is.EqualTo(sizeof(IP_MCAST_COUNTER_INFO))); } /// <summary>Validates that the <see cref="IP_MCAST_COUNTER_INFO" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(IP_MCAST_COUNTER_INFO).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="IP_MCAST_COUNTER_INFO" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(IP_MCAST_COUNTER_INFO), Is.EqualTo(32)); } }
38.628571
145
0.727071
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
tests/Interop/Windows/Windows/um/IPExport/IP_MCAST_COUNTER_INFOTests.cs
1,354
C#
using Microsoft.TeamFoundation.Core.WebApi; using Microsoft.TeamFoundation.Core.WebApi.Types; using Microsoft.TeamFoundation.SourceControl.WebApi; using Microsoft.TeamFoundation.WorkItemTracking.WebApi; using Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models; using Microsoft.VisualStudio.Services.WebApi; using Microsoft.VisualStudio.Services.WebApi.Patch; using Microsoft.VisualStudio.Services.WebApi.Patch.Json; using System; using System.Collections.Generic; namespace Microsoft.Azure.DevOps.ClientSamples.WorkItemTracking { /// <summary> /// Client samples for managing work items in Team Services and Team Foundation Server. /// </summary> [ClientSample(WitConstants.WorkItemTrackingWebConstants.RestAreaName, "workitemssamples")] public class WorkItemsSample : ClientSample { [ClientSampleMethod] public WorkItem CreateWorkItem() { // Construct the object containing field values required for the new work item JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.Title", Value = "Sample task 1" } ); //patchDocument.Add( // new JsonPatchOperation() // { // Operation = Operation.Add, // Path = "/fields/System.IterationPath", // Value = "Test Project\\Iteration 1" // } //); // Get a client VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); // Get the project to create the sample work item in TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context); // Create the new work item WorkItem newWorkItem = workItemTrackingClient.CreateWorkItemAsync(patchDocument, project.Id, "Task").Result; Console.WriteLine("Created work item ID {0} {1}", newWorkItem.Id, newWorkItem.Fields["System.Title"]); // Save this newly created for later samples Context.SetValue<WorkItem>("$newWorkItem", newWorkItem); return newWorkItem; } [ClientSampleMethod] public WorkItem CreateWorkItem(string title, string type) { // Construct the object containing field values required for the new work item JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.Title", Value = title } ); // Get a client VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); // Get the project to create the sample work item in TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context); // Create the new work item WorkItem newWorkItem = workItemTrackingClient.CreateWorkItemAsync(patchDocument, project.Id, type).Result; Console.WriteLine("Created work item ID {0} {1}", newWorkItem.Id, newWorkItem.Fields["System.Title"]); return newWorkItem; } [ClientSampleMethod] public void CreateSampleWorkItemData() { WorkItem newWorkItem; newWorkItem = this.CreateWorkItem("Sample Task #1", "Task"); Context.SetValue<WorkItem>("$newWorkItem1", newWorkItem); newWorkItem = this.CreateWorkItem("Sample Task #2", "Task"); Context.SetValue<WorkItem>("$newWorkItem2", newWorkItem); newWorkItem = this.CreateWorkItem("Sample Task #3", "Task"); Context.SetValue<WorkItem>("$newWorkItem3", newWorkItem); } [ClientSampleMethod] public List<WorkItem> GetWorkItemsByIDs() { Context.SetValue<int[]>("$workitemIds", new int[] { Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem1").Id), Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem2").Id), Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem3").Id) }); int[] workitemIds = Context.GetValue<int[]>("$workitemIds"); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); List<WorkItem> workitems = workItemTrackingClient.GetWorkItemsAsync(workitemIds).Result; foreach (var workitem in workitems) { Console.WriteLine(" {0}: {1}", workitem.Id, workitem.Fields["System.Title"]); } return workitems; } [ClientSampleMethod] public WorkItemTemplate CreateTemplate() { VssConnection connection = Context.Connection; WorkItemTrackingHttpClient client = connection.GetClient<WorkItemTrackingHttpClient>(); Dictionary<string, string> field = new Dictionary<string, string> { { "System.State", "New" } }; WorkItemTemplate newTemplate = new WorkItemTemplate() { Name = "Test Template", Description = "Template to be created", WorkItemTypeName = "Feature", Fields = field }; WorkItemTemplate result = null; try { result = client.CreateTemplateAsync(newTemplate, getTeamContext()).Result; Context.SetValue<Guid>("$newTemplateId", result.Id); Console.WriteLine("Create template Successed."); } catch (Exception e) { Console.WriteLine("Create template Failed:" + e.Message); } return result; } [ClientSampleMethod] public List<WorkItem> GetWorkItemsWithSpecificFields() { int[] workitemIds = Context.GetValue<int[]>("$workitemIds"); string[] fieldNames = new string[] { "System.Id", "System.Title", "System.WorkItemType" }; VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); List<WorkItem> workitems = workItemTrackingClient.GetWorkItemsAsync(workitemIds, fieldNames).Result; foreach (var workitem in workitems) { Console.WriteLine(workitem.Id); foreach (var fieldName in fieldNames) { Console.Write(" {0}: {1}", fieldName, workitem.Fields[fieldName]); } } return workitems; } [ClientSampleMethod] public List<WorkItem> GetWorkItemsAsOfDate() { int[] workitemIds = Context.GetValue<int[]>("$workitemIds"); string[] fieldNames = new string[] { "System.Id", "System.Title", "System.WorkItemType" }; DateTime asOfDate = new DateTime(2016, 12, 31); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); List<WorkItem> workitems = workItemTrackingClient.GetWorkItemsAsync(workitemIds, fieldNames, asOfDate).Result; foreach (var workitem in workitems) { Console.WriteLine(workitem.Id); foreach (var fieldName in fieldNames) { Console.Write(" {0}: {1}", fieldName, workitem.Fields[fieldName]); } } return workitems; } [ClientSampleMethod] public List<WorkItem> GetWorkItemsWithLinksAndAttachments() { int[] workitemIds = Context.GetValue<int[]>("$workitemIds"); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); List<WorkItem> workitems = workItemTrackingClient.GetWorkItemsAsync(workitemIds, expand: WorkItemExpand.Links | WorkItemExpand.Relations).Result; foreach(var workitem in workitems) { Console.WriteLine("Work item {0}", workitem.Id); if (workitem.Relations == null) { Console.WriteLine(" No relations found on this work item"); } else { foreach (var relation in workitem.Relations) { Console.WriteLine(" {0} {1}", relation.Rel, relation.Url); } } } return workitems; } [ClientSampleMethod] public WorkItem GetWorkItemById() { int id = Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem1").Id); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); WorkItem workitem = workItemTrackingClient.GetWorkItemAsync(id).Result; foreach (var field in workitem.Fields) { Console.WriteLine(" {0}: {1}", field.Key, field.Value); } return workitem; } [ClientSampleMethod] public WorkItem GetWorkItemFullyExpanded() { int id = Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem1").Id); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); WorkItem workitem = workItemTrackingClient.GetWorkItemAsync(id, expand: WorkItemExpand.All).Result; Console.WriteLine(workitem.Id); Console.WriteLine("Fields: "); foreach (var field in workitem.Fields) { Console.WriteLine(" {0}: {1}", field.Key, field.Value); } Console.WriteLine("Relations: "); if (workitem.Relations == null) { Console.WriteLine(" No relations found for this work item"); } else { foreach (var relation in workitem.Relations) { Console.WriteLine(" {0} {1}", relation.Rel, relation.Url); } } return workitem; } [ClientSampleMethod] public WorkItem CreateAndLinkToWorkItem() { string title = "My new work item with links"; string description = "This is a new work item that has a link also created on it."; string linkUrl = Context.GetValue<WorkItem>("$newWorkItem1").Url; //get the url of a previously added work item JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.Title", Value = title } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.Description", Value = description } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.History", Value = "Jim has the most context around this." } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/relations/-", Value = new { rel = "System.LinkTypes.Hierarchy-Reverse", url = linkUrl, attributes = new { comment = "decomposition of work" } } } ); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); // Get the project to create the sample work item in TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context); WorkItem result = workItemTrackingClient.CreateWorkItemAsync(patchDocument, project.Name, "Task").Result; return result; } [ClientSampleMethod] public WorkItem BypassRulesOnCreate() { JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.Title", Value = "JavaScript implementation for Microsoft Account" } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.CreatedDate", Value = "6/1/2016" } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.CreatedBy", Value = "Art VanDelay" } ); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); // Get the project to create the sample work item in TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context); WorkItem result = workItemTrackingClient.CreateWorkItemAsync(patchDocument, project.Name, "Task", bypassRules: true).Result; return result; } [ClientSampleMethod] public WorkItem UpdateValidateOnly() { int id = Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem").Id); JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Test, Path = "/rev", Value = "1" } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.Title", Value = "Hello World" } ); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); //set validateOnly param == true. This will only validate the work item. it will not attempt to save it. WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, id, true).Result; return result; } [ClientSampleMethod] public WorkItem ChangeFieldValue() { int id = Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem").Id); JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Test, Path = "/rev", Value = "1" } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.Title", Value = "This is the new title for my work item" } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.History", Value = "Changing priority" } ); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, id).Result; return result; } [ClientSampleMethod] public WorkItem AddTags() { int id = Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem2").Id); string[] tags = { "teamservices", "client", "sample" }; JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.Tags", Value = string.Join(";", tags) } ); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, id).Result; return result; } [ClientSampleMethod] public WorkItem LinkToOtherWorkItem() { int sourceWorkItemId = Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem1").Id); int targetWorkItemId = Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem2").Id); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); // Get work target work item WorkItem targetWorkItem = workItemTrackingClient.GetWorkItemAsync(targetWorkItemId).Result; JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/relations/-", Value = new { rel = "System.LinkTypes.Dependency-forward", url = targetWorkItem.Url, attributes = new { comment = "Making a new link for the dependency" } } } ); WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, sourceWorkItemId).Result; return result; } /// <summary> /// get a list of the child work items for a specific parent /// </summary> /// <returns></returns> [ClientSampleMethod] public List<WorkItem> GetChildWorkItemsByParent() { int id = Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem1").Id); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); WorkItem workitem = workItemTrackingClient.GetWorkItemAsync(id, expand: WorkItemExpand.Relations).Result; List<WorkItem> workitems = null; if (workitem.Relations == null) { Console.WriteLine(" No relations found for this work item"); } else { List<int> list = new List<int>(); Console.WriteLine("Getting child work items from parent..."); foreach (var relation in workitem.Relations) { //get the child links if (relation.Rel == "System.LinkTypes.Hierarchy-Forward") { var lastIndex = relation.Url.LastIndexOf("/"); var itemId = relation.Url.Substring(lastIndex + 1); list.Add(Convert.ToInt32(itemId)); Console.WriteLine(" {0} ", itemId); }; } int[] workitemIds = list.ToArray(); workitems = workItemTrackingClient.GetWorkItemsAsync(workitemIds).Result; Console.WriteLine("Getting full work item for each child..."); foreach (var item in workitems) { Console.WriteLine(" {0}: {1} : {2}", item.Fields["System.WorkItemType"], item.Id, item.Fields["System.Title"]); } } return workitems; } [ClientSampleMethod] public WorkItem UpdateLinkComment() { int id = Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem1").Id); JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Test, Path = "/rev", Value = "1" } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Replace, Path = "/relations/0/attributes/comment", Value = "Adding traceability to dependencies" } ); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, id).Result; return result; } public WorkItem RemoveLink() { int id = Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem1").Id); JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Test, Path = "/rev", Value = "1" } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Remove, Path = "/relations/0" } ); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, id).Result; return result; } [ClientSampleMethod] public WorkItem AddAttachment() { int id = Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem3").Id); string filePath = ClientSampleHelpers.GetSampleTextFile(); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); // upload attachment to store and get a reference to that file AttachmentReference attachmentReference = workItemTrackingClient.CreateAttachmentAsync(filePath).Result; JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Test, Path = "/rev", Value = "1" } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.History", Value = "Adding the necessary spec" } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/relations/-", Value = new { rel = "AttachedFile", url = attachmentReference.Url, attributes = new { comment = "VanDelay Industries - Spec" } } } ); WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, id).Result; return result; } [ClientSampleMethod] public WorkItem RemoveAttachment() { int id = Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem3").Id); string rev = "0"; JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Test, Path = "/rev", Value = "2" } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Remove, Path = "/relations/" + rev } ); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, id).Result; return result; } [ClientSampleMethod] public WorkItem UpdateWorkItemAddHyperLink() { int id = Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem2").Id); JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Test, Path = "/rev", Value = "2" } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/relations/-", Value = new { rel = "Hyperlink", url = "https://docs.microsoft.com/en-us/rest/api/vsts/" } } ); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, id).Result; return result; } [ClientSampleMethod] public WorkItem UpdateWorkItemUsingByPassRules() { int id = Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem2").Id); JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.CreatedBy", Value = "Foo <Foo@hotmail.com>" } ); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, id, null, true).Result; return result; } [ClientSampleMethod] public WorkItemDelete DeleteWorkItem() { int id = Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem2").Id); // Get a client VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); // Delete the work item (but don't destroy it completely) WorkItemDelete results = workItemTrackingClient.DeleteWorkItemAsync(id, destroy: false).Result; return results; } public WorkItem MoveToAnotherProject() { int id = -1; string targetProject = null; string targetAreaPath = null; string targetIterationPath = null; JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.TeamProject", Value = targetProject } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.AreaPath", Value = targetAreaPath } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.IterationPath", Value = targetIterationPath } ); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, id).Result; return result; } public WorkItem ChangeType() { WorkItem newWorkItem; using (new ClientSampleHttpLoggerOutputSuppression()) { newWorkItem = this.CreateWorkItem("Another Sample Work Item", "Task"); } int id = Convert.ToInt32(newWorkItem.Id); JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.WorkItemType", Value = "User Story" } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.State", Value = "Active" } ); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, id).Result; return result; } public WorkItem UpdateWorkItemLinkToPullRequest() { int id = Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem2").Id); VssConnection connection = Context.Connection; GitHttpClient gitClient = connection.GetClient<GitHttpClient>(); //you will need to edit this line and enter a legit pull request id var pullRequest = gitClient.GetPullRequestByIdAsync(999).Result; var pullRequestUri = pullRequest.ArtifactId; JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Test, Path = "/rev", Value = "3" } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/relations/-", Value = new { rel = "ArtifactLink", url = pullRequestUri, attributes = new { comment = "Fixed in Commit", name = "pull request" } } } ); WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, id).Result; return result; } public WorkItem UpdateWorkItemLinkToCommit() { int id = Convert.ToInt32(Context.GetValue<WorkItem>("$newWorkItem2").Id); System.Guid repositoryId = new Guid("2f3d611a-f012-4b39-b157-8db63f380226"); string commitId = "be67f8871a4d2c75f13a51c1d3c30ac0d74d4ef4"; VssConnection connection = Context.Connection; GitHttpClient gitClient = connection.GetClient<GitHttpClient>(); //you will need to edit this line and enter a legit repo id and commit id //these are samples and will not work var commit = gitClient.GetCommitAsync(commitId, repositoryId).Result; var commitUri = commit.Url; JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Test, Path = "/rev", Value = "3" } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/relations/-", Value = new { rel = "ArtifactLink", url = commitUri, attributes = new { comment = "Fixed in Commit", name = "commit" } } } ); WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, id).Result; return result; } public void UpdateWorkItemsByQueryResults(WorkItemQueryResult workItemQueryResult, string changedBy) { JsonPatchDocument patchDocument = new JsonPatchDocument(); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/Microsoft.VSTS.Common.BacklogPriority", Value = "2", From = changedBy } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.History", Value = "comment from client lib sample code", From = changedBy } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/System.State", Value = "Active", From = changedBy } ); VssConnection connection = Context.Connection; WorkItemTrackingHttpClient workItemTrackingClient = connection.GetClient<WorkItemTrackingHttpClient>(); foreach (WorkItemReference workItemReference in workItemQueryResult.WorkItems) { WorkItem result = workItemTrackingClient.UpdateWorkItemAsync(patchDocument, workItemReference.Id).Result; } } [ClientSampleMethod] public WorkItem GetWorkItemTemplate() { VssConnection connection = Context.Connection; WorkItemTrackingHttpClient client = connection.GetClient<WorkItemTrackingHttpClient>(); // Get the project to create the sample work item in TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context); WorkItem result = client.GetWorkItemTemplateAsync(project.Name, "Bug").Result; return result; } [ClientSampleMethod] public List<WorkItemTemplateReference> ListTemplates() { VssConnection connection = Context.Connection; WorkItemTrackingHttpClient client = connection.GetClient<WorkItemTrackingHttpClient>(); List<WorkItemTemplateReference> result = client.GetTemplatesAsync(getTeamContext()).Result; return result; } [ClientSampleMethod] public WorkItem GetTemplate() { VssConnection connection = Context.Connection; WorkItemTrackingHttpClient client = connection.GetClient<WorkItemTrackingHttpClient>(); TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context); WorkItem result = client.GetWorkItemTemplateAsync(project.Name, "Feature").Result; return result; } [ClientSampleMethod] public WorkItemTemplate ReplaceTemplate() { VssConnection connection = Context.Connection; WorkItemTrackingHttpClient client = connection.GetClient<WorkItemTrackingHttpClient>(); Dictionary<string, string> field = new Dictionary<string, string> { { "System.State", "Replaced" } }; WorkItemTemplate newTemplate = new WorkItemTemplate() { Name = "New Test Template", Description = "Replacing template", WorkItemTypeName = "Feature", Fields = field }; WorkItemTemplate result = null; try { result = client.ReplaceTemplateAsync(newTemplate, getTeamContext(), Context.GetValue<Guid>("$newTemplateId")).Result; Console.WriteLine("Replace template successed."); } catch(Exception e) { result = null; Console.WriteLine("Replace template failed: " + e.Message); } return result; } [ClientSampleMethod] public WorkItem UpdateWorkItemBoardColumn() { string targetColumn = "Testing"; //need to set to match your board VssConnection connection = Context.Connection; WorkItemTrackingHttpClient witClient = connection.GetClient<WorkItemTrackingHttpClient>(); JsonPatchDocument patchDocument = new JsonPatchDocument(); //create a work item that drops into the new column by default WorkItem workItem = this.CreateWorkItem("Board Column Test", "User Story"); string wefField = ""; //find the WEF field //todo: do something smarter rather than loop through all fields to find the WEF foreach (var field in workItem.Fields) { if (field.Key.Contains("_Kanban.Column")) { wefField = field.Key.ToString(); break; } } //build a patch document to update the WEF field patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Test, Path = "/rev", Value = "1" } ); patchDocument.Add( new JsonPatchOperation() { Operation = Operation.Add, Path = "/fields/" + wefField, Value = targetColumn } ); WorkItem result = witClient.UpdateWorkItemAsync(patchDocument, Convert.ToInt32(workItem.Id)).Result; Context.Log("Updated work item to teams board column '" + targetColumn + "'"); return result; } [ClientSampleMethod] public void DeleteTemplate() { VssConnection connection = Context.Connection; WorkItemTrackingHttpClient client = connection.GetClient<WorkItemTrackingHttpClient>(); try { client.DeleteTemplateAsync(getTeamContext(), Context.GetValue<Guid>("$newTemplateId")); Console.WriteLine("Delete template successed."); } catch { Console.WriteLine("Delete template Failded."); } } private TeamContext getTeamContext() { TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context); WebApiTeamRef team = ClientSampleHelpers.FindAnyTeam(this.Context, project.Id); TeamContext teamContext = new TeamContext(project.Name, team.Name); return teamContext; } } }
36.111675
261
0.537133
[ "MIT" ]
4vidya2022/azure-devops-dotnet-samples
ClientLibrary/Samples/WorkItemTracking/WorkItemsSample.cs
42,686
C#
using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.Extensions.Hosting; namespace Milou.Deployer.Web.Core.Health { [UsedImplicitly] public class HealthBackgroundService : BackgroundService { private readonly HealthChecker _healthChecker; public HealthBackgroundService(HealthChecker healthChecker) { _healthChecker = healthChecker; } protected override Task ExecuteAsync(CancellationToken stoppingToken) { return _healthChecker.DoHealthChecksAsync(stoppingToken); } } }
26.782609
77
0.714286
[ "MIT" ]
milou-se/milou.deployer.web
src/Milou.Deployer.Web.Core/Health/HealthBackgroundService.cs
618
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview { using static Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Extensions; /// <summary>Resource tags.</summary> public partial class MoveCollectionTags : Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.IMoveCollectionTags, Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Models.Api20191001Preview.IMoveCollectionTagsInternal { /// <summary>Creates an new <see cref="MoveCollectionTags" /> instance.</summary> public MoveCollectionTags() { } } /// Resource tags. public partial interface IMoveCollectionTags : Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.IJsonSerializable, Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.IAssociativeArray<string> { } /// Resource tags. internal partial interface IMoveCollectionTagsInternal { } }
34.166667
111
0.716098
[ "MIT" ]
3quanfeng/azure-powershell
src/ResourceMover/generated/api/Models/Api20191001Preview/MoveCollectionTags.cs
996
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PopNTouch2.Model { /// <summary> /// Enum used by every Note to store its accidentals (Sharp, Flat or None) /// </summary> public enum Accidental { None, Flat, Sharp, } }
17.611111
78
0.618297
[ "MIT" ]
nbusseneau/Pop-n-Touch
src/PopNTouch2/Model/Notes/Accidental.cs
319
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Red.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Red.Formats.Red.Records.Enums; namespace GameEstate.Red.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class BTTaskRaiseEventOnDeactivate : IBehTreeTask { [Ordinal(1)] [RED("eventName")] public CName EventName { get; set;} public BTTaskRaiseEventOnDeactivate(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new BTTaskRaiseEventOnDeactivate(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
33.56
140
0.743743
[ "MIT" ]
bclnet/GameEstate
src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/BTTaskRaiseEventOnDeactivate.cs
839
C#
using System; namespace EricBach.CQRS.Commands { public interface ICommand { Guid Id { get; } } }
13.222222
32
0.605042
[ "MIT" ]
eric-bach/EricBach.CQRS
EricBach.CQRS/Commands/ICommand.cs
121
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ExternalNmeaGPS.Controls { /// <summary> /// Interaction logic for SatelliteView.xaml /// </summary> public partial class SatelliteView : UserControl { public SatelliteView() { InitializeComponent(); } public NmeaParser.Messages.Gsv GsvMessage { get { return (NmeaParser.Messages.Gsv)GetValue(GsvMessageProperty); } set { SetValue(GsvMessageProperty, value); } } public static readonly DependencyProperty GsvMessageProperty = DependencyProperty.Register(nameof(GsvMessage), typeof(NmeaParser.Messages.Gsv), typeof(SatelliteView), new PropertyMetadata(null, OnGsvMessagePropertyChanged)); private static void OnGsvMessagePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var sats = e.NewValue as NmeaParser.Messages.Gsv; if (sats == null) ((SatelliteView)d).satellites.ItemsSource = null; else ((SatelliteView)d).satellites.ItemsSource = sats.SVs; } } public class PolarPlacementItem : ContentControl { public PolarPlacementItem() { HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch; VerticalAlignment = System.Windows.VerticalAlignment.Stretch; } protected override Size ArrangeOverride(Size arrangeBounds) { double az = (Azimuth - 90) / 180 * Math.PI; double e = (90 - Elevation) / 90; double X = Math.Cos(az) * e; double Y = Math.Sin(az) * e; X = arrangeBounds.Width * .5 * X; Y = arrangeBounds.Height * .5 * Y; RenderTransform = new TranslateTransform(X, Y); return base.ArrangeOverride(arrangeBounds); } public double Azimuth { get { return (double)GetValue(AzimuthProperty); } set { SetValue(AzimuthProperty, value); } } public static readonly DependencyProperty AzimuthProperty = DependencyProperty.Register("Azimuth", typeof(double), typeof(PolarPlacementItem), new PropertyMetadata(0d, OnAzimuthPropertyChanged)); private static void OnAzimuthPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((UIElement)d).InvalidateArrange(); } public double Elevation { get { return (double)GetValue(ElevationProperty); } set { SetValue(ElevationProperty, value); } } public static readonly DependencyProperty ElevationProperty = DependencyProperty.Register("Elevation", typeof(double), typeof(PolarPlacementItem), new PropertyMetadata(0d, OnElevationPropertyChanged)); private static void OnElevationPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((UIElement)d).InvalidateArrange(); } } }
30.936842
164
0.75672
[ "Apache-2.0" ]
KarenQuartic/arcgis-runtime-demos-dotnet
src/ExternalNmeaGPS/ExternalNmeaGPS.Desktop/Controls/SatelliteView.xaml.cs
2,941
C#
using System; using System.Windows.Forms; namespace CharacterCreator.Winforms { partial class CharacterForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose ( bool disposing ) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent () { this._txtName = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); this._CbProfession = new System.Windows.Forms.ComboBox(); this._CbRace = new System.Windows.Forms.ComboBox(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.label12 = new System.Windows.Forms.Label(); this.label13 = new System.Windows.Forms.Label(); this.btnSave = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.label14 = new System.Windows.Forms.Label(); this._txtDescription = new System.Windows.Forms.TextBox(); this._txtStrength = new System.Windows.Forms.NumericUpDown(); this._txtIntelligence = new System.Windows.Forms.NumericUpDown(); this._txtAgility = new System.Windows.Forms.NumericUpDown(); this._txtConstitution = new System.Windows.Forms.NumericUpDown(); this._txtCharisma = new System.Windows.Forms.NumericUpDown(); this.menuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this._txtStrength)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this._txtIntelligence)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this._txtAgility)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this._txtConstitution)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this._txtCharisma)).BeginInit(); this.SuspendLayout(); // // _txtName // this._txtName.Location = new System.Drawing.Point(121, 12); this._txtName.Name = "_txtName"; this._txtName.Size = new System.Drawing.Size(112, 23); this._txtName.TabIndex = 0; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(73, 12); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(42, 15); this.label1.TabIndex = 1; this.label1.Text = "Name:"; this.label1.Click += new System.EventHandler(this.label1_Click); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(-41, 64); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(38, 15); this.label2.TabIndex = 2; this.label2.Text = "label2"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(-41, 72); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(38, 15); this.label3.TabIndex = 3; this.label3.Text = "label3"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(-41, 84); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(38, 15); this.label4.TabIndex = 4; this.label4.Text = "label4"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(50, 50); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(65, 15); this.label5.TabIndex = 5; this.label5.Text = "Profession:"; this.label5.Click += new System.EventHandler(this.label5_Click); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem1, this.toolStripMenuItem2}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(284, 24); this.menuStrip1.TabIndex = 7; this.menuStrip1.Text = "menuStrip1"; this.menuStrip1.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.menuStrip1_ItemClicked); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(12, 20); // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(12, 20); // // _CbProfession // this._CbProfession.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._CbProfession.FormattingEnabled = true; this._CbProfession.Items.AddRange(new object[] { "Fighter", "Hunter", "Priest", "Rogue", "Wizard"}); this._CbProfession.Location = new System.Drawing.Point(120, 39); this._CbProfession.Name = "_CbProfession"; this._CbProfession.Size = new System.Drawing.Size(112, 23); this._CbProfession.TabIndex = 8; this._CbProfession.SelectedIndexChanged += new System.EventHandler(this.comboProfession_SelectedIndexChanged); // // _CbRace // this._CbRace.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._CbRace.FormattingEnabled = true; this._CbRace.Items.AddRange(new object[] { "Dwarf", "Elf", "Gnome", "Half Elf", "Human"}); this._CbRace.Location = new System.Drawing.Point(120, 68); this._CbRace.Name = "_CbRace"; this._CbRace.Size = new System.Drawing.Size(112, 23); this._CbRace.TabIndex = 9; this._CbRace.SelectedIndexChanged += new System.EventHandler(this.comboBox2_SelectedIndexChanged); // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(80, 81); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(35, 15); this.label6.TabIndex = 10; this.label6.Text = "Race:"; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(60, 105); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(55, 15); this.label7.TabIndex = 11; this.label7.Text = "Strength:"; this.label7.Click += new System.EventHandler(this.label7_Click); // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(16, 47); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(0, 15); this.label8.TabIndex = 13; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(22, 218); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(0, 15); this.label9.TabIndex = 15; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(44, 134); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(71, 15); this.label10.TabIndex = 16; this.label10.Text = "Intelligence:"; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(71, 160); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(44, 15); this.label11.TabIndex = 17; this.label11.Text = "Agility:"; this.label11.Click += new System.EventHandler(this.label11_Click); // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(37, 183); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(76, 15); this.label12.TabIndex = 19; this.label12.Text = "Constitution:"; this.label12.Click += new System.EventHandler(this.label12_Click); // // label13 // this.label13.AutoSize = true; this.label13.Location = new System.Drawing.Point(53, 212); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(60, 15); this.label13.TabIndex = 21; this.label13.Text = "Charisma:"; // // btnSave // this.btnSave.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnSave.Location = new System.Drawing.Point(89, 351); this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(75, 23); this.btnSave.TabIndex = 25; this.btnSave.Text = "save"; this.btnSave.UseVisualStyleBackColor = true; this.btnSave.Click += new System.EventHandler(this.OnSave); // // btnCancel // this.btnCancel.Location = new System.Drawing.Point(185, 351); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(75, 23); this.btnCancel.TabIndex = 26; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // label14 // this.label14.AutoSize = true; this.label14.Location = new System.Drawing.Point(51, 261); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(67, 15); this.label14.TabIndex = 32; this.label14.Text = "Description"; // // _txtDescription // this._txtDescription.Location = new System.Drawing.Point(118, 239); this._txtDescription.Multiline = true; this._txtDescription.Name = "_txtDescription"; this._txtDescription.Size = new System.Drawing.Size(112, 70); this._txtDescription.TabIndex = 33; // // _txtStrength // this._txtStrength.Location = new System.Drawing.Point(121, 97); this._txtStrength.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this._txtStrength.Name = "_txtStrength"; this._txtStrength.Size = new System.Drawing.Size(112, 23); this._txtStrength.TabIndex = 34; this._txtStrength.Tag = "Strength"; this._txtStrength.Value = new decimal(new int[] { 50, 0, 0, 0}); // // _txtIntelligence // this._txtIntelligence.Location = new System.Drawing.Point(121, 126); this._txtIntelligence.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this._txtIntelligence.Name = "_txtIntelligence"; this._txtIntelligence.Size = new System.Drawing.Size(111, 23); this._txtIntelligence.TabIndex = 35; this._txtIntelligence.Tag = "Intellgence"; this._txtIntelligence.Value = new decimal(new int[] { 50, 0, 0, 0}); // // _txtAgility // this._txtAgility.Location = new System.Drawing.Point(121, 152); this._txtAgility.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this._txtAgility.Name = "_txtAgility"; this._txtAgility.Size = new System.Drawing.Size(109, 23); this._txtAgility.TabIndex = 36; this._txtAgility.Tag = "Agility"; this._txtAgility.Value = new decimal(new int[] { 50, 0, 0, 0}); // // _txtConstitution // this._txtConstitution.Location = new System.Drawing.Point(119, 181); this._txtConstitution.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this._txtConstitution.Name = "_txtConstitution"; this._txtConstitution.Size = new System.Drawing.Size(112, 23); this._txtConstitution.TabIndex = 37; this._txtConstitution.Tag = "Constitution"; this._txtConstitution.Value = new decimal(new int[] { 50, 0, 0, 0}); // // _txtCharisma // this._txtCharisma.Location = new System.Drawing.Point(119, 210); this._txtCharisma.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this._txtCharisma.Name = "_txtCharisma"; this._txtCharisma.Size = new System.Drawing.Size(111, 23); this._txtCharisma.TabIndex = 38; this._txtCharisma.Tag = "Charisma"; this._txtCharisma.Value = new decimal(new int[] { 50, 0, 0, 0}); // // CharacterForm // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 411); this.Controls.Add(this._txtCharisma); this.Controls.Add(this._txtConstitution); this.Controls.Add(this._txtAgility); this.Controls.Add(this._txtIntelligence); this.Controls.Add(this._txtStrength); this.Controls.Add(this._txtDescription); this.Controls.Add(this.label14); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnSave); this.Controls.Add(this.label13); this.Controls.Add(this.label12); this.Controls.Add(this.label11); this.Controls.Add(this.label10); this.Controls.Add(this.label9); this.Controls.Add(this.label8); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this._CbRace); this.Controls.Add(this._CbProfession); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this._txtName); this.Controls.Add(this.menuStrip1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MainMenuStrip = this.menuStrip1; this.MaximizeBox = false; this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(260, 420); this.Name = "CharacterForm"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Create New Character"; this.Load += new System.EventHandler(this.CharacterForm_Load); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this._txtStrength)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this._txtIntelligence)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this._txtAgility)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this._txtConstitution)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this._txtCharisma)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } private void btnCancel_Click ( object sender, EventArgs e ) { Close(); } private void OnSavebtn ( object sender, EventArgs e ) { var character = new Character(); character.Name = _txtName.Text; character.Profession =_CbProfession.Text; character.Race = _CbRace.Text; character.Strength = ReadAsInt32(_txtStrength); character.Intelligence = ReadAsInt32(_txtIntelligence); character.Agility = ReadAsInt32(_txtAgility); character.Constitution = ReadAsInt32(_txtConstitution); character.Charisma = ReadAsInt32(_txtCharisma); // Validation var error = character.Validate(); if (!String.IsNullOrEmpty(error)) { // Show error message MessageBox.Show(this, error, "Save failed", MessageBoxButtons.OK, MessageBoxIcon.Error); DialogResult =DialogResult.None; Close(); return; }; //Return character // MessageBox.Show(character.Name); SelectedCharacter = character; // MessageBox.Show(Character.Name); Close(); //var character = new Character(); //character.Name = txtName.Text; //character.Profession =txtComboProfession.SelectedText; //character.Race = txtComboRace.SelectedText; //character.Strength = ReadAsInt32(txtStrength); //character.Intelligence = ReadAsInt32(txtIntelligence); //character.Agility = ReadAsInt32(txtAgility); //character.Constitution = ReadAsInt32(txtConstitution); //character.Charisma = ReadAsInt32(txtCharisma); // Validation // Return character //Close (); } #endregion private System.Windows.Forms.TextBox _txtName; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem2; private System.Windows.Forms.ComboBox _CbProfession; private System.Windows.Forms.ComboBox _CbRace; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label label13; private System.Windows.Forms.Button btnSave; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.TextBox _textname; private System.Windows.Forms.Label label14; private System.Windows.Forms.TextBox _txtDescription; private NumericUpDown _txtStrength; private NumericUpDown _txtIntelligence; private NumericUpDown _txtAgility; private NumericUpDown _txtConstitution; private NumericUpDown _txtCharisma; } }
42.736434
130
0.56462
[ "MIT" ]
bbohara20/itse1430
labs/Lab 2/CharacterCreator.Winforms/CharacterForm.Designer.cs
22,054
C#
using System; namespace T02.FamilyTrip { class Program { static void Main(string[] args) { double budget = double.Parse(Console.ReadLine()); int nights = int.Parse(Console.ReadLine()); double pricePerNight = double.Parse(Console.ReadLine()); int additionalExpensesPercent = int.Parse(Console.ReadLine()); double totalCost = 0; totalCost = pricePerNight * nights; if (nights > 7) { totalCost *= 0.95; } totalCost += budget * additionalExpensesPercent / 100; if (budget >= totalCost) { Console.WriteLine($"Ivanovi will be left with {budget - totalCost:f2} leva after vacation."); } else { Console.WriteLine($"{totalCost - budget:f2} leva needed."); } } } }
28.333333
109
0.51123
[ "MIT" ]
akdimitrov/CSharp-Basics
_PB - EXAMS/Exam Prep - PB Online Exam 6-7July2019/T02.FamilyTrip/Program.cs
937
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Reflection; namespace Heine.Mvc.ActionFilters.Services { public class ObfuscaterService : IObfuscaterService { private readonly int expandDepth; private const string HeaderKeyXObfuscate = "X-Obfuscate"; public ObfuscaterService(int expandDepth, params Assembly[] assemblies) { this.expandDepth = expandDepth; TypeObfuscationGraphs = Initialize(assemblies); } private IDictionary<Type, IList<string>> Initialize(params Assembly[] assemblies) { string BuildPropertyName(PropertyInfo propertyInfo) { var propertyType = propertyInfo.PropertyType; if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(ICollection<>)) return $"{propertyInfo.Name}[*]"; return typeof(ICollection).IsAssignableFrom(propertyType) ? $"{propertyInfo.Name}[*]" // Collection : propertyInfo.Name; // Object or scalar value } Type GetCorrectType(Type type) { if (type.IsArray) return type.GetElementType(); if (type.IsGenericType && type.GetInterfaces().Contains(typeof(IEnumerable))) return type.GetGenericArguments().Last(); return type; } void AddObfuscateProperties(Type type, ref List<string> properties, List<PropertyInfo> prevPropList, int depth) { if (depth == 0) return; // Check if type is already present in list of previous properties. // If so it should not be traversed. if (prevPropList != null) { var typeName = type.FullName; // Support a class referencing itself, // but check for reference loop in other cases. if (!(prevPropList.Count == 1 && typeName == prevPropList.First().DeclaringType?.FullName)) { foreach (var prop in prevPropList) { if (prop.DeclaringType?.FullName == typeName) { return; } } } } foreach (var propertyInfo in type.GetProperties()) { // Empty all previous properties because method is at root. if (depth == expandDepth) { prevPropList = new List<PropertyInfo>(); } // When circling back after a recursive call there will be element/s in list // which should not be present at current depth. // Therefore need to remove all the last elements in list which whould not be at current depth. if (prevPropList.Count > expandDepth - depth) { var numberOfRecordsToDelete = prevPropList.Count - (expandDepth - depth); for (var i = 0; i < numberOfRecordsToDelete; i++) { prevPropList.RemoveAt(prevPropList.Count - 1); } } if (Attribute.IsDefined(propertyInfo, typeof(ObfuscationAttribute))) { if (!prevPropList.Any()) { properties.Add(BuildPropertyName(propertyInfo)); } else { var jPath = string.Empty; foreach (var prop in prevPropList) { jPath += $"{BuildPropertyName(prop)}."; } properties.Add($"{jPath}{BuildPropertyName(propertyInfo)}"); } } else if (propertyInfo.PropertyType.IsClass || propertyInfo.PropertyType.IsInterface) { if (depth - 1 <= 0) continue; var propertyType = GetCorrectType(propertyInfo.PropertyType); prevPropList.Add(propertyInfo); AddObfuscateProperties(propertyType, ref properties, prevPropList, depth - 1); } } } var typeObfuscationGraphs = new Dictionary<Type, IList<string>>(); foreach (var assembly in assemblies) { foreach (var type in assembly.GetTypes()) { var properties = new List<string>(); // Obfuscation attribute on class level. if (Attribute.IsDefined(type, typeof(ObfuscationAttribute))) { foreach (var propertyInfo in type.GetProperties()) { properties.Add(BuildPropertyName(propertyInfo)); } } // Obfuscation attribute on property level. else { AddObfuscateProperties(type, ref properties, null, expandDepth); } if (properties.Any()) typeObfuscationGraphs.Add(type, properties); } } return typeObfuscationGraphs; } public IDictionary<Type, IList<string>> TypeObfuscationGraphs { get; set; } public void SetObfuscateHeader(HttpHeaders httpHeaders, params Type[] types) { if (httpHeaders == null) return; foreach (var type in types) { if (!TypeObfuscationGraphs.ContainsKey(type)) return; if (httpHeaders.TryGetValues(HeaderKeyXObfuscate, out var values)) { if (!httpHeaders.Remove(HeaderKeyXObfuscate)) return; httpHeaders.TryAddWithoutValidation(HeaderKeyXObfuscate, values.Concat(TypeObfuscationGraphs[type]).Distinct()); } else { httpHeaders.TryAddWithoutValidation(HeaderKeyXObfuscate, TypeObfuscationGraphs[type].Distinct()); } } } } }
40.070588
117
0.484439
[ "MIT" ]
hfurubotten/Heine.Mvc.ActionFilters
Heine.Mvc.ActionFilters/Services/ObfuscaterService.cs
6,814
C#
namespace Jane { public interface IDataGenerator { string GetRandomString(byte length, bool includeDigit = true, bool includeUppercase = true, bool includeLowercase = true); string NumberToS36(long number); string NumberToS64(long number); long S36ToNumber(string s36); long S64ToNumber(string s64); } }
24
130
0.675
[ "Apache-2.0" ]
Caskia/Jane
src/Jane/Environment/IDataGenerator.cs
362
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; using System.Net; using System.Linq; using TMPro; public class RankingCanvasController : MonoBehaviour { public GameObject[] ranks; private List<PlayerData> playerList; // Use this for initialization void Awake () { InitRanking(); } private void InitRanking() { var webAddr = GameManager.Instance.URL + "/api/players/"; var req = (HttpWebRequest)WebRequest.Create(webAddr); req.ContentType = "application/json; charset=utf-8"; req.Method = "GET"; var response = (HttpWebResponse)req.GetResponse(); using (var streamReader = new StreamReader(response.GetResponseStream())) { JSONObject result = new JSONObject(streamReader.ReadToEnd()); if (result.GetField("status").ToString().Equals("1")) { //Debug.Log("GetRank successs"); //add players to playerList playerList = new List<PlayerData>(); for (int i = 0; i < result.GetField("players").Count; i++) { JSONObject player = result.GetField("players")[i]; float scores = Converter.JsonToFloat(player.GetField("scores").ToString()); float seeds = Converter.JsonToFloat(player.GetField("seeds").ToString()); //not show scores/seeds of new register player that still did't play the game if (!scores.Equals(0) && !seeds.Equals(0)) { PlayerData playerAdd = new PlayerData( Converter.JsonToString(player.GetField("_id").ToString()), Converter.JsonToString(player.GetField("name").ToString()), scores, seeds); playerList.Add(playerAdd); } } //sort playerList by scores descending playerList = playerList.OrderByDescending(o => o.scores).ToList(); //destroy rank[i] if playerList.Count < ranks.Length int countDelete = 0; for (int i = playerList.Count; i < ranks.Length; i++) { Destroy(ranks[i]); countDelete++; } //match playerList and UI for (int i = 0;i< ranks.Length - countDelete;i++) { //scores ranks[i].transform.GetChild(0).GetChild(0).gameObject.GetComponent<TextMeshProUGUI>().text = playerList[i].scores.ToString(); //seeds ranks[i].transform.GetChild(1).GetChild(0).gameObject.GetComponent<TextMeshProUGUI>().text = playerList[i].seeds.ToString(); //rankNumber ranks[i].transform.GetChild(3).GetChild(0).gameObject.GetComponent<TextMeshProUGUI>().text = "Rank " + (i + 1) + "\n" + playerList[i].name; } } else { //error Debug.Log(result); } } } }
41.421687
261
0.495055
[ "MIT" ]
LNWPOR/HamsterRushVR
Assets/Scripts/RankingCanvasController.cs
3,440
C#
using Google.Protobuf; namespace AElf.Sdk.CSharp.State { /// <summary> /// Wrapper around boolean values for use in smart contract state. /// </summary> public class BoolState : SingletonState<bool> { } /// <summary> /// Wrapper around 32-bit integer values for use in smart contract state. /// </summary> public class Int32State : SingletonState<int> { } /// <summary> /// Wrapper around unsigned 32-bit integer values for use in smart contract state. /// </summary> public class UInt32State : SingletonState<uint> { } /// <summary> /// Wrapper around 64-bit integer values for use in smart contract state. /// </summary> public class Int64State : SingletonState<long> { } /// <summary> /// Wrapper around unsigned 64-bit integer values for use in smart contract state. /// </summary> public class UInt64State : SingletonState<ulong> { } /// <summary> /// Wrapper around string values for use in smart contract state. /// </summary> public class StringState : SingletonState<string> { } /// <summary> /// Wrapper around byte arrays for use in smart contract state. /// </summary> public class BytesState : SingletonState<byte[]> { } // ReSharper disable once IdentifierTypo public class ProtobufState<TEntity> : SingletonState<TEntity> where TEntity : IMessage, new() { } }
25.275862
97
0.631651
[ "MIT" ]
AElfProject/AElf
src/AElf.Sdk.CSharp/State/SingletonState_Aliases.cs
1,466
C#
using System.Collections.Generic; using System.Data.SqlClient; using System; namespace BandTracker { public class Band { private int _id; private string _name; public Band(string Name, int Id = 0) { _id = Id; _name = Name; } public int GetId() { return _id; } public string GetName() { return _name; } public void SetName(string newName) { _name = newName; } public static List<Band> GetAll() { List<Band> allBands = new List<Band>{}; SqlConnection conn = DB.Connection(); conn.Open(); SqlCommand cmd = new SqlCommand("SELECT * FROM bands;", conn); SqlDataReader rdr = cmd.ExecuteReader(); while(rdr.Read()) { int bandId = rdr.GetInt32(0); string bandName = rdr.GetString(1); Band newBand = new Band(bandName, bandId); allBands.Add(newBand); } if (rdr != null) { rdr.Close(); } if (conn != null) { conn.Close(); } return allBands; } public override bool Equals(System.Object otherBand) { if (!(otherBand is Band)) { return false; } else { Band newBand = (Band) otherBand; bool idEquality = this.GetId() == newBand.GetId(); bool nameEquality = this.GetName() == newBand.GetName(); return (idEquality && nameEquality); } } public void Save() { SqlConnection conn = DB.Connection(); conn.Open(); SqlCommand cmd = new SqlCommand("INSERT INTO bands (name) OUTPUT INSERTED.id VALUES (@BandName);", conn); SqlParameter nameParameter = new SqlParameter(); nameParameter.ParameterName = "@BandName"; nameParameter.Value = this.GetName(); cmd.Parameters.Add(nameParameter); SqlDataReader rdr = cmd.ExecuteReader(); while(rdr.Read()) { this._id = rdr.GetInt32(0); } if (rdr != null) { rdr.Close(); } if(conn != null) { conn.Close(); } } public static Band Find(int id) { SqlConnection conn = DB.Connection(); conn.Open(); SqlCommand cmd = new SqlCommand("SELECT * FROM bands WHERE id = @BandId;", conn); SqlParameter bandIdParameter = new SqlParameter(); bandIdParameter.ParameterName = "@BandId"; bandIdParameter.Value = id.ToString(); cmd.Parameters.Add(bandIdParameter); SqlDataReader rdr = cmd.ExecuteReader(); int foundBandId = 0; string foundBandName = null; while(rdr.Read()) { foundBandId = rdr.GetInt32(0); foundBandName = rdr.GetString(1); } Band foundBand = new Band(foundBandName, foundBandId); if (rdr != null) { rdr.Close(); } if (conn != null) { conn.Close(); } return foundBand; } public void AddVenue(Venue newVenue) { SqlConnection conn = DB.Connection(); conn.Open(); SqlCommand cmd = new SqlCommand("INSERT INTO venues_bands (venue_id, band_id) VALUES (@VenueId, @BandId);", conn); SqlParameter venueIdParameter = new SqlParameter(); venueIdParameter.ParameterName = "@VenueId"; venueIdParameter.Value = newVenue.GetId(); cmd.Parameters.Add(venueIdParameter); SqlParameter bandIdParameter = new SqlParameter(); bandIdParameter.ParameterName = "@BandId"; bandIdParameter.Value = this.GetId(); cmd.Parameters.Add(bandIdParameter); cmd.ExecuteNonQuery(); if (conn != null) { conn.Close(); } } public List<Venue> GetVenues() { SqlConnection conn = DB.Connection(); conn.Open(); SqlCommand cmd = new SqlCommand("SELECT venues.* FROM bands JOIN venues_bands ON (bands.id = venues_bands.band_id) JOIN venues ON (venues_bands.venue_id = venues.id) WHERE bands.id = @bandId",conn); SqlParameter bandIdParameter = new SqlParameter(); bandIdParameter.ParameterName= "@BandId"; bandIdParameter.Value=this.GetId(); cmd.Parameters.Add(bandIdParameter); SqlDataReader rdr = cmd.ExecuteReader(); List<Venue> venues = new List<Venue> {}; while(rdr.Read()) { int venueId = rdr.GetInt32(0); string venueName = rdr.GetString(1); Venue newVenue = new Venue(venueName, venueId); venues.Add(newVenue); } if(rdr !=null) { rdr.Close(); } if (conn != null) { conn.Close(); } return venues; } public void Delete() { SqlConnection conn = DB.Connection(); conn.Open(); SqlCommand cmd = new SqlCommand("DELETE FROM bands WHERE id = @BandId; DELETE FROM venues_bands WHERE band_id = @BandId;", conn); SqlParameter bandIdParameter = new SqlParameter(); bandIdParameter.ParameterName = "@BandId"; bandIdParameter.Value = this.GetId(); cmd.Parameters.Add(bandIdParameter); cmd.ExecuteNonQuery(); if (conn != null) { conn.Close(); } } public static void DeleteAll() { SqlConnection conn = DB.Connection(); conn.Open(); SqlCommand cmd = new SqlCommand("DELETE FROM bands;", conn); cmd.ExecuteNonQuery(); conn.Close(); } } }
23.924779
204
0.581468
[ "MIT" ]
Sherly789/BandTracker
Objects/Band.cs
5,407
C#
using System; using System.ComponentModel; using EfsTools.Attributes; using EfsTools.Utils; using Newtonsoft.Json; using EfsTools.Items.Data; namespace EfsTools.Items.Nv { [Serializable] [NvItemId(7224)] [Attributes(9)] public class C1Wcdma2100VgaGainOffsetCar1 { [ElementsCount(1)] [ElementType("int16")] [Description("")] public short Value { get; set; } } }
20.363636
46
0.622768
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Nv/C1Wcdma2100VgaGainOffsetCar1I.cs
448
C#
using System; using System.Collections; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace ModernWpf.Controls { internal class RepeaterUIElementCollection : UIElementCollection { public RepeaterUIElementCollection(UIElement visualParent, FrameworkElement logicalParent) : base(visualParent, logicalParent) { _visualChildren = new VisualCollection(visualParent); _visualParent = visualParent; _logicalParent = logicalParent; } public override int Count => _visualChildren.Count; public override bool IsSynchronized => _visualChildren.IsSynchronized; public override object SyncRoot => _visualChildren.SyncRoot; public override void CopyTo(Array array, int index) { _visualChildren.CopyTo(array, index); } public override void CopyTo(UIElement[] array, int index) { _visualChildren.CopyTo(array, index); } public override int Capacity { get => _visualChildren.Capacity; set => _visualChildren.Capacity = value; } public override UIElement this[int index] { get => _visualChildren[index] as UIElement; set { ValidateElement(value); VisualCollection vc = _visualChildren; //if setting new element into slot or assigning null, //remove previously hooked element from the logical tree if (vc[index] != value) { UIElement e = vc[index] as UIElement; if (e != null) ClearLogicalParent(e); vc[index] = value; SetLogicalParent(value); } } } public override int Add(UIElement element) { return AddInternal(element); } // Warning: this method is very dangerous because it does not prevent adding children // into collection populated by generator. This may cause crashes if used incorrectly. // Don't call this unless you are deriving a panel that is populating the collection // in cooperation with the generator internal int AddInternal(UIElement element) { ValidateElement(element); SetLogicalParent(element); int retVal = _visualChildren.Add(element); return retVal; } public override int IndexOf(UIElement element) { return _visualChildren.IndexOf(element); } public override void Remove(UIElement element) { RemoveInternal(element); } internal void RemoveInternal(UIElement element) { _visualChildren.Remove(element); ClearLogicalParent(element); } public override bool Contains(UIElement element) { return _visualChildren.Contains(element); } public override void Clear() { ClearInternal(); } // Warning: this method is very dangerous because it does not prevent adding children // into collection populated by generator. This may cause crashes if used incorrectly. // Don't call this unless you are deriving a panel that is populating the collection // in cooperation with the generator internal void ClearInternal() { VisualCollection vc = _visualChildren; int cnt = vc.Count; if (cnt > 0) { // copy children in VisualCollection so that we can clear the visual link first, // followed by the logical link Visual[] visuals = new Visual[cnt]; for (int i = 0; i < cnt; i++) { visuals[i] = vc[i]; } vc.Clear(); //disconnect from logical tree for (int i = 0; i < cnt; i++) { UIElement e = visuals[i] as UIElement; if (e != null) { ClearLogicalParent(e); } } } } public override void Insert(int index, UIElement element) { InsertInternal(index, element); } // Warning: this method is very dangerous because it does not prevent adding children // into collection populated by generator. This may cause crashes if used incorrectly. // Don't call this unless you are deriving a panel that is populating the collection // in cooperation with the generator internal void InsertInternal(int index, UIElement element) { ValidateElement(element); SetLogicalParent(element); _visualChildren.Insert(index, element); } public override void RemoveAt(int index) { VisualCollection vc = _visualChildren; //disconnect from logical tree UIElement e = vc[index] as UIElement; vc.RemoveAt(index); if (e != null) ClearLogicalParent(e); } public override void RemoveRange(int index, int count) { RemoveRangeInternal(index, count); } // Warning: this method is very dangerous because it does not prevent adding children // into collection populated by generator. This may cause crashes if used incorrectly. // Don't call this unless you are deriving a panel that is populating the collection // in cooperation with the generator internal void RemoveRangeInternal(int index, int count) { VisualCollection vc = _visualChildren; int cnt = vc.Count; if (count > (cnt - index)) { count = cnt - index; } if (count > 0) { // copy children in VisualCollection so that we can clear the visual link first, // followed by the logical link Visual[] visuals = new Visual[count]; int i = index; for (int loop = 0; loop < count; i++, loop++) { visuals[loop] = vc[i]; } vc.RemoveRange(index, count); //disconnect from logical tree for (i = 0; i < count; i++) { UIElement e = visuals[i] as UIElement; if (e != null) { ClearLogicalParent(e); } } } } // Helper function to validate element; will throw exceptions if problems are detected. private void ValidateElement(UIElement element) { if (element == null) { throw new ArgumentNullException(string.Format("Children of '{0}' cannot be null. Object derived from UIElement expected.", this.GetType())); } } public override IEnumerator GetEnumerator() { return _visualChildren.GetEnumerator(); } private readonly VisualCollection _visualChildren; private readonly UIElement _visualParent; private readonly FrameworkElement _logicalParent; } }
32.169492
156
0.54834
[ "MIT" ]
AlphaNecron/ModernWpf
ModernWpf.Controls/Repeater/RepeaterUIElementCollection.cs
7,594
C#
//----------------------------------------------------------------------- // <copyright file="TestSnapshotStoreFailureException.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- namespace Akka.Persistence.TestKit { using System; using System.Runtime.Serialization; [Serializable] public class TestSnapshotStoreFailureException : Exception { public TestSnapshotStoreFailureException() { } public TestSnapshotStoreFailureException(string message) : base(message) { } public TestSnapshotStoreFailureException(string message, Exception inner) : base(message, inner) { } protected TestSnapshotStoreFailureException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
44.636364
127
0.623218
[ "Apache-2.0" ]
Aaronontheweb/akka.net
src/core/Akka.Persistence.TestKit/SnapshotStore/TestSnapshotStoreFailureException.cs
984
C#
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. // // ███╗ ██╗ ██████╗ ████████╗██╗ ██████╗███████╗ // ████╗ ██║██╔═══██╗╚══██╔══╝██║██╔════╝██╔════╝ // ██╔██╗ ██║██║ ██║ ██║ ██║██║ █████╗ // ██║╚██╗██║██║ ██║ ██║ ██║██║ ██╔══╝ // ██║ ╚████║╚██████╔╝ ██║ ██║╚██████╗███████╗ // ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝ // ------------------------------------------------ // // This file is automatically generated. // Please do not edit these files manually. // // ------------------------------------------------ using Elastic.Transport; using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text.Json; using System.Text.Json.Serialization; #nullable restore namespace Elastic.Clients.Elasticsearch.Ilm { public sealed class IlmStopRequestParameters : RequestParameters<IlmStopRequestParameters> { [JsonIgnore] public Elastic.Clients.Elasticsearch.Time? MasterTimeout { get => Q<Elastic.Clients.Elasticsearch.Time?>("master_timeout"); set => Q("master_timeout", value); } [JsonIgnore] public Elastic.Clients.Elasticsearch.Time? Timeout { get => Q<Elastic.Clients.Elasticsearch.Time?>("timeout"); set => Q("timeout", value); } } public partial class IlmStopRequest : PlainRequestBase<IlmStopRequestParameters> { internal override ApiUrls ApiUrls => ApiUrlsLookups.IndexLifecycleManagementStop; protected override HttpMethod HttpMethod => HttpMethod.POST; protected override bool SupportsBody => false; [JsonIgnore] public Elastic.Clients.Elasticsearch.Time? MasterTimeout { get => Q<Elastic.Clients.Elasticsearch.Time?>("master_timeout"); set => Q("master_timeout", value); } [JsonIgnore] public Elastic.Clients.Elasticsearch.Time? Timeout { get => Q<Elastic.Clients.Elasticsearch.Time?>("timeout"); set => Q("timeout", value); } } public sealed partial class IlmStopRequestDescriptor : RequestDescriptorBase<IlmStopRequestDescriptor, IlmStopRequestParameters> { internal IlmStopRequestDescriptor(Action<IlmStopRequestDescriptor> configure) => configure.Invoke(this); public IlmStopRequestDescriptor() { } internal override ApiUrls ApiUrls => ApiUrlsLookups.IndexLifecycleManagementStop; protected override HttpMethod HttpMethod => HttpMethod.POST; protected override bool SupportsBody => false; public IlmStopRequestDescriptor MasterTimeout(Elastic.Clients.Elasticsearch.Time? masterTimeout) => Qs("master_timeout", masterTimeout); public IlmStopRequestDescriptor Timeout(Elastic.Clients.Elasticsearch.Time? timeout) => Qs("timeout", timeout); protected override void Serialize(Utf8JsonWriter writer, JsonSerializerOptions options, IElasticsearchClientSettings settings) { } } }
44.169231
162
0.675026
[ "Apache-2.0" ]
SimonCropp/elasticsearch-net
src/Elastic.Clients.Elasticsearch/_Generated/Api/Ilm/IlmStopRequest.g.cs
3,317
C#
using Amazon; using Amazon.S3; using Amazon.S3.Model; using Amazon.Textract; using Amazon.Textract.Model; namespace hello_textract { public class TextractHelper { private string _bucketname { get; set; } private RegionEndpoint _region { get; set; } private AmazonTextractClient _textractClient { get; set; } private AmazonS3Client _s3Client { get; set; } public TextractHelper(string bucketname, RegionEndpoint region) { _bucketname = bucketname; _region = region; _textractClient = new AmazonTextractClient(_region); _s3Client = new AmazonS3Client(_region); } /// <summary> /// ID document analysis. /// </summary> /// <param name="filename"></param> public async Task AnalyzeID(string filename) { Console.WriteLine("Start document ID analysis"); var bytes = File.ReadAllBytes(filename); AnalyzeIDRequest request = new AnalyzeIDRequest() { DocumentPages = new List<Document> { new Document { Bytes = new MemoryStream(bytes) } } }; var getDetectionResponse3 = await _textractClient.AnalyzeIDAsync(request); foreach (var doc in getDetectionResponse3.IdentityDocuments) { foreach (var field in doc.IdentityDocumentFields) { Console.WriteLine($"{field.Type.Text}: {field.ValueDetection.Text}"); } } } /// <summary> /// Analyze document for text detection. /// </summary> /// <param name="filename">path to local file</param> public async Task AnalyzeText(string filename) { // Upload document to S3. var docLocation = await UploadFileToBucket(filename); // Start a document text detection job. Console.WriteLine("Starting document text detection job"); var startJobRequest = new StartDocumentTextDetectionRequest { DocumentLocation = docLocation }; var startJobResponse = await _textractClient.StartDocumentTextDetectionAsync(startJobRequest); Console.WriteLine($"Job ID: {startJobResponse.JobId}"); // Wait for the job to complete. Console.Write("Waiting for job completion"); var getResultsRequest = new GetDocumentTextDetectionRequest { JobId = startJobResponse.JobId }; GetDocumentTextDetectionResponse getResultsResponse = null!; while ((getResultsResponse = await _textractClient.GetDocumentTextDetectionAsync(getResultsRequest)).JobStatus==JobStatus.IN_PROGRESS) { Console.Write("."); Thread.Sleep(1000); } Console.WriteLine(); // Display detected text blocks. if (getResultsResponse.JobStatus == JobStatus.SUCCEEDED) { Console.WriteLine("Detected text blocks:"); do { foreach (var block in getResultsResponse.Blocks) { Console.WriteLine($"Type {block.BlockType}, Text: {block.Text} ({block.Confidence:N0}%)"); } if (string.IsNullOrEmpty(getResultsResponse.NextToken)) { break; } getResultsRequest.NextToken = getResultsResponse.NextToken; getResultsResponse = await _textractClient.GetDocumentTextDetectionAsync(getResultsRequest); } while (!string.IsNullOrEmpty(getResultsResponse.NextToken)); } else { Console.WriteLine($"ERROR: job failed - {getResultsResponse.StatusMessage}"); } } /// <summary> /// Analyze document for table data. /// </summary> /// <param name="filename">path to local file</param> public async Task AnalyzeTable(string filename) { // Upload document to S3. var docLocation = await UploadFileToBucket(filename); // Start a document analysis job. Console.WriteLine("Starting document analysis job"); var startJobRequest = new StartDocumentAnalysisRequest { DocumentLocation = docLocation, FeatureTypes = { "TABLES" } }; var startJobResponse = await _textractClient.StartDocumentAnalysisAsync(startJobRequest); Console.WriteLine($"Job ID: {startJobResponse.JobId}"); // Wait for the job to complete. Console.Write("Waiting for job completion"); var getResultsRequest = new GetDocumentAnalysisRequest { JobId = startJobResponse.JobId }; GetDocumentAnalysisResponse getResultsResponse = null!; while ((getResultsResponse = await _textractClient.GetDocumentAnalysisAsync(getResultsRequest)).JobStatus == JobStatus.IN_PROGRESS) { Console.Write("."); Thread.Sleep(1000); } Console.WriteLine(); // Display detected tables. if (getResultsResponse.JobStatus == JobStatus.SUCCEEDED) { do { var tables = from table in getResultsResponse.Blocks where table.BlockType == BlockType.TABLE select table; var cells = from cell in getResultsResponse.Blocks where cell.BlockType == BlockType.CELL select cell; Console.WriteLine($"Found {tables.Count()} tables and {cells.Count()} cells"); foreach(var cell in cells) { if (cell.ColumnIndex==1) { Console.WriteLine(); Console.Write("| "); } foreach(var rel in cell.Relationships) { foreach (var id in rel.Ids) { var cellText = (from text in getResultsResponse.Blocks where text.Id == id select text.Text).FirstOrDefault(); Console.Write($"{cellText} "); } } Console.Write("| "); } if (string.IsNullOrEmpty(getResultsResponse.NextToken)) { break; } getResultsRequest.NextToken = getResultsResponse.NextToken; getResultsResponse = await _textractClient.GetDocumentAnalysisAsync(getResultsRequest); } while (!string.IsNullOrEmpty(getResultsResponse.NextToken)); } else { Console.WriteLine($"ERROR: job failed - {getResultsResponse.StatusMessage}"); } } /// <summary> /// Upload local file to S3 bucket. /// </summary> /// <param name="filename"></param> /// <returns>DocumentLocation object, suitable for inclusion in Textract start job requests.</returns> private async Task<DocumentLocation> UploadFileToBucket(string filename) { Console.WriteLine($"Upload {filename} to {_bucketname} bucket"); var putRequest = new PutObjectRequest { BucketName = _bucketname, FilePath = filename, Key = Path.GetFileName(filename) }; await _s3Client.PutObjectAsync(putRequest); return new DocumentLocation { S3Object = new Amazon.Textract.Model.S3Object { Bucket = _bucketname, Name = putRequest.Key } }; } } }
39.258706
146
0.557344
[ "MIT" ]
davidpallmann/hello-textract
TextractHelper.cs
7,893
C#
using System; using System.Collections.Generic; using System.Linq; using DvornikovTask.Math; namespace DvornikovTask { public class DvornikovSystem { public uint MobilityW { get; private set; } public uint CountM { get; private set; } public uint CountN { get; private set; } public uint ComplexityTau { get; private set; } public DvornikovSystem(uint mobilityW, uint countM, uint countN, uint complexityTau) { CheckArgs(mobilityW, countM, countN, complexityTau); MobilityW = mobilityW; CountM = countM; CountN = countN; ComplexityTau = complexityTau; } public static void CheckArgs(uint mobilityW, uint countM, uint countN, uint complexityTau) { if (countM > 4) { throw new ArgumentOutOfRangeException(); } if (countN == 0) { throw new ArgumentOutOfRangeException(); } if (complexityTau == 0) { throw new ArgumentOutOfRangeException(); } } public DvornikovSolution Solve() { var result = new DvornikovSolution(this); var decompositions = new NumberDecomposition(CountN - 1, ComplexityTau - 1); var rangeTau = Enumerable.Range(1, (int) ComplexityTau).Reverse().Select(i => (uint) i).ToList(); foreach (var decomposition in decompositions) { decomposition.Insert(0, 1); var tmp = Utils.MultiSum(decomposition, rangeTau); var tmpDecompositions = new NumberDecomposition(tmp, 5 - CountM); var resultDecomposition = decomposition.Skip(1).Reverse().ToArray(); var key = new SystemSolution((uint) resultDecomposition.Length, resultDecomposition, Enumerable.Range(1, (int) ComplexityTau - 1).Select(i => (uint) i).ToArray()); foreach (var tmpDecomposition in tmpDecompositions) { if (!CheckSum(tmpDecomposition)) { continue; } var value = new SystemSolution((uint) tmpDecomposition.Count, tmpDecomposition.ToArray(), Enumerable.Range((int)CountM + 1, (int) (5 - CountM)).Reverse().Select(i => (uint) i).ToArray()); if (!result.Solutions.ContainsKey(key)) { result.Solutions.Add(key, new List<SystemSolution>()); } result.Solutions[key].Add(value); } } return result; } private bool CheckSum(List<uint> tmpDecomposition) { var sum = 0; var m = (int) CountM; for (var i = m + 1; i < 6; i++) { sum += (i - m) * (int) tmpDecomposition[i - m - 1]; } return MobilityW == ((6 - CountM) * CountN - sum); } } }
32.677083
121
0.517055
[ "MIT" ]
alldevic/NbiEduPractice
DvornikovTask/DvornikovSystem.cs
3,137
C#
// // IN Copyright (c) %s, Microsoft Corporation // IN // IN SPDX-License-Identifier: Apache-2.0 * // IN // IN All rights reserved. This program and the accompanying materials are // IN made available under the terms of the Apache License, Version 2.0 // IN which accompanies this distribution, and is available at // IN http://www.apache.org/licenses/LICENSE-2.0 // IN // IN Permission to use, copy, modify, and/or distribute this software for // IN any purpose with or without fee is hereby granted, provided that the // IN above copyright notice and this permission notice appear in all // IN copies. // IN // IN THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL // IN WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED // IN WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE // IN AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL // IN DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR // IN PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER // IN TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // IN PERFORMANCE OF THIS SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices.WindowsRuntime; using BridgeRT; using System.Diagnostics; using System.Threading; namespace AdapterLib { public sealed class Adapter : IAdapter { private const uint ERROR_SUCCESS = 0; private const uint ERROR_INVALID_HANDLE = 6; private const uint ERROR_INVALID_DATA = 13; private const uint ERROR_INVALID_PARAMETER = 87; private const uint ERROR_NOT_SUPPORTED = 50; public string Vendor { get; } public string AdapterName { get; } public string Version { get; } public string ExposedAdapterPrefix { get; } public string ExposedApplicationName { get; } public Guid ExposedApplicationGuid { get; } public IList<IAdapterSignal> Signals { get; } // A map of signal handle (object's hash code) and related listener entry private struct SIGNAL_LISTENER_ENTRY { // The signal object internal IAdapterSignal Signal; // The listener object internal IAdapterSignalListener Listener; // // The listener context that will be // passed to the signal handler // internal object Context; } private Dictionary<int, IList<SIGNAL_LISTENER_ENTRY>> m_signalListeners; // ZigBee command used to get new device notification, reportable attributes internal readonly DeviceAnnce m_deviceAnnonce = DeviceAnnce.Instance; internal readonly ZclReportAttributes m_reportAttributes = ZclReportAttributes.Instance; internal readonly ZclServerCommandHandler m_zclServerCommandHandler = ZclServerCommandHandler.Instance; public Adapter() { Windows.ApplicationModel.Package package = Windows.ApplicationModel.Package.Current; Windows.ApplicationModel.PackageId packageId = package.Id; Windows.ApplicationModel.PackageVersion versionFromPkg = packageId.Version; this.Vendor = AdapterHelper.ADAPTER_VENDOR; this.AdapterName = AdapterHelper.ADAPTER_NAME; // the adapter prefix must be something like "com.mycompany" (only alpha num and dots) // it is used by the Device System Bridge as root string for all services and interfaces it exposes this.ExposedAdapterPrefix = AdapterHelper.ADAPTER_DOMAIN + "." + this.Vendor.ToLower(); this.ExposedApplicationGuid = Guid.Parse(AdapterHelper.ADAPTER_APPLICATION_GUID); if (null != package && null != packageId) { this.ExposedApplicationName = packageId.Name; this.Version = versionFromPkg.Major.ToString() + "." + versionFromPkg.Minor.ToString() + "." + versionFromPkg.Revision.ToString() + "." + versionFromPkg.Build.ToString(); } else { this.ExposedApplicationName = AdapterHelper.ADAPTER_DEFAULT_APPLICATION_NAME; this.Version = AdapterHelper.ADAPTER_DEFAULT_VERSION; } try { this.Signals = new List<IAdapterSignal>(); this.m_signalListeners = new Dictionary<int, IList<SIGNAL_LISTENER_ENTRY>>(); } catch (OutOfMemoryException ex) { Debug.WriteLine(ex); throw; } } public uint SetConfiguration([ReadOnlyArray] byte[] ConfigurationData) { // TODO: add configuration, e.g.: VID/PID of ZigBee dongle return ERROR_NOT_SUPPORTED; } public uint GetConfiguration(out byte[] ConfigurationDataPtr) { // TODO: add configuration ConfigurationDataPtr = null; return ERROR_NOT_SUPPORTED; } public uint Initialize() { try { m_xBeeModule.Initialize(out m_adapter); } catch (Exception ex) { return (uint)ex.HResult; } // discover ZigBee device CreateSignals(); StartDeviceDiscovery(); // add new device and change of attribute value notifications m_deviceAnnonce.OnReception += AddDeviceInDeviceList; m_reportAttributes.OnReception += ZclReportAttributeReception; m_xBeeModule.AddXZibBeeNotification(m_deviceAnnonce); m_xBeeModule.AddXZibBeeNotification(m_reportAttributes); m_xBeeModule.AddXZibBeeNotification(m_zclServerCommandHandler); return ERROR_SUCCESS; } public uint Shutdown() { m_xBeeModule.Shutdown(); return ERROR_SUCCESS; } public uint EnumDevices( ENUM_DEVICES_OPTIONS Options, out IList<IAdapterDevice> DeviceListPtr, out IAdapterIoRequest RequestPtr) { RequestPtr = null; DeviceListPtr = new List<IAdapterDevice>(); // Add all end points in all ZigBee devices to the list // if device list not locked // note that: // - an endpoint is a device for BridgeRT // - endpoints will be notified as ZigBee devices arrive if (Monitor.TryEnter(m_deviceMap)) { try { foreach (var zigBeeDeviceItem in m_deviceMap) { foreach (var endPointItem in zigBeeDeviceItem.Value.EndPointList) { DeviceListPtr.Add(endPointItem.Value); } } } finally { // use try/finally to ensure m_deviceList is unlocked in every case Monitor.Exit(m_deviceMap); } } return ERROR_SUCCESS; } public uint GetProperty( IAdapterProperty Property, out IAdapterIoRequest RequestPtr) { RequestPtr = null; // sanity check if (Property == null) { return ERROR_INVALID_PARAMETER; } // cast back IAdapterProperty to ZclCluster ZclCluster cluster = (ZclCluster)Property; // read all attributes for the attribute foreach (var item in cluster.InternalAttributeList) { var attribute = item.Value; object value; if(!attribute.Read(out value)) { // give up at 1st read error return (uint) ZclHelper.ZigBeeStatusToHResult(attribute.Status); } } return ERROR_SUCCESS; } public uint SetProperty( IAdapterProperty Property, out IAdapterIoRequest RequestPtr) { RequestPtr = null; // sanity check if (Property == null) { return ERROR_INVALID_PARAMETER; } // cast back IAdapterProperty to ZclCluster ZclCluster cluster = (ZclCluster)Property; // write new value for all attributes // note that it is assumed that BridgeRT has set the new value // for each attribute foreach (var item in cluster.InternalAttributeList) { var attribute = item.Value; if (attribute.Write(attribute.Value.Data)) { // give up at 1st write error return (uint)ZclHelper.ZigBeeStatusToHResult(attribute.Status); } } return ERROR_SUCCESS; } public uint GetPropertyValue( IAdapterProperty Property, string AttributeName, out IAdapterValue ValuePtr, out IAdapterIoRequest RequestPtr) { ValuePtr = null; RequestPtr = null; // sanity check if (Property == null) { return ERROR_INVALID_PARAMETER; } // cast back IAdapterProperty to ZclCluster ZclCluster cluster = (ZclCluster) Property; // look for the attribute foreach(var item in cluster.InternalAttributeList) { var attribute = item.Value; if (attribute.Value.Name == AttributeName) { object value; if(attribute.Read(out value)) { ValuePtr = attribute.Value; return ERROR_SUCCESS; } else { return (uint)ZclHelper.ZigBeeStatusToHResult(attribute.Status); } } } return ERROR_NOT_SUPPORTED; } public uint SetPropertyValue( IAdapterProperty Property, IAdapterValue Value, out IAdapterIoRequest RequestPtr) { RequestPtr = null; // sanity check if (Property == null) { return ERROR_INVALID_PARAMETER; } // cast back IAdapterProperty to ZclCluster ZclCluster cluster = (ZclCluster)Property; // look for the attribute and write new data foreach (var item in cluster.InternalAttributeList) { var attribute = item.Value; if (attribute.Value.Name == Value.Name) { if (attribute.Write(Value.Data)) { return ERROR_SUCCESS; } else { return (uint)ZclHelper.ZigBeeStatusToHResult(attribute.Status); } } } return ERROR_NOT_SUPPORTED; } public uint CallMethod( IAdapterMethod Method, out IAdapterIoRequest RequestPtr) { RequestPtr = null; // sanity check if (Method == null) { return ERROR_INVALID_PARAMETER; } // IAdapterMethod is either a ZclCommand or a ManagementLeave command, // cast back IAdapterMethod to ZclCommand first then to ManagementLeave if cast failed try { var command = (ZclCommand) Method; command.Send(); return (uint)command.HResult; } catch (InvalidCastException e) { // send the leave command and remove devices (hence all end points of the ZigBee device) // // Note that ManagementLeave is THE unique ZdoCommand exposed to AllJoyn // var command = (ManagementLeave)Method; command.Send(); if (command.ZigBeeStatus != ZdoHelper.ZDO_NOT_SUPPORTED) { // async device removal Task.Run(() => RemoveDevice(command.Device)); } return (uint)command.HResult; } } public uint RegisterSignalListener( IAdapterSignal Signal, IAdapterSignalListener Listener, object ListenerContext) { // sanity check if (Signal == null || Listener == null) { return ERROR_INVALID_PARAMETER; } int signalHashCode = Signal.GetHashCode(); SIGNAL_LISTENER_ENTRY newEntry; newEntry.Signal = Signal; newEntry.Listener = Listener; newEntry.Context = ListenerContext; lock (m_signalListeners) { if (m_signalListeners.ContainsKey(signalHashCode)) { m_signalListeners[signalHashCode].Add(newEntry); } else { var newEntryList = new List<SIGNAL_LISTENER_ENTRY> { newEntry }; m_signalListeners.Add(signalHashCode, newEntryList); } } return ERROR_SUCCESS; } public uint UnregisterSignalListener( IAdapterSignal Signal, IAdapterSignalListener Listener) { return ERROR_SUCCESS; } private uint CreateSignals() { // create device arrival signal and add it to list AdapterSignal deviceArrival = new AdapterSignal(Constants.DEVICE_ARRIVAL_SIGNAL); deviceArrival.AddParam(Constants.DEVICE_ARRIVAL__DEVICE_HANDLE); Signals.Add(deviceArrival); // create device removal signal and add it to list AdapterSignal deviceRemoval = new AdapterSignal(Constants.DEVICE_REMOVAL_SIGNAL); deviceRemoval.AddParam(Constants.DEVICE_REMOVAL__DEVICE_HANDLE); Signals.Add(deviceRemoval); return ERROR_SUCCESS; } internal void NotifyBridgeRT(ZigBeeEndPoint endPoint, string signalName, string paramName) { // find device arrival signal in list var deviceArrival = Signals.OfType<AdapterSignal>().FirstOrDefault(s => s.Name == signalName); if (deviceArrival == null) { // no device arrival signal return; } // set parameter value var param = deviceArrival.Params.FirstOrDefault(p => p.Name == paramName); if(param == null) { // signal doesn't have the expected parameter return; } param.Data = endPoint; NotifySignalListeners(deviceArrival); } internal void NotifySignalListeners(IAdapterSignal signal) { int signalHashCode = signal.GetHashCode(); IList<SIGNAL_LISTENER_ENTRY> listenerList = null; lock (m_signalListeners) { if(m_signalListeners.ContainsKey(signalHashCode)) { // make a local copy of the listener list listenerList = m_signalListeners[signalHashCode].ToArray(); } else { // can't do anything return; } } // call out event handlers out of the lock to avoid // deadlock risk foreach (SIGNAL_LISTENER_ENTRY entry in listenerList) { IAdapterSignalListener listener = entry.Listener; object listenerContext = entry.Context; listener.AdapterSignalHandler(signal, listenerContext); } } private void RemoveDevice(ZigBeeDevice zigBeeDevice) { // remove device from list (it will be garbaged collect later) lock (m_deviceMap) { m_deviceMap.Remove(zigBeeDevice.MacAddress); } // remove server commands that belong to that device m_zclServerCommandHandler.RemoveCommands(zigBeeDevice); // notify AllJoyn/BridgeRT // // note that a ZigBee endpoint is a exposed as a device on AllJoyn // => BridgeRT should be notified of removal of each enpoint of the removed ZigBee device foreach (var endPoint in zigBeeDevice.EndPointList) { NotifyBridgeRT(endPoint.Value, Constants.DEVICE_REMOVAL_SIGNAL, Constants.DEVICE_REMOVAL__DEVICE_HANDLE); } } private XBeeModule m_xBeeModule = new XBeeModule(); internal XBeeModule XBeeModule { get { return m_xBeeModule; } } private ZigBeeDevice m_adapter = null; private ZclClusterFactory m_zclClusterFactory = ZclClusterFactory.Instance; private ZigBeeProfileLibrary m_zigBeeProfileLibrary = ZigBeeProfileLibrary.Instance; private readonly Dictionary<UInt64, ZigBeeDevice> m_deviceMap = new Dictionary<UInt64, ZigBeeDevice>(); internal Dictionary<UInt64, ZigBeeDevice> DeviceList { get { return m_deviceMap; } } private void StartDeviceDiscovery() { // async discovery process Task.Run(() => DiscoverDevices()); } private void DiscoverDevices() { ManagementLQI lqiCommand = new ManagementLQI(); // lock device list and clear it lock(m_deviceMap) { m_deviceMap.Clear(); } // get direct neighbor and add them in list // // note: for now, only deal with direct neighbor (no hop) // going through ZigBee network nodes and graph will come later lqiCommand.GetNeighbors(m_xBeeModule, m_adapter); foreach (var deviceDescriptor in lqiCommand.NeighborList) { // async add device in list so device details can be queried in parallel and // one detail discovery won't block the others Task.Run(() => { AddDeviceInDeviceList(deviceDescriptor.networkAddress, deviceDescriptor.macAddress, deviceDescriptor.isEndDevice); }); } } private void AddDeviceInDeviceList(UInt16 networkAddress, UInt64 macAddress, bool isEndDevice) { bool deviceFound = false; bool addDeviceInList = false; ZigBeeDevice device = null; Logger.TraceDevice(networkAddress, macAddress); lock (m_deviceMap) { deviceFound = m_deviceMap.TryGetValue(macAddress, out device); } if(!deviceFound) { // the device isn't in the list yet device = new ZigBeeDevice(networkAddress, macAddress, isEndDevice); // get end points and supported clusters ActiveEndPoints activeEndPointsCommand = new ActiveEndPoints(); activeEndPointsCommand.GetEndPoints(m_xBeeModule, device); foreach (var endPointId in activeEndPointsCommand.EndPointList) { SimpleDescriptor descriptor = new SimpleDescriptor(); descriptor.GetDescriptor(m_xBeeModule, device, endPointId); Logger.TraceDeviceDetailed(device.MacAddress, endPointId, descriptor); foreach (var clusterId in descriptor.InClusterList) { if (m_zclClusterFactory.IsClusterSupported(clusterId) && device.AddClusterToEndPoint(true, endPointId, descriptor.ProfileId, descriptor.DeviceId, clusterId, this)) { // only add device in list if at least 1 cluster is supported addDeviceInList = true; } } foreach (var clusterId in descriptor.OutClusterList) { if (m_zclClusterFactory.IsClusterSupported(clusterId) && device.AddClusterToEndPoint(false, endPointId, descriptor.ProfileId, descriptor.DeviceId, clusterId, this)) { // only add device in list if at least 1 cluster is supported addDeviceInList = true; } } } } else { // the device is already in list so just refresh its network address. // note that mac address will never change but network address can, e.g.: if end device connects to another router device.NetworkAddress = networkAddress; } // add device in list if necessary if (addDeviceInList) { lock (m_deviceMap) { // add device in list if it has not been added between beginning of this routine and now ZigBeeDevice tempDevice = null; if(!m_deviceMap.TryGetValue(device.MacAddress, out tempDevice)) { m_deviceMap.Add(device.MacAddress, device); } else { // device has been added => update network address of already existing device // give up with device that has been created and use the already existing device instead tempDevice.NetworkAddress = device.NetworkAddress; device = tempDevice; } } } // notify devices to bridgeRT // note end points are devices as far as BridgeRT is concerned foreach (var endpoint in device.EndPointList) { NotifyBridgeRT(endpoint.Value, Constants.DEVICE_ARRIVAL_SIGNAL, Constants.DEVICE_ARRIVAL__DEVICE_HANDLE); } } private void ZclReportAttributeReception(ZclReportAttributes.SOURCE_INFO deviceInfo, UInt16 attributeId, object newValue) { ZigBeeDevice device = null; ZigBeeEndPoint endPoint = null; ZclCluster cluster = null; ZclAttribute attribute = null; // look for corresponding ZigBee device lock (m_deviceMap) { if (!m_deviceMap.TryGetValue(deviceInfo.macAddress, out device)) { // unknown device => do nothing return; } } // look for corresponding end point if (!device.EndPointList.TryGetValue(deviceInfo.endpointId, out endPoint)) { // unknown end point => do nothing return; } // look for corresponding cluster cluster = endPoint.GetCluster(deviceInfo.clusterId); if (cluster == null) { // unknown cluster => do nothing return; } // look for the corresponding attribute if (cluster.InternalAttributeList.TryGetValue(attributeId, out attribute)) { // unknown attribute => do nothing return; } // update value attribute.Value.Data = newValue; // signal value of attribute has changed SignalChangeOfAttributeValue(endPoint, cluster, attribute); } internal void SignalChangeOfAttributeValue(ZigBeeEndPoint endPoint, ZclCluster cluster, ZclAttribute attribute) { // find change of value signal of that end point (end point == bridgeRT device) var covSignal = endPoint.Signals.OfType<AdapterSignal>().FirstOrDefault(s => s.Name == Constants.CHANGE_OF_VALUE_SIGNAL); if (covSignal == null) { // no change of value signal return; } // set property and attribute param of COV signal // note that // - ZCL cluster correspond to BridgeRT property // - ZCL attribute correspond to BridgeRT attribute var param = covSignal.Params.FirstOrDefault(p => p.Name == Constants.COV__PROPERTY_HANDLE); if (param == null) { // signal doesn't have the expected parameter return; } param.Data = cluster; param = covSignal.Params.FirstOrDefault(p => p.Name == Constants.COV__ATTRIBUTE_HANDLE); if (param == null) { // signal doesn't have the expected parameter return; } param.Data = attribute; // signal change of value to BridgeRT NotifySignalListeners(covSignal); } public UInt64 MacAddress { get { return m_adapter.MacAddress; } } } }
36.083102
151
0.550937
[ "Apache-2.0" ]
alljoyn/dsb
Samples/ZigBeeAdapter/AdapterLib/ZigBeeAdapter.cs
26,054
C#
using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; using System; using TogglerService.ViewModels; namespace TogglerService.ViewModelSchemaFilters { public class ToggleVMSchemaFilter : ISchemaFilter { public void Apply(Schema model, SchemaFilterContext context) { var toggle = new ToggleVM() { Id = "isButtonBlue", Value = true, Created = DateTime.UtcNow, Modified = DateTime.UtcNow }; model.Default = toggle; model.Example = toggle; } } }
25.16
68
0.591415
[ "MIT" ]
pherbel/togglersample
src/TogglerService/ViewModelSchemaFilters/ToggleVMSchemaFilter.cs
629
C#
// // Configuration.cs // // Author: // Matt Ward <matt.ward@microsoft.com> // // Copyright (c) 2019 Microsoft // // 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; namespace MonoDevelop.PackageManagement.PowerShell.EnvDTE { public class Configuration : MarshalByRefObject, global::EnvDTE.Configuration { public Configuration (Project project) { Project = project; var propertyFactory = new ConfigurationPropertyFactory (this); Properties = new Properties (propertyFactory); } internal Project Project { get; } public global::EnvDTE.Properties Properties { get; private set; } } }
35.869565
80
0.753333
[ "Apache-2.0", "MIT" ]
berlamont/monodevelop-nuget-extensions
src/MonoDevelop.PackageManagement.PowerShell.ConsoleHost.Core/MonoDevelop.PackageManagement.PowerShell.EnvDTE/Configuration.cs
1,652
C#
namespace Heimdall.Infrastructure.Repository.Interfaces { public interface IBaseService<TEntity, TId> : IDisposable where TEntity : class { Task<TEntity> InsertAsync(TEntity entity); Task<TEntity> UpdateAsync(TEntity entity); Task<TEntity> GetByIdAsync(TId id); Task DeleteAsync(TEntity entity); Task<List<TEntity>> GetAllAsync(); } }
35.090909
83
0.694301
[ "MIT" ]
marcosmariano/heimdall-template
working/templates/heimdall-clean-arch-template-api/src/Heimdall.Infrastructure/Repository/Interfaces/IBaseService.cs
386
C#
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Basil.User.IdentityServer; using AspectCore.Extensions.DependencyInjection; using AspectCore.Injector; using Basil.Util.Log; namespace Basil.User.Service { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath); if (env.IsDevelopment()) { builder.AddJsonFile("appsettings.json"); } else { builder.AddJsonFile("appsettings.production.json"); } this.Configuration = builder.AddEnvironmentVariables().Build(); } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddUserServer(Configuration); services.AddMvc(); //替换默认Di并初始化应用 return services.InitApplication(Configuration); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseErrorHandling(); } app.UseMvc(routes => { routes.MapRoute( name: "Default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Values", action = "Get" } ); }); app.UseUserServer(); } } }
35.462963
106
0.6047
[ "MIT" ]
Basil1991/MicroDDD
src/Sample/IdentityServer/Basil.User.Service/Startup.cs
1,937
C#
using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Unicode; using System.Threading; using System.Threading.Tasks; using Xunit; namespace ForEvolve.Testing.AspNetCore.Http { public class HttpResponseFakeTest { [Fact] public async Task Should_support_WriteAsync() { // Arrange var helper = new HttpContextHelper(); var sut = helper.HttpResponseFake; // Act await sut.WriteAsync("Some Text"); // Assert sut.BodyShouldEqual("Some Text"); } } }
21.933333
53
0.629179
[ "MIT" ]
ForEvolve/ForEvolve.Testing
test/ForEvolve.Testing.AspNetCore.Tests/Http/HttpResponseFakeTest.cs
660
C#
using System; using System.Reflection; namespace EloquentObjects.RPC.Server.Implementation { internal struct HostedEvent { public HostedEvent(EventInfo eventInfo, Delegate handler) { EventInfo = eventInfo; Handler = handler; } public EventInfo EventInfo { get; } public Delegate Handler { get; } } }
22.176471
65
0.628647
[ "MIT" ]
ni28/EloquentObjects
src/EloquentObjects/RPC/Server/Implementation/HostedEvent.cs
377
C#
using Dapper; using SFA.DAS.ApplyService.Application.Email; using SFA.DAS.ApplyService.Configuration; using SFA.DAS.ApplyService.Domain.Entities; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace SFA.DAS.ApplyService.Data { public class EmailTemplateRepository : IEmailTemplateRepository { private readonly IApplyConfig _config; public EmailTemplateRepository(IConfigurationService configurationService) { _config = configurationService.GetConfig().Result; } public async Task<EmailTemplate> GetEmailTemplate(string templateName) { using (var connection = new SqlConnection(_config.SqlConnectionString)) { if (connection.State != ConnectionState.Open) await connection.OpenAsync(); var sql = "SELECT * " + "FROM [EmailTemplates] " + "WHERE TemplateName = @templateName " + "AND Status = 'Live'"; var emailTemplates = await connection.QueryAsync<EmailTemplate>(sql, new { templateName }); return emailTemplates.FirstOrDefault(); } } } }
32
107
0.623438
[ "MIT" ]
codescene-org/das-apply-service
src/SFA.DAS.ApplyService.Data/EmailTemplateRepository.cs
1,282
C#
using System.Data; using System.Data.SqlClient; using SOLID.DIP.Solucao.Interfaces; namespace SOLID.DIP.Solucao { public class ClienteRepository : IClienteRepository { public void AdicionarCliente(Cliente cliente) { using (var cn = new SqlConnection()) { var cmd = new SqlCommand(); cn.ConnectionString = "MinhaConnectionString"; cmd.Connection = cn; cmd.CommandType = CommandType.Text; cmd.CommandText = "INSERT INTO CLIENTE (NOME, EMAIL CPF, DATACADASTRO) VALUES (@nome, @email, @cpf, @dataCad))"; cmd.Parameters.AddWithValue("nome", cliente.Nome); cmd.Parameters.AddWithValue("email", cliente.Email); cmd.Parameters.AddWithValue("cpf", cliente.Cpf); cmd.Parameters.AddWithValue("dataCad", cliente.DataCadastro); cn.Open(); cmd.ExecuteNonQuery(); } } } }
31.5625
128
0.576238
[ "MIT" ]
Bpirett/FundamentosArquitetura
Exercicios-SOLID/SOLID/5 - DIP/DIP.Solucao/ClienteRepository.cs
1,010
C#
using System; using LumiSoft.Net; namespace LumiSoft.Net.FTP.Server { /// <summary> /// Provides data for the AuthUser event for FTP_Server. /// </summary> public class AuthUser_EventArgs { private FTP_Session m_pSession = null; private string m_UserName = ""; private string m_PasswData = ""; private string m_Data = ""; private AuthType m_AuthType; private bool m_Validated = true; /// <summary> /// Default constructor. /// </summary> /// <param name="session">Reference to pop3 session.</param> /// <param name="userName">Username.</param> /// <param name="passwData">Password data.</param> /// <param name="data">Authentication specific data(as tag).</param> /// <param name="authType">Authentication type.</param> public AuthUser_EventArgs(FTP_Session session,string userName,string passwData,string data,AuthType authType) { m_pSession = session; m_UserName = userName; m_PasswData = passwData; m_Data = data; m_AuthType = authType; } #region Properties Implementation /// <summary> /// Gets reference to pop3 session. /// </summary> public FTP_Session Session { get{ return m_pSession; } } /// <summary> /// User name. /// </summary> public string UserName { get{ return m_UserName; } } /// <summary> /// Password data. eg. for AUTH=PLAIN it's password and for AUTH=APOP it's md5HexHash. /// </summary> public string PasswData { get{ return m_PasswData; } } /// <summary> /// Authentication specific data(as tag). /// </summary> public string AuthData { get{ return m_Data; } } /// <summary> /// Authentication type. /// </summary> public AuthType AuthType { get{ return m_AuthType; } } /// <summary> /// Gets or sets if user is valid. /// </summary> public bool Validated { get{ return m_Validated; } set{ m_Validated = value; } } #endregion } }
22.538462
112
0.609946
[ "BSD-3-Clause" ]
Klaudit/inbox2_desktop
ThirdParty/Src/Lumisoft.Net/FTP/Server/AuthUser_EventArgs.cs
2,051
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PicSim { [Flags] enum Operation { ADDWF = 0x0700, ANDWF = 0x0500, CLRF = 0x0180, CLRW = 0x0100, COMF = 0x0900, DECF = 0x0300, DECFSZ = 0x0B00, INCF = 0x0A00, INCFSZ = 0x0F00, IORWF = 0x0400, MOVF = 0x0800, MOVWF = 0x0080, NOP = 0x0000, RLF = 0x0D00, RRF = 0x0C00, SUBWF = 0x0200, SWAPF = 0x0E00, XORWF = 0x0600, BCF = 0x1000, BSF = 0x1400, BTFSC = 0x1800, BTFSS = 0x1C00, ADDLW = 0x3E00, ANDLW = 0x3900, CALL = 0x2000, CLRWDT = 0x0064, GOTO = 0x2800, IORLW = 0x3800, MOVLW = 0x3000, RETFIE = 0x0009, RETLW = 0x3400, RETURN = 0x0008, SLEEP = 0x0063, SUBLW = 0x3C00, XORLW = 0x3A00, } }
20.042553
33
0.530786
[ "MIT" ]
StefanStegmueller/PicSim
PicSim/Operation.cs
944
C#
using Autofac; using Maple.Core.Configuration; namespace Maple.Core.Infrastructure.DependencyManagement { /// <summary> /// 依赖注册接口 /// </summary> public interface IDependencyRegistrar { /// <summary> /// 执行类型注册 /// </summary> /// <param name="builder">Container builder</param> /// <param name="typeFinder">Type finder</param> /// <param name="config">Config</param> void Register(ContainerBuilder builder, ITypeFinder typeFinder, MapleConfig config); /// <summary> /// 获取注册顺序 /// </summary> int Order { get; } } }
26.16
93
0.561162
[ "BSD-3-Clause" ]
fengqinhua/Maple
src/Maple.Core/Infrastructure/DependencyManagement/IDependencyRegistrar.cs
692
C#
using BBI.Core.Utility.FixedPoint; using BBI.Game.Data; using System.Linq; namespace Subsystem.Wrappers { public class UnitHangarAttributesWrapper : UnitHangarAttributes { public UnitHangarAttributesWrapper(UnitHangarAttributes other) { HangarBays = other.HangarBays.ToArray(); UnitDockingTriggers = other.UnitDockingTriggers; HangarDockingTriggers = other.HangarDockingTriggers; BoneResetTriggers = other.BoneResetTriggers; AlignmentTime = other.AlignmentTime; ApproachTime = other.ApproachTime; } public HangarBay[] HangarBays { get; set; } public UnitDockingTrigger[] UnitDockingTriggers { get; set; } public HangarDockingTrigger[] HangarDockingTriggers { get; set; } public HangarDockingBoneResetTrigger[] BoneResetTriggers { get; set; } public Fixed64 AlignmentTime { get; set; } public Fixed64 ApproachTime { get; set; } } }
31.09375
78
0.680402
[ "MIT" ]
Majiir/Subsystem
Subsystem/Wrappers/UnitHangarAttributesWrapper.cs
997
C#
using Patchwork; using System.Collections.Generic; using UnityEngine; using Game; using Game.GameData; using Game.UI; using Onyx; namespace PoE2Mods { [ModifiesType("Game.Player")] class mod_Player : Player { [NewMember] bool ConfigHasBeenInit; [NewMember] bool UseMod; /// <summary> /// Modification: Updates the cursor to show player that walkable areas covered by fog are /// still valid navigation targets. /// </summary> [ModifiesMember("UpdateCursor")] public void mod_UpdateCursor() { if (!ConfigHasBeenInit) { UseMod = UserConfig.GetValueAsBool("ShipMechanics", "clickThroughFog"); ConfigHasBeenInit = true; } if (GameCursor.CurrentMode == GameCursor.InputMode.Empowering) { GameCursor.UiCursor = GameCursor.CursorType.Empower; return; } if (Player.IsCasting() && this.CastingAbility != null) { if (!this.CastingAbility.ReadyForUI) { this.CancelModes(true); } if (this.CastingAbility != null && !this.CastingAbility.IsValidTarget(GameCursor.CharacterUnderCursor)) { GameCursor.DesiredCursor = GameCursor.CursorType.NoWalk; return; } } if (InGameUIManager.MouseOverUI) { GameCursor.DesiredCursor = GameCursor.CursorType.Normal; if (Player.IsCastingOrRetargeting()) { if (this.IsCastingAutoAttack) { GameCursor.DesiredCursor = this.GetAttackCursor(); } else { GameCursor.DesiredCursor = Player.GetCursorForCastingStatus(this.GetCanCastCurrentAbility()); } } return; } if (this.m_isSelecting) { GameCursor.DesiredCursor = GameCursor.CursorType.Normal; } else if (this.IsInForceAttackMode) { if (GameCursor.CharacterUnderCursor != null) { Health component = GameCursor.CharacterUnderCursor.GetComponent<Health>(); if (component == null || !component.IsTargetableByCursor() || SingletonBehavior<PartyManager>.Instance.IsSelectedPartyMember(GameCursor.CharacterUnderCursor)) { GameCursor.DesiredCursor = GameCursor.CursorType.NoWalk; } else { GameCursor.DesiredCursor = this.GetAttackCursor(); } } else { GameCursor.DesiredCursor = this.GetAttackCursor(); } } else if (Player.IsCastingOrRetargeting()) { if (this.IsCastingAutoAttack) { GameCursor.DesiredCursor = this.GetAttackCursor(); } else { GameCursor.DesiredCursor = Player.GetCursorForCastingStatus(this.GetCanCastCurrentAbility()); } } else if (this.RotatingFormation) { GameCursor.DesiredCursor = GameCursor.CursorType.RotateFormation; } else if (Player.MouseFollowActive) { Vector3 position = base.transform.position; List<GameObject> selectedPartyMemberGameObjects = SingletonBehavior<PartyManager>.Instance.GetSelectedPartyMemberGameObjects(); if (selectedPartyMemberGameObjects.Count > 0) { position = SingletonBehavior<PartyManager>.Instance.GetSelectedPartyCenter(); } Camera main = Camera.main; Vector2 vector = main.WorldToScreenPoint(GameInput.WorldMousePosition) - main.WorldToScreenPoint(position); int num = Mathf.CeilToInt((Mathf.Atan2(vector.y, vector.x) - 0.196349546f) / 0.3926991f); GameCursor.DesiredCursor = GameCursor.CursorType.ShipMove_N + (-num + 16 + 4) % 16; } else { GameObject objectUnderCursor = GameCursor.ObjectUnderCursor; if (objectUnderCursor) { Usable component2 = objectUnderCursor.GetComponent<Usable>(); WorldMapUsable component3 = objectUnderCursor.GetComponent<WorldMapUsable>(); Faction component4 = objectUnderCursor.GetComponent<Faction>(); Health component5 = objectUnderCursor.GetComponent<Health>(); Destructible component6 = objectUnderCursor.GetComponent<Destructible>(); // TPS: Specified Game.Collider2D here Game.Collider2D component7 = objectUnderCursor.GetComponent<Game.Collider2D>(); PartyMember component8 = objectUnderCursor.GetComponent<PartyMember>(); if (component3 != null) { GameCursor.DesiredCursor = component3.HoverCursor; } else if (!SingletonBehavior<PartyManager>.Instance.IsPartyMemberSelected()) { if (component8 != null) { GameCursor.DesiredCursor = GameCursor.CursorType.Normal; } else { GameCursor.DesiredCursor = GameCursor.CursorType.NoWalk; } } else if (component2 != null && component2.IconType != ColliderIconType.None) { GameCursor.DesiredCursor = GameCursor.CursorType.Normal; } else if (component6 != null) { if (!component6.IsDestroyed) { GameCursor.DesiredCursor = GameCursor.CursorType.Attack; } else { GameCursor.DesiredCursor = GameCursor.CursorType.Normal; } } else if (component4 != null && component4.GetRelationshipToPlayer() == Relationship.Hostile && component5 != null && !component5.IsDeadOrUnconscious && component4.CharacterStats != null && !component4.CharacterStats.IsImmuneToAttacks && !GameCursor.OverrideCharacterUnderCursor) { GameCursor.DesiredCursor = this.GetAttackCursor(); } else if (component2 != null) { GameCursor.DesiredCursor = component2.GetDesiredCursor(); } else if (component7) { if (!SingletonBehavior<PartyManager>.Instance.IsPrimaryPartyMemberSelected()) { GameCursor.DesiredCursor = GameCursor.CursorType.NoWalk; } else if (GameCursor.CursorOverride != GameCursor.CursorType.None) { GameCursor.DesiredCursor = GameCursor.CursorOverride; } else { GameCursor.DesiredCursor = GameCursor.CursorType.Normal; } } } else if (WorldMapPlayer.Instance != null && WorldMapPlayer.Instance.CanReachMousePosition()) { if (UseMod) { // TPS: Ignore presence of fog when checking walkable state GameCursor.DesiredCursor = GameCursor.CursorType.Walk; } else // default behavior { if (SingletonBehavior<WorldMapFogOfWar>.Instance.IsFogRevealed(GameInput.WorldMousePosition)) { GameCursor.DesiredCursor = GameCursor.CursorType.Walk; } else { GameCursor.DesiredCursor = GameCursor.CursorType.NoWalk; } } } else if (this.CanAtLeastOneSelectedPartyMemberReachMousePosition()) { if (GameState.InCombat && Player.IsSelectedPartyMemberEngaged()) { GameCursor.DesiredCursor = GameCursor.CursorType.Disengage; } else { GameCursor.DesiredCursor = GameCursor.CursorType.Walk; } } else { GameCursor.DesiredCursor = GameCursor.CursorType.NoWalk; } } if (GameCursor.DesiredCursor == GameCursor.CursorType.Normal && GameInput.GetControl(MappedControl.MULTISELECT, false)) { GameCursor.DesiredCursor = GameCursor.CursorType.SelectionAdd; } else if (GameCursor.DesiredCursor == GameCursor.CursorType.Normal && GameInput.GetControl(MappedControl.MULTISELECT_NEGATIVE, false)) { GameCursor.DesiredCursor = GameCursor.CursorType.SelectionSubtract; } this.WantsAttackAdvantageCursor = false; } } }
43.431034
298
0.494045
[ "MIT" ]
SonicZentropy/PoE2Mods.pw
Mods/PoE2Mods/ShipMechanicsMod/Player.cs
10,078
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace FunctionsHost { [DataContract] public class ProcessState { [DataMember] public DateTime DeploymentTimestamp { get; private set; } [DataMember] public byte[] State { get; private set; } [DataMember] public VectorClock SeenClock { get; private set; } [DataMember] public long OurClock { get; private set; } [DataMember] public long Version { get; private set; } public override String ToString() { if (State == null) return $"Checkpoint(v{Version} initial state)"; else return $"Checkpoint(v{Version} sent:{OurClock} seen:{SeenClock} size:{State.Length/1024}kB)"; } // create an empty checkpoint public ProcessState(DateTime deploymentTimestamp, long version) { this.DeploymentTimestamp = deploymentTimestamp; this.Version = version; SeenClock = new VectorClock(); } // create a checkpoint with a state public ProcessState(DateTime deploymentTimestamp, long version, byte[] state, VectorClock seenClock, long ourClock) { this.DeploymentTimestamp = deploymentTimestamp; this.Version = version; this.State = state; this.SeenClock = seenClock; this.OurClock = ourClock; } } }
28.982759
123
0.613325
[ "MIT" ]
Bhaskers-Blu-Org2/ReactiveMachine
Hosts/FunctionsHost/Storage/ProcessState.cs
1,683
C#
namespace Algorithms { /// <summary> /// This is a C# port of the bitonicsort algorithm /// described at https://www.geeksforgeeks.org/bitonic-sort/ /// This is merely a demonstration of BitonicSort and not an optimised /// implementation that should be used in production environments. /// </summary> public class bitonicsort { private static void CompAndSwap(int[] array, int i, int j, int dir) { if ((dir != 0) == (array[i] > array[j])) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } } private static void BitonicMerge(int[] array, int low, int count, int dir) { if (count > 1) { int k = count / 2; for (int i = low; i < low + k; i++) { CompAndSwap(array, i, i + k, dir); } BitonicMerge(array, low, k, dir); BitonicMerge(array, low + k, k, dir); } } private static void Sort(int[] array, int low, int count, int dir) { if (count > 1) { int k = count / 2; Sort(array, low, k, 1); Sort(array, low + k, k, 0); BitonicMerge(array, low, count, dir); } } // Only works when input size is of a power of 2 public static void BitonicSort(int[] array) { Sort(array, 0, array.Length, 1); } } }
27.568966
82
0.45591
[ "MIT" ]
AjayZinngg/csharp
algorithms/sorting/bitonicsort.cs
1,601
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 SharperCryptoApiAnalysis.Installer.Win.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
35.258065
151
0.590119
[ "MIT" ]
AnakinSklavenwalker/SharperCryptoApiAnalysis
tools/SharperCryptoApiAnalysis.Installer.Win/Properties/Settings.Designer.cs
1,095
C#
/* Copyright (C) 2008-2016 Andrea Maggiulli (a.maggiulli@gmail.com) This file is part of QLNet Project https://github.com/amaggiulli/qlnet QLNet is free software: you can redistribute it and/or modify it under the terms of the QLNet license. You should have received a copy of the license along with this program; if not, license is available at <https://github.com/amaggiulli/QLNet/blob/develop/LICENSE>. QLNet is a based on QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ The QuantLib license is available online at http://quantlib.org/license.shtml. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ using System; using System.Collections.Generic; namespace QLNet { //! Hazard-rate term structure /*! This abstract class acts as an adapter to DefaultProbabilityTermStructure allowing the programmer to implement only the <tt>hazardRateImpl(Time)</tt> method in derived classes. Survival/default probabilities and default densities are calculated from hazard rates. Hazard rates are defined with annual frequency and continuous compounding. \ingroup defaultprobabilitytermstructures */ public abstract class HazardRateStructure : DefaultProbabilityTermStructure { #region Constructors protected HazardRateStructure(DayCounter dc = null, List<Handle<Quote> > jumps = null, List<Date> jumpDates = null) : base(dc, jumps, jumpDates) {} protected HazardRateStructure(Date referenceDate, Calendar cal = null, DayCounter dc = null, List<Handle<Quote> > jumps = null, List<Date> jumpDates = null) : base(referenceDate, cal, dc, jumps, jumpDates) { } protected HazardRateStructure(int settlementDays, Calendar cal, DayCounter dc = null, List<Handle<Quote> > jumps = null, List<Date> jumpDates = null) : base(settlementDays, cal, dc, jumps, jumpDates) { } #endregion #region Calculations // This method must be implemented in derived classes to // perform the actual calculations. When it is called, // range check has already been performed; therefore, it // must assume that extrapolation is required. //! hazard rate calculation protected abstract double hazardRateImpl(double t); #endregion #region DefaultProbabilityTermStructure implementation /*! survival probability calculation implemented in terms of the hazard rate \f$ h(t) \f$ as \f[ S(t) = \exp\left( - \int_0^t h(\tau) d\tau \right). \f] \warning This default implementation uses numerical integration, which might be inefficient and inaccurate. Derived classes should override it if a more efficient implementation is available. */ protected override double survivalProbabilityImpl(double t) { GaussChebyshevIntegration integral = new GaussChebyshevIntegration(48); // this stores the address of the method to integrate (so that // we don't have to insert its full expression inside the // integral below--it's long enough already) // the Gauss-Chebyshev quadratures integrate over [-1,1], // hence the remapping (and the Jacobian term t/2) return Math.Exp(-integral.value(hazardRateImpl) * t / 2.0); } //! default density calculation protected override double defaultDensityImpl(double t) { return hazardRateImpl(t) * survivalProbabilityImpl(t); } #endregion } }
38.74
121
0.685338
[ "BSD-3-Clause" ]
SalmonTie/QLNet
src/QLNet/Termstructures/Credit/HazardRateStructure.cs
3,876
C#
namespace UnityEngine.Animations.Rigging { /// <summary> /// This interface is used to represent all constraints classes. /// </summary> public interface IRigConstraint { /// <summary> /// Retrieves the constraint valid state. /// </summary> /// <returns>Returns true if constraint data can be successfully evaluated. Returns false otherwise.</returns> bool IsValid(); /// <summary> /// Creates the animation job for this constraint. /// </summary> /// <param name="animator">The animated hierarchy Animator component.</param> /// <returns>Returns the newly instantiated job.</returns> IAnimationJob CreateJob(Animator animator); /// <summary> /// Updates the specified job data. /// </summary> /// <param name="job">The job to update.</param> void UpdateJob(IAnimationJob job); /// <summary> /// Frees the specified job memory. /// </summary> /// <param name="job">The job to destroy.</param> void DestroyJob(IAnimationJob job); /// <summary> /// The data container for the constraint. /// </summary> IAnimationJobData data { get; } /// <summary> /// The job binder for the constraint. /// </summary> IAnimationJobBinder binder { get; } /// <summary> /// The component for the constraint. /// </summary> Component component { get; } /// <summary> /// The constraint weight. This is a value in between 0 and 1. /// </summary> float weight { get; set; } } }
32.346154
118
0.565398
[ "CC0-1.0" ]
ewanreis/fmp-v1
fmp/Library/PackageCache/com.unity.animation.rigging@1.0.3/Runtime/AnimationRig/IRigConstraint.cs
1,682
C#
using System.Threading.Tasks; namespace DiscordUWA.Interfaces { interface INavigable { Task OnNavigatedToAsync(object parameter); Task OnNavigatedFromAsync(object parameter); } }
22.777778
52
0.726829
[ "MIT" ]
jarveson/discorduwa
DiscordUWA/Interfaces/INavigable.cs
207
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Hashing.Algorithms.Tests { [SkipOnPlatform(TestPlatforms.Browser, "Not supported on Browser")] public class HmacSha1Tests : Rfc2202HmacTests { private static readonly byte[][] s_testKeys2202 = { null, ByteUtils.RepeatByte(0x0b, 20), ByteUtils.AsciiBytes("Jefe"), ByteUtils.RepeatByte(0xaa, 20), ByteUtils.HexToByteArray("0102030405060708090a0b0c0d0e0f10111213141516171819"), ByteUtils.RepeatByte(0x0c, 20), ByteUtils.RepeatByte(0xaa, 80), ByteUtils.RepeatByte(0xaa, 80), }; private static readonly byte[][] s_testMacs2202 = { null, ByteUtils.HexToByteArray("b617318655057264e28bc0b6fb378c8ef146be00"), ByteUtils.HexToByteArray("effcdf6ae5eb2fa2d27416d5f184df9c259a7c79"), ByteUtils.HexToByteArray("125d7342b9ac11cd91a39af48aa17b4f63f175d3"), ByteUtils.HexToByteArray("4c9007f4026250c6bc8414f9bf50c86c2d7235da"), ByteUtils.HexToByteArray("4c1a03424b55e07fe7f27be1d58bb9324a9a5a04"), ByteUtils.HexToByteArray("aa4ae5e15272d00e95705637ce8a3b55ed402112"), ByteUtils.HexToByteArray("e8e99d0f45237d786d6bbaa7965c7808bbff1a91"), }; public HmacSha1Tests() : base(s_testKeys2202, s_testMacs2202) { } protected override int BlockSize => 64; protected override int MacSize => 20; protected override HMAC Create() => new HMACSHA1(); protected override HashAlgorithm CreateHashAlgorithm() => SHA1.Create(); protected override byte[] HashDataOneShot(byte[] key, byte[] source) => HMACSHA1.HashData(key, source); protected override byte[] HashDataOneShot(ReadOnlySpan<byte> key, ReadOnlySpan<byte> source) => HMACSHA1.HashData(key, source); protected override int HashDataOneShot(ReadOnlySpan<byte> key, ReadOnlySpan<byte> source, Span<byte> destination) => HMACSHA1.HashData(key, source, destination); protected override bool TryHashDataOneShot(ReadOnlySpan<byte> key, ReadOnlySpan<byte> source, Span<byte> destination, out int written) => HMACSHA1.TryHashData(key, source, destination, out written); [Fact] public void HmacSha1_Byte_Constructors() { byte[] key = (byte[])s_testKeys2202[1].Clone(); string digest = "b617318655057264e28bc0b6fb378c8ef146be00"; using (HMACSHA1 h1 = new HMACSHA1(key)) { VerifyHmac_KeyAlreadySet(h1, 1, digest); using (HMACSHA1 h2 = new HMACSHA1(key, true)) { VerifyHmac_KeyAlreadySet(h2, 1, digest); Assert.Equal(h1.Key, h2.Key); } using (HMACSHA1 h2 = new HMACSHA1(key, false)) { VerifyHmac_KeyAlreadySet(h1, 1, digest); Assert.Equal(h1.Key, h2.Key); } } } [Fact] public void HmacSha1_ThrowsArgumentNullForNullConstructorKey() { AssertExtensions.Throws<ArgumentNullException>("key", () => new HMACSHA1(null)); } [Fact] public void HmacSha1_Rfc2202_1() { VerifyHmac(1, s_testMacs2202[1]); } [Fact] public void HmacSha1_Rfc2202_2() { VerifyHmac(2, s_testMacs2202[2]); } [Fact] public void HmacSha1_Rfc2202_3() { VerifyHmac(3, s_testMacs2202[3]); } [Fact] public void HmacSha1_Rfc2202_4() { VerifyHmac(4, s_testMacs2202[4]); } [Fact] public void HmacSha1_Rfc2202_5() { VerifyHmac(5, s_testMacs2202[5]); } [Fact] public void HmacSha1_Rfc2202_6() { VerifyHmac(6, s_testMacs2202[6]); } [Fact] public void HmacSha1_Rfc2202_7() { VerifyHmac(7, s_testMacs2202[7]); } [Fact] public void HMacSha1_Rfc2104_2() { VerifyHmacRfc2104_2(); } } }
33.074074
145
0.594849
[ "MIT" ]
Alex-ABPerson/runtime
src/libraries/System.Security.Cryptography.Algorithms/tests/HmacSha1Tests.cs
4,465
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.UI.Xaml.Controls { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented] #endif public enum PivotSlideInAnimationGroup { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ Default, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ GroupOne, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ GroupTwo, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ GroupThree, #endif } #endif }
35.269231
99
0.715376
[ "Apache-2.0" ]
Abhishek-Sharma-Msft/uno
src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml.Controls/PivotSlideInAnimationGroup.cs
917
C#
#pragma checksum "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "05cab76d386113316385bc2675c68f8b4773be2e" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared__Layout2), @"mvc.1.0.view", @"/Views/Shared/_Layout2.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\_ViewImports.cshtml" using E_Learning.Learning; #line default #line hidden #nullable disable #nullable restore #line 2 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\_ViewImports.cshtml" using E_Learning.ViewModel; #line default #line hidden #nullable disable #nullable restore #line 3 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\_ViewImports.cshtml" using E_Learning.Domain; #line default #line hidden #nullable disable #nullable restore #line 1 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" using Microsoft.AspNetCore.Identity; #line default #line hidden #nullable disable #nullable restore #line 2 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" using E_Learning.Learning.Areas.Identity.Data; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"05cab76d386113316385bc2675c68f8b4773be2e", @"/Views/Shared/_Layout2.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"2076f24ad3f96ce7096c49ff78c747174fc0b112", @"/Views/_ViewImports.cshtml")] public class Views_Shared__Layout2 : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<IndexViewModel> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("rel", new global::Microsoft.AspNetCore.Html.HtmlString("stylesheet"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/assets/vendor/fonts/boxicons.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/assets/vendor/css/core.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("template-customizer-core-css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/assets/vendor/css/theme-default.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("template-customizer-theme-css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/assets/css/demo.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/assets/vendor/libs/apex-charts/apex-charts.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_9 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "~/assets/vendor/js/helpers.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_10 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "~/assets/js/config.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_11 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/Pages/1-dars Das 9db0f.html"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_12 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("menu-link"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_13 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/assets/img/avatars/1.png"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_14 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("w-px-40 h-auto rounded-circle"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_15 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("dropdown-item"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_16 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-area", "Identity", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_17 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "/Account/Manage/Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_18 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("logoutForm"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_19 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("form-inline"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_20 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "/Account/Logout", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_21 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "~/assets/vendor/libs/jquery/jquery.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_22 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "~/assets/vendor/libs/popper/popper.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_23 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "~/assets/vendor/js/bootstrap.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_24 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "~/assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_25 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "~/assets/vendor/js/menu.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_26 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "~/assets/vendor/libs/apex-charts/apexcharts.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_27 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "~/assets/js/main.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_28 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "~/assets/js/dashboards-analytics.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper; private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper; private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { WriteLiteral("\r\n"); WriteLiteral("\r\n"); WriteLiteral("\r\n<!DOCTYPE html>\r\n<html lang=\"en\">\r\n"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("head", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "05cab76d386113316385bc2675c68f8b4773be2e14694", async() => { WriteLiteral("\r\n <meta charset=\"utf-8\" />\r\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\r\n <title>"); #nullable restore #line 14 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" Write(ViewData["Title"]); #line default #line hidden #nullable disable WriteLiteral(@" - E_Learning.Learning</title> <!-- Fonts --> <link rel=""preconnect"" href=""https://fonts.googleapis.com"" /> <link rel=""preconnect"" href=""https://fonts.gstatic.com"" crossorigin /> <link href=""https://fonts.googleapis.com/css2?family=Public+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&display=swap"" rel=""stylesheet""/> <!-- Icons. Uncomment required icon fonts --> "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "05cab76d386113316385bc2675c68f8b4773be2e15768", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral(@" <!-- Google Web Fonts --> <link rel=""preconnect"" href=""https://fonts.googleapis.com""> <link rel=""preconnect"" href=""https://fonts.gstatic.com"" crossorigin> <link href=""https://fonts.googleapis.com/css2?family=Heebo:wght@400;500;600&family=Nunito:wght@600;700;800&display=swap"" rel=""stylesheet""> <!-- Core CSS --> "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "05cab76d386113316385bc2675c68f8b4773be2e17305", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "05cab76d386113316385bc2675c68f8b4773be2e18571", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "05cab76d386113316385bc2675c68f8b4773be2e19837", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n\r\n <!-- Vendors CSS -->\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "05cab76d386113316385bc2675c68f8b4773be2e21048", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "05cab76d386113316385bc2675c68f8b4773be2e22231", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_8); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n\r\n <!-- Page CSS -->\r\n\r\n <!-- Helpers -->\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "05cab76d386113316385bc2675c68f8b4773be2e23467", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_9.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_9); #nullable restore #line 44 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion = true; #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-append-version", __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "05cab76d386113316385bc2675c68f8b4773be2e25436", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_10.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_10); #nullable restore #line 46 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion = true; #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-append-version", __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n"); } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("body", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "05cab76d386113316385bc2675c68f8b4773be2e28107", async() => { WriteLiteral(@" <!-- Layout wrapper --> <div class=""layout-wrapper layout-content-navbar""> <div class=""layout-container""> <!-- Menu --> <aside id=""layout-menu"" class=""layout-menu menu-vertical menu bg-menu-theme""> <div class=""app-brand demo""> <a href=""index.html"" class=""app-brand-link""> <span class=""app-brand-logo demo""> <svg width=""25"" viewBox=""0 0 25 42"" version=""1.1"" xmlns=""http://www.w3.org/2000/svg"" xmlns:xlink=""http://www.w3.org/1999/xlink"" > <defs> <path d=""M13.7918663,0.358365126 L3.39788168,7.44174259 C0.566865006,9.69408886 -0.379795268,12.4788597 0.557900856,15.7960551 C0.68998853,16.2305145 1.09562888,17.7872135 3.12357076,19.2293357 C3.8146334,19.7207684 5.32369333,20.3834223 7.65075054,21.2172976 L7.59773219,21.2525164 L2.63468769,24.5493413 C"); WriteLiteral(@"0.445452254,26.3002124 0.0884951797,28.5083815 1.56381646,31.1738486 C2.83770406,32.8170431 5.20850219,33.2640127 7.09180128,32.5391577 C8.347334,32.0559211 11.4559176,30.0011079 16.4175519,26.3747182 C18.0338572,24.4997857 18.6973423,22.4544883 18.4080071,20.2388261 C17.963753,17.5346866 16.1776345,15.5799961 13.0496516,14.3747546 L10.9194936,13.4715819 L18.6192054,7.984237 L13.7918663,0.358365126 Z"" id=""path-1"" ></path> <path d=""M5.47320593,6.00457225 C4.05321814,8.216144 4.36334763,10.0722806 6.40359441,11.5729822 C8.61520715,12.571656 10.0999176,13.2171421 10.8577257,13.5094407 L15.5088241,14.433041 L18.6192054,7.984237 C15.5364148,3.11535317 13.9273018,0.573395879 13.7918663,0.358365126 C13.5790555,0.511491653 10.8061687,2.3935607 5.47320593,6.00457225 Z"" id=""path-3"" ></path> <path d=""M7.50063644,21.2294429 L12.3234468,23.3159332 C"); WriteLiteral(@"14.1688022,24.7579751 14.397098,26.4880487 13.008334,28.506154 C11.6195701,30.5242593 10.3099883,31.790241 9.07958868,32.3040991 C5.78142938,33.4346997 4.13234973,34 4.13234973,34 C4.13234973,34 2.75489982,33.0538207 2.37032616e-14,31.1614621 C-0.55822714,27.8186216 -0.55822714,26.0572515 -4.05231404e-15,25.8773518 C0.83734071,25.6075023 2.77988457,22.8248993 3.3049379,22.52991 C3.65497346,22.3332504 5.05353963,21.8997614 7.50063644,21.2294429 Z"" id=""path-4"" ></path> <path d=""M20.6,7.13333333 L25.6,13.8 C26.2627417,14.6836556 26.0836556,15.9372583 25.2,16.6 C24.8538077,16.8596443 24.4327404,17 24,17 L14,17 C12.8954305,17 12,16.1045695 12,15 C12,14.5672596 12.1403557,14.1461923 12.4,13.8 L17.4,7.13333333 C18.0627417,6.24967773 19.3163444,6.07059163 20.2,6.73333333 C20.3516113,6.84704183 20.4862915,6.981722 20.6,7.13333333 Z"" id=""path-5"" ></path> </defs> "); WriteLiteral(@" <g id=""g-app-brand"" stroke=""none"" stroke-width=""1"" fill=""none"" fill-rule=""evenodd""> <g id=""Brand-Logo"" transform=""translate(-27.000000, -15.000000)""> <g id=""Icon"" transform=""translate(27.000000, 15.000000)""> <g id=""Mask"" transform=""translate(0.000000, 8.000000)""> <mask id=""mask-2"" fill=""white""> <use xlink:href=""#path-1""></use> </mask> <use fill=""#696cff"" xlink:href=""#path-1""></use> <g id=""Path-3"" mask=""url(#mask-2)""> <use fill=""#696cff"" xlink:href=""#path-3""></use> <use fill-opacity=""0.2"" fill=""#FFFFFF"" xlink:href=""#path-3""></use> </g> <g id=""Path-4"" mask=""url(#mask-2)""> <use fill=""#696cff"" xlink:href=""#path-4""></use> <use fill-op"); WriteLiteral(@"acity=""0.2"" fill=""#FFFFFF"" xlink:href=""#path-4""></use> </g> </g> <g id=""Triangle"" transform=""translate(19.000000, 11.000000) rotate(-300.000000) translate(-19.000000, -11.000000) "" > <use fill=""#696cff"" xlink:href=""#path-5""></use> <use fill-opacity=""0.2"" fill=""#FFFFFF"" xlink:href=""#path-5""></use> </g> </g> </g> </g> </svg> </span> <span class=""app-brand-text demo menu-text fw-bolder ms-2"">Informatik</span> </a> <a href=""javascript:void(0);"" class=""layout-menu-toggle menu-link text-large ms-auto d-block d-xl-none""> <i class=""bx bx-chevron-left bx-sm align-middle""></i> </a> </div> <div class=""m"); WriteLiteral(@"enu-inner-shadow""></div> <ul class=""menu-inner py-1""> <!-- Dashboard --> <!-- Kerakli qism --> <li class=""menu-item open""> <a href=""javascript:void(0);"" class=""menu-link menu-toggle""> <i class=""menu-icon tf-icons bx bxl-windows""></i> <div>"); #nullable restore #line 131 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" Write(Model.Chapter.Name); #line default #line hidden #nullable disable WriteLiteral("</div>\r\n </a>\r\n <ul class=\"menu-sub\"> \n"); #nullable restore #line 134 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" foreach (var item in Model.Chapter.Sections) { #line default #line hidden #nullable disable WriteLiteral(" <li class=\"menu-item\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "05cab76d386113316385bc2675c68f8b4773be2e34884", async() => { WriteLiteral("\r\n <div>"); #nullable restore #line 138 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" Write(item.Name); #line default #line hidden #nullable disable WriteLiteral("</div>\r\n "); } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_11); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_12); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </li>\n"); #nullable restore #line 141 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" } #line default #line hidden #nullable disable WriteLiteral(@" </ul> </li> <!-- /Kerakli qism --> </ul> </aside> <!-- / Menu --> <!-- Layout container --> <div class=""layout-page""> <!-- Navbar --> <nav class=""layout-navbar container-xxl navbar navbar-expand-xl navbar-detached align-items-center bg-navbar-theme"" id=""layout-navbar"" > <div class=""layout-menu-toggle navbar-nav align-items-xl-center me-3 me-xl-0 d-xl-none""> <a class=""nav-item nav-link px-0 me-xl-4"" href=""javascript:void(0)""> <i class=""bx bx-menu bx-sm""></i> </a> </div> <div class=""navbar-nav-right d-flex align-items-center"" id=""navbar-collapse""> <!-- Search --> <div class=""navbar-nav align-items-center""> <div class=""nav-item d-flex align-items-center""> <i class=""bx bx-search fs-4 lh-0""></i> "); WriteLiteral(@" <input type=""text"" class=""form-control border-0 shadow-none"" placeholder=""Search..."" aria-label=""Search..."" /> </div> </div> <!-- /Search --> <ul class=""navbar-nav flex-row align-items-center ms-auto""> <!-- Place this tag where you want the button to render. --> <li class=""nav-item lh-1 me-3""> <a class=""alert-link"" href=""#""> Prosta link </a> </li> <!-- User --> <li class=""nav-item navbar-dropdown dropdown-user dropdown""> <a class=""nav-link dropdown-toggle hide-arrow"" href=""javascript:void(0);"" data-bs-toggle=""dropdown""> <div class=""avatar avatar-online""> "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "05cab76d386113316385bc2675c68f8b4773be2e38754", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_13); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_14); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral(@" </div> </a> <ul class=""dropdown-menu dropdown-menu-end""> <li> <a class=""dropdown-item""> <div class=""d-flex""> <div class=""flex-shrink-0 me-3""> <div class=""avatar avatar-online""> "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "05cab76d386113316385bc2675c68f8b4773be2e40330", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_13); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_14); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n </div>\r\n <div class=\"flex-grow-1\">\r\n <span class=\"fw-semibold d-block\">"); #nullable restore #line 204 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" Write(UserManager.GetUserAsync(User).Result.FirstName); #line default #line hidden #nullable disable WriteLiteral(" !</span>\r\n <small class=\"text-muted\">"); #nullable restore #line 205 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" Write(UserManager.GetUserName(User)); #line default #line hidden #nullable disable WriteLiteral(@"!</small> </div> </div> </a> </li> <li> <div class=""dropdown-divider""></div> </li> <li> "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "05cab76d386113316385bc2675c68f8b4773be2e42674", async() => { WriteLiteral("\r\n <i class=\"bx bx-user me-2\"></i>\r\n <span class=\"align-middle\">My Profile</span>\r\n "); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_15); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_16.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_16); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_17.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_17); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </li>\r\n <li>\r\n <div class=\"dropdown-divider\"></div>\r\n </li>\r\n <li>\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "05cab76d386113316385bc2675c68f8b4773be2e44549", async() => { WriteLiteral("\r\n <span class=\"align-middle\"><button id=\"logout\" type=\"submit\" class=\"nav-link btn btn-link text-dark\"><i class=\"bx bx-power-off me-2\"></i> Log out</button></span> \r\n "); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_18); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_19); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Area = (string)__tagHelperAttribute_16.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_16); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Page = (string)__tagHelperAttribute_20.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_20); if (__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.RouteValues == null) { throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-returnUrl", "Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper", "RouteValues")); } BeginWriteTagHelperAttribute(); #nullable restore #line 223 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" WriteLiteral(Url.Action("Index", "Home", new { area = "" })); #line default #line hidden #nullable disable __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.RouteValues["returnUrl"] = __tagHelperStringValueBuffer; __tagHelperExecutionContext.AddTagHelperAttribute("asp-route-returnUrl", __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.RouteValues["returnUrl"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral(@" </li> </ul> </li> <!--/ User --> </ul> </div> </nav> <!-- / Navbar --> <!-- Content wrapper --> <div class=""content-wrapper""> <!-- Content --> <div class=""container-xxl flex-grow-1 container-p-y""> <main class=""row""> "); #nullable restore #line 241 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" Write(RenderBody()); #line default #line hidden #nullable disable WriteLiteral(@" </main> </div> <!-- / Content --> <!-- Footer --> <footer class=""content-footer footer bg-footer-theme""> <div class=""container-xxl d-flex flex-wrap justify-content-between py-2 flex-md-row flex-column""> <div class=""mb-2 mb-md-0""> © <script> document.write(new Date().getFullYear()); </script> , made with ❤️ by <a href=""https://mdevs.uz"" target=""_blank"" class=""footer-link fw-bolder"">MDevs Group</a> </div> <div> <a href=""https://github.com/themeselection/sneat-html-admin-template-free/issues"" target=""_blank"" class=""footer-link me-4"" >Support</a > </div> </div> </footer> <!-- / Footer --> "); WriteLiteral(@" <div class=""content-backdrop fade""></div> </div> <!-- Content wrapper --> </div> <!-- / Layout page --> </div> <!-- Overlay --> <div class=""layout-overlay layout-menu-toggle""></div> </div> <!-- / Layout wrapper --> <!-- Core JS --> <!-- build:js assets/vendor/js/core.js --> "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "05cab76d386113316385bc2675c68f8b4773be2e50003", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_21.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_21); #nullable restore #line 284 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion = true; #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-append-version", __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "05cab76d386113316385bc2675c68f8b4773be2e51971", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_22.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_22); #nullable restore #line 285 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion = true; #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-append-version", __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "05cab76d386113316385bc2675c68f8b4773be2e53939", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_23.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_23); #nullable restore #line 286 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion = true; #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-append-version", __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "05cab76d386113316385bc2675c68f8b4773be2e55907", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_24.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_24); #nullable restore #line 287 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion = true; #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-append-version", __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "05cab76d386113316385bc2675c68f8b4773be2e57875", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_25.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_25); #nullable restore #line 288 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion = true; #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-append-version", __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n <!-- endbuild -->\r\n\r\n <!-- Vendors JS -->\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "05cab76d386113316385bc2675c68f8b4773be2e59899", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_26.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_26); #nullable restore #line 292 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion = true; #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-append-version", __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n\r\n <!-- Main JS -->\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "05cab76d386113316385bc2675c68f8b4773be2e61895", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_27.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_27); #nullable restore #line 295 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion = true; #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-append-version", __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n\r\n <!-- Page JS -->\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "05cab76d386113316385bc2675c68f8b4773be2e63891", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_28.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_28); #nullable restore #line 298 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion = true; #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-append-version", __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); #nullable restore #line 299 "E:\OWN\E-Learning\BackEnd\E-Learning\E-Learning.Learning\Views\Shared\_Layout2.cshtml" Write(await RenderSectionAsync("Scripts", required: false)); #line default #line hidden #nullable disable WriteLiteral("\r\n"); } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n</html>\r\n"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public UserManager<E_LearningLearningUser> UserManager { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public SignInManager<E_LearningLearningUser> SignInManager { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<IndexViewModel> Html { get; private set; } } } #pragma warning restore 1591
74.543764
483
0.681226
[ "MIT" ]
Nodirbek-Abdulaxadov/e-learning
BackEnd/E-Learning/E-Learning.Learning/obj/Debug/net5.0/Razor/Views/Shared/_Layout2.cshtml.g.cs
68,138
C#
using UnityEngine; namespace Client.Scripts.UI.Window { public abstract class Window : MonoBehaviour { public void Open() { MainMenu.MainMenu.Instance.CloseAllButtons(); gameObject.SetActive(true); } public void Close() => gameObject.SetActive(false); } }
21.666667
59
0.612308
[ "Unlicense" ]
meanxson/Scream-Into-The-Empty
Assets/Client/Scripts/UI/Window/Window.cs
325
C#
// Developed by doiTTeam => devdoiTTeam@gmail.com using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.ServiceModel; using System.ServiceModel.Channels; using DHT; using DHT.MainModule; namespace ConsoleApplication1.ServiceReference1 { [GeneratedCode("System.ServiceModel", "4.0.0.0")] [ServiceContract(ConfigurationName = "ServiceReference1.IReverseIndexServiceContract")] public interface IReverseIndexServiceContract { // CODEGEN: Generating message contract since the wrapper namespace (DHT) of message PingRequest does not match the default value (http://tempuri.org/) [OperationContract(Action = "DHT/IKadNodeOf_String_IEnumerableOf_FileId/Ping", ReplyAction = "DHT/IKadNodeOf_String_IEnumerableOf_FileId/PingResponse")] PingResponse Ping(PingRequest request); // CODEGEN: Generating message contract since the wrapper namespace (DHT) of message StoreRequest does not match the default value (http://tempuri.org/) [OperationContract(Action = "DHT/IKadNodeOf_String_IEnumerableOf_FileId/Store", ReplyAction = "DHT/IKadNodeOf_String_IEnumerableOf_FileId/StoreResponse")] StoreResponse Store(StoreRequest request); // CODEGEN: Generating message contract since the wrapper namespace (DHT) of message FindNodeRequest does not match the default value (http://tempuri.org/) [OperationContract(Action = "DHT/IKadNodeOf_String_IEnumerableOf_FileId/FindNode", ReplyAction = "DHT/IKadNodeOf_String_IEnumerableOf_FileId/FindNodeResponse")] [ServiceKnownType(typeof (FindValueResult<string, FileId[]>))] FindNodeResponse FindNode(FindNodeRequest request); // CODEGEN: Generating message contract since the wrapper namespace (DHT) of message FindValueRequest does not match the default value (http://tempuri.org/) [OperationContract(Action = "DHT/IKadNodeOf_String_IEnumerableOf_FileId/FindValue", ReplyAction = "DHT/IKadNodeOf_String_IEnumerableOf_FileId/FindValueResponse")] FindValueResponse FindValue(FindValueRequest request); // CODEGEN: Generating message contract since the wrapper namespace (DHT) of message RemoveRequest does not match the default value (http://tempuri.org/) [OperationContract(Action = "DHT/IKadNodeOf_String_IEnumerableOf_FileId/Remove", ReplyAction = "DHT/IKadNodeOf_String_IEnumerableOf_FileId/RemoveResponse")] RemoveResponse Remove(RemoveRequest request); [OperationContract(Action = "http://tempuri.org/ISetKadNodeOf_String_FileId/StoreInto", ReplyAction = "http://tempuri.org/ISetKadNodeOf_String_FileId/StoreIntoResponse")] void StoreInto(string key, FileId value, NodeIdentifier<string> callerIdentifier); [OperationContract(Action = "http://tempuri.org/ISetKadNodeOf_String_FileId/RemoveInto", ReplyAction = "http://tempuri.org/ISetKadNodeOf_String_FileId/RemoveIntoResponse")] bool RemoveInto(string key, FileId value, NodeIdentifier<string> callerIdentifier); [OperationContract(Action = "http://tempuri.org/ISetKadNodeOf_String_FileId/FindPagedValue", ReplyAction = "http://tempuri.org/ISetKadNodeOf_String_FileId/FindPagedValueResponse")] FindValueResult<string, FileId[]> FindPagedValue(string key, int pageIndex, int pageCount, NodeIdentifier<string> callerIdentifier); } [DebuggerStepThrough] [GeneratedCode("System.ServiceModel", "4.0.0.0")] [EditorBrowsable(EditorBrowsableState.Advanced)] [MessageContract(WrapperName = "Ping", WrapperNamespace = "DHT", IsWrapped = true)] public class PingRequest { [MessageBodyMember(Namespace = "DHT", Order = 0)] public NodeIdentifier<string> callerIdentifier; public PingRequest() { } public PingRequest(NodeIdentifier<string> callerIdentifier) { this.callerIdentifier = callerIdentifier; } } [DebuggerStepThrough] [GeneratedCode("System.ServiceModel", "4.0.0.0")] [EditorBrowsable(EditorBrowsableState.Advanced)] [MessageContract(WrapperName = "PingResponse", WrapperNamespace = "DHT", IsWrapped = true)] public class PingResponse { [MessageBodyMember(Namespace = "DHT", Order = 0)] public HeartBeat<string> PingResult; public PingResponse() { } public PingResponse(HeartBeat<string> PingResult) { this.PingResult = PingResult; } } [DebuggerStepThrough] [GeneratedCode("System.ServiceModel", "4.0.0.0")] [EditorBrowsable(EditorBrowsableState.Advanced)] [MessageContract(WrapperName = "Store", WrapperNamespace = "DHT", IsWrapped = true)] public class StoreRequest { [MessageBodyMember(Namespace = "DHT", Order = 2)] public NodeIdentifier<string> callerIdentifier; [MessageBodyMember(Namespace = "DHT", Order = 0)] public string key; [MessageBodyMember(Namespace = "DHT", Order = 1)] public FileId[] value; public StoreRequest() { } public StoreRequest(string key, FileId[] value, NodeIdentifier<string> callerIdentifier) { this.key = key; this.value = value; this.callerIdentifier = callerIdentifier; } } [DebuggerStepThrough] [GeneratedCode("System.ServiceModel", "4.0.0.0")] [EditorBrowsable(EditorBrowsableState.Advanced)] [MessageContract(WrapperName = "StoreResponse", WrapperNamespace = "DHT", IsWrapped = true)] public class StoreResponse { } [DebuggerStepThrough] [GeneratedCode("System.ServiceModel", "4.0.0.0")] [EditorBrowsable(EditorBrowsableState.Advanced)] [MessageContract(WrapperName = "FindNode", WrapperNamespace = "DHT", IsWrapped = true)] public class FindNodeRequest { [MessageBodyMember(Namespace = "DHT", Order = 1)] public NodeIdentifier<string> callerIdentifier; [MessageBodyMember(Namespace = "DHT", Order = 0)] public string key; public FindNodeRequest() { } public FindNodeRequest(string key, NodeIdentifier<string> callerIdentifier) { this.key = key; this.callerIdentifier = callerIdentifier; } } [DebuggerStepThrough] [GeneratedCode("System.ServiceModel", "4.0.0.0")] [EditorBrowsable(EditorBrowsableState.Advanced)] [MessageContract(WrapperName = "FindNodeResponse", WrapperNamespace = "DHT", IsWrapped = true)] public class FindNodeResponse { [MessageBodyMember(Namespace = "DHT", Order = 0)] public FindNodeResult<string> FindNodeResult; public FindNodeResponse() { } public FindNodeResponse(FindNodeResult<string> FindNodeResult) { this.FindNodeResult = FindNodeResult; } } [DebuggerStepThrough] [GeneratedCode("System.ServiceModel", "4.0.0.0")] [EditorBrowsable(EditorBrowsableState.Advanced)] [MessageContract(WrapperName = "FindValue", WrapperNamespace = "DHT", IsWrapped = true)] public class FindValueRequest { [MessageBodyMember(Namespace = "DHT", Order = 1)] public NodeIdentifier<string> callerIdentifier; [MessageBodyMember(Namespace = "DHT", Order = 0)] public string key; public FindValueRequest() { } public FindValueRequest(string key, NodeIdentifier<string> callerIdentifier) { this.key = key; this.callerIdentifier = callerIdentifier; } } [DebuggerStepThrough] [GeneratedCode("System.ServiceModel", "4.0.0.0")] [EditorBrowsable(EditorBrowsableState.Advanced)] [MessageContract(WrapperName = "FindValueResponse", WrapperNamespace = "DHT", IsWrapped = true)] public class FindValueResponse { [MessageBodyMember(Namespace = "DHT", Order = 0)] public FindValueResult<string, FileId[]> FindValueResult; public FindValueResponse() { } public FindValueResponse(FindValueResult<string, FileId[]> FindValueResult) { this.FindValueResult = FindValueResult; } } [DebuggerStepThrough] [GeneratedCode("System.ServiceModel", "4.0.0.0")] [EditorBrowsable(EditorBrowsableState.Advanced)] [MessageContract(WrapperName = "Remove", WrapperNamespace = "DHT", IsWrapped = true)] public class RemoveRequest { [MessageBodyMember(Namespace = "DHT", Order = 1)] public NodeIdentifier<string> callerIdentifier; [MessageBodyMember(Namespace = "DHT", Order = 0)] public string key; public RemoveRequest() { } public RemoveRequest(string key, NodeIdentifier<string> callerIdentifier) { this.key = key; this.callerIdentifier = callerIdentifier; } } [DebuggerStepThrough] [GeneratedCode("System.ServiceModel", "4.0.0.0")] [EditorBrowsable(EditorBrowsableState.Advanced)] [MessageContract(WrapperName = "RemoveResponse", WrapperNamespace = "DHT", IsWrapped = true)] public class RemoveResponse { [MessageBodyMember(Namespace = "DHT", Order = 0)] public bool RemoveResult; public RemoveResponse() { } public RemoveResponse(bool RemoveResult) { this.RemoveResult = RemoveResult; } } [GeneratedCode("System.ServiceModel", "4.0.0.0")] public interface IReverseIndexServiceContractChannel : IReverseIndexServiceContract, IClientChannel { } [DebuggerStepThrough] [GeneratedCode("System.ServiceModel", "4.0.0.0")] public class ReverseIndexServiceContractClient : ClientBase<IReverseIndexServiceContract>, IReverseIndexServiceContract { public ReverseIndexServiceContractClient() { } public ReverseIndexServiceContractClient(string endpointConfigurationName) : base(endpointConfigurationName) { } public ReverseIndexServiceContractClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public ReverseIndexServiceContractClient(string endpointConfigurationName, EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public ReverseIndexServiceContractClient(Binding binding, EndpointAddress remoteAddress) : base(binding, remoteAddress) { } #region IReverseIndexServiceContract Members [EditorBrowsable(EditorBrowsableState.Advanced)] PingResponse IReverseIndexServiceContract.Ping(PingRequest request) { return base.Channel.Ping(request); } [EditorBrowsable(EditorBrowsableState.Advanced)] StoreResponse IReverseIndexServiceContract.Store(StoreRequest request) { return base.Channel.Store(request); } [EditorBrowsable(EditorBrowsableState.Advanced)] FindNodeResponse IReverseIndexServiceContract.FindNode(FindNodeRequest request) { return base.Channel.FindNode(request); } [EditorBrowsable(EditorBrowsableState.Advanced)] FindValueResponse IReverseIndexServiceContract.FindValue(FindValueRequest request) { return base.Channel.FindValue(request); } [EditorBrowsable(EditorBrowsableState.Advanced)] RemoveResponse IReverseIndexServiceContract.Remove(RemoveRequest request) { return base.Channel.Remove(request); } public void StoreInto(string key, FileId value, NodeIdentifier<string> callerIdentifier) { base.Channel.StoreInto(key, value, callerIdentifier); } public bool RemoveInto(string key, FileId value, NodeIdentifier<string> callerIdentifier) { return base.Channel.RemoveInto(key, value, callerIdentifier); } public FindValueResult<string, FileId[]> FindPagedValue(string key, int pageIndex, int pageCount, NodeIdentifier<string> callerIdentifier) { return base.Channel.FindPagedValue(key, pageIndex, pageCount, callerIdentifier); } #endregion public HeartBeat<string> Ping(NodeIdentifier<string> callerIdentifier) { var inValue = new PingRequest(); inValue.callerIdentifier = callerIdentifier; PingResponse retVal = ((IReverseIndexServiceContract) (this)).Ping(inValue); return retVal.PingResult; } public void Store(string key, FileId[] value, NodeIdentifier<string> callerIdentifier) { var inValue = new StoreRequest(); inValue.key = key; inValue.value = value; inValue.callerIdentifier = callerIdentifier; StoreResponse retVal = ((IReverseIndexServiceContract) (this)).Store(inValue); } public FindNodeResult<string> FindNode(string key, NodeIdentifier<string> callerIdentifier) { var inValue = new FindNodeRequest(); inValue.key = key; inValue.callerIdentifier = callerIdentifier; FindNodeResponse retVal = ((IReverseIndexServiceContract) (this)).FindNode(inValue); return retVal.FindNodeResult; } public FindValueResult<string, FileId[]> FindValue(string key, NodeIdentifier<string> callerIdentifier) { var inValue = new FindValueRequest(); inValue.key = key; inValue.callerIdentifier = callerIdentifier; FindValueResponse retVal = ((IReverseIndexServiceContract) (this)).FindValue(inValue); return retVal.FindValueResult; } public bool Remove(string key, NodeIdentifier<string> callerIdentifier) { var inValue = new RemoveRequest(); inValue.key = key; inValue.callerIdentifier = callerIdentifier; RemoveResponse retVal = ((IReverseIndexServiceContract) (this)).Remove(inValue); return retVal.RemoveResult; } } }
38.994595
164
0.671403
[ "MIT" ]
dayanruben/DistributedSearchs
Src/ConsoleApplication1/Service References/ServiceReference1/Reference.cs
14,430
C#
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Console")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("michaelw")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
35.071429
82
0.742363
[ "Unlicense" ]
michael-watson/particle-xamarin
samples/InternetButtonEvolve2016/EvolveApp/Console/Properties/AssemblyInfo.cs
984
C#
//------------------------------------------------------------------------------ // <auto-generated> // Этот код создан программой. // Исполняемая версия:4.0.30319.42000 // // Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае // повторной генерации кода. // </auto-generated> //------------------------------------------------------------------------------ namespace NewPlatform.Flexberry.ServiceBus { using System; using System.Xml; // *** Start programmer edit section *** (Using statements) using ICSSoft.STORMNET; using ICSSoft.STORMNET.Business; using ICSSoft.STORMNET.FunctionalLanguage; using ICSSoft.STORMNET.FunctionalLanguage.SQLWhere; using ICSSoft.STORMNET.KeyGen; // *** End programmer edit section *** (Using statements) /// <summary> /// MessageBS. /// </summary> // *** Start programmer edit section *** (MessageBS CustomAttributes) // *** End programmer edit section *** (MessageBS CustomAttributes) [ICSSoft.STORMNET.AccessType(ICSSoft.STORMNET.AccessType.@this)] public class MessageBS : ICSSoft.STORMNET.Business.BusinessServer { // *** Start programmer edit section *** (MessageBS CustomMembers) /// <summary> /// Returns LCS for loading messages with a specific <paramref name="group"/>, received by subscriptions for the specified <paramref name="client"/> and <paramref name="messageType"/>. /// </summary> /// <param name="client">Client.</param> /// <param name="messageType">Message type.</param> /// <param name="group">Group.</param> /// <param name="view">The view, if not specified, uses <see cref="Message.Views.MessageLightView"/>.</param> /// <returns></returns> public static LoadingCustomizationStruct GetMessagesWithGroupLCS(Client client, MessageType messageType, string group, View view = null) { LoadingCustomizationStruct lcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Message), view ?? Message.Views.MessageLightView); lcs.LimitFunction = SQLWhereLanguageDef.LanguageDef.GetFunction( SQLWhereLanguageDef.LanguageDef.funcAND, SQLWhereLanguageDef.LanguageDef.GetFunction( SQLWhereLanguageDef.LanguageDef.funcEQ, new VariableDef(SQLWhereLanguageDef.LanguageDef.GuidType, Information.ExtractPropertyPath<Message>(x => x.Recipient)), ((KeyGuid)client.__PrimaryKey).Guid), SQLWhereLanguageDef.LanguageDef.GetFunction( SQLWhereLanguageDef.LanguageDef.funcEQ, new VariableDef(SQLWhereLanguageDef.LanguageDef.GuidType, Information.ExtractPropertyPath<Message>(x => x.MessageType)), ((KeyGuid)messageType.__PrimaryKey).Guid), SQLWhereLanguageDef.LanguageDef.GetFunction( SQLWhereLanguageDef.LanguageDef.funcEQ, new VariableDef(SQLWhereLanguageDef.LanguageDef.StringType, Information.ExtractPropertyPath<Message>(x => x.Group)), group), SQLWhereLanguageDef.LanguageDef.GetFunction( SQLWhereLanguageDef.LanguageDef.funcEQ, new VariableDef(SQLWhereLanguageDef.LanguageDef.BoolType, Information.ExtractPropertyPath<Message>(x => x.IsSending)), false)); return lcs; } // *** End programmer edit section *** (MessageBS CustomMembers) // *** Start programmer edit section *** (OnUpdateMessage CustomAttributes) // *** End programmer edit section *** (OnUpdateMessage CustomAttributes) public virtual ICSSoft.STORMNET.DataObject[] OnUpdateMessage(NewPlatform.Flexberry.ServiceBus.Message UpdatedObject) { // *** Start programmer edit section *** (OnUpdateMessage) if (UpdatedObject.GetStatus() == ObjectStatus.Created && !string.IsNullOrEmpty(UpdatedObject.Group) && DataService.GetObjectsCount(GetMessagesWithGroupLCS(UpdatedObject.Recipient, UpdatedObject.MessageType, UpdatedObject.Group)) > 0) { throw new Exception($"A similar message with the group '{UpdatedObject.Group}' already exists."); } return new ICSSoft.STORMNET.DataObject[0]; // *** End programmer edit section *** (OnUpdateMessage) } } }
50.714286
193
0.617551
[ "MIT" ]
Flexberry/NewPlatform.Flexberry.ServiceBus
NewPlatform.Flexberry.ServiceBus.BusinessServers/BusinessServers/MessageBS.cs
4,751
C#
namespace P03_FootballBetting.Data.Configurations { using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using P03_FootballBetting.Data.Models; public class CountryConfiguration : IEntityTypeConfiguration<Country> { public void Configure(EntityTypeBuilder<Country> country) { country .HasKey(c => c.CountryId); country .Property(c => c.Name) .HasMaxLength(50) .IsRequired(true) .IsUnicode(true); } } }
27.090909
73
0.604027
[ "MIT" ]
HostVanyaD/SoftUni
Entity Framework Core/04.Entity-Relations-Exercises/P03_FootballBetting/Data/Configurations/CountryConfiguration.cs
598
C#
// This file is part of the re-linq project (relinq.codeplex.com) // Copyright (C) 2005-2009 rubicon informationstechnologie gmbh, www.rubicon.eu // // re-linq is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License as published by the // Free Software Foundation; either version 2.1 of the License, // or (at your option) any later version. // // re-linq is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with re-linq; if not, see http://www.gnu.org/licenses. // using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Remotion.Linq.Clauses; using Remotion.Linq.Utilities; namespace Remotion.Linq.Parsing.Structure.IntermediateModel { /// <summary> /// Represents a <see cref="MethodCallExpression"/> for /// <see cref="Queryable.ThenByDescending{TSource,TKey}(System.Linq.IOrderedQueryable{TSource},System.Linq.Expressions.Expression{System.Func{TSource,TKey}})"/>. /// It is generated by <see cref="ExpressionTreeParser"/> when an <see cref="Expression"/> tree is parsed. /// When this node is used, it follows an <see cref="OrderByExpressionNode"/>, an <see cref="OrderByDescendingExpressionNode"/>, /// a <see cref="ThenByExpressionNode"/>, or a <see cref="ThenByDescendingExpressionNode"/>. /// </summary> public class ThenByDescendingExpressionNode : MethodCallExpressionNodeBase { public static readonly MethodInfo[] SupportedMethods = new[] { GetSupportedMethod (() => Queryable.ThenByDescending<object, object> (null, null)), GetSupportedMethod (() => Enumerable.ThenByDescending<object, object> (null, null)), }; private readonly ResolvedExpressionCache<Expression> _cachedSelector; public ThenByDescendingExpressionNode (MethodCallExpressionParseInfo parseInfo, LambdaExpression keySelector) : base (parseInfo) { ArgumentUtility.CheckNotNull ("keySelector", keySelector); if (keySelector != null && keySelector.Parameters.Count != 1) throw new ArgumentException ("KeySelector must have exactly one parameter.", "keySelector"); KeySelector = keySelector; _cachedSelector = new ResolvedExpressionCache<Expression> (this); } public LambdaExpression KeySelector { get; private set; } public Expression GetResolvedKeySelector (ClauseGenerationContext clauseGenerationContext) { return _cachedSelector.GetOrCreate (r => r.GetResolvedExpression (KeySelector.Body, KeySelector.Parameters[0], clauseGenerationContext)); } public override Expression Resolve ( ParameterExpression inputParameter, Expression expressionToBeResolved, ClauseGenerationContext clauseGenerationContext) { ArgumentUtility.CheckNotNull ("inputParameter", inputParameter); ArgumentUtility.CheckNotNull ("expressionToBeResolved", expressionToBeResolved); // this simply streams its input data to the output without modifying its structure, so we resolve by passing on the data to the previous node return Source.Resolve (inputParameter, expressionToBeResolved, clauseGenerationContext); } protected override QueryModel ApplyNodeSpecificSemantics (QueryModel queryModel, ClauseGenerationContext clauseGenerationContext) { ArgumentUtility.CheckNotNull ("queryModel", queryModel); var orderByClause = GetOrderByClause (queryModel); if (orderByClause == null) throw new ParserException ("ThenByDescending expressions must follow OrderBy, OrderByDescending, ThenBy, or ThenByDescending expressions."); orderByClause.Orderings.Add (new Ordering (GetResolvedKeySelector (clauseGenerationContext), OrderingDirection.Desc)); return queryModel; } private OrderByClause GetOrderByClause (QueryModel queryModel) { if (queryModel.BodyClauses.Count == 0) return null; else return queryModel.BodyClauses[queryModel.BodyClauses.Count - 1] as OrderByClause; } } }
48.419355
163
0.712636
[ "MIT" ]
rajcybage/BrightstarDB
src/portable/BrightstarDB.Portable/relinq/RelinqCore/Parsing/Structure/IntermediateModel/ThenByDescendingExpressionNode.cs
4,503
C#
// Copyright (c) Microsoft. All rights reserved. namespace Microsoft.Azure.Devices.Edge.Storage { using System.Text; using Newtonsoft.Json; public static class SerDeExtensions { public static T FromJson<T>(this string json) { if (string.IsNullOrWhiteSpace(json)) { return default(T); } return typeof(T) == typeof(string) ? (T)(object)json : JsonConvert.DeserializeObject<T>(json); } public static string ToJson(this object value) { if (value == null) { return string.Empty; } return value as string ?? JsonConvert.SerializeObject(value); } public static string FromBytes(this byte[] bytes) => bytes == null || bytes.Length == 0 ? string.Empty : Encoding.UTF8.GetString(bytes); public static byte[] ToBytes(this string value) => string.IsNullOrWhiteSpace(value) ? new byte[0] : Encoding.UTF8.GetBytes(value); public static byte[] ToBytes(this object value) { if (value == null) { return null; } if (!(value is byte[] bytes)) { string json = value.ToJson(); bytes = json.ToBytes(); } return bytes; } public static T FromBytes<T>(this byte[] bytes) { if (bytes == null) { return default(T); } if (typeof(T) == typeof(byte[])) { return (T)(object)bytes; } string json = bytes.FromBytes(); var value = json.FromJson<T>(); return value; } } }
25.493151
95
0.476088
[ "MIT" ]
CIPop/iotedge
edge-util/src/Microsoft.Azure.Devices.Edge.Storage/SerDeExtensions.cs
1,861
C#
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. using UnrealBuildTool; public class WindowsTargetPlatform : ModuleRules { public WindowsTargetPlatform(TargetInfo Target) { PrivateDependencyModuleNames.AddRange( new string[] { "Core", "CoreUObject", "TargetPlatform", "DesktopPlatform", } ); PrivateIncludePathModuleNames.AddRange( new string[] { "Settings", } ); PrivateIncludePaths.AddRange( new string[] { "Developer/WindowsTargetPlatform/Classes" } ); // compile with Engine if (UEBuildConfiguration.bCompileAgainstEngine) { PrivateDependencyModuleNames.Add("Engine"); PrivateIncludePathModuleNames.Add("TextureCompressor"); } } }
19.026316
60
0.710927
[ "MIT" ]
armroyce/Unreal
UnrealEngine-4.11.2-release/Engine/Source/Developer/Windows/WindowsTargetPlatform/WindowsTargetPlatform.Build.cs
723
C#
namespace PosSystem { partial class frmAddOrder { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.txtCustomer = new System.Windows.Forms.TextBox(); this.txtPrice = new System.Windows.Forms.TextBox(); this.txtID = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.btnMenu = new System.Windows.Forms.Button(); this.btnSubmit = new System.Windows.Forms.Button(); this.btnSaveOrder = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.cmbProducts = new System.Windows.Forms.ComboBox(); this.SuspendLayout(); // // txtCustomer // this.txtCustomer.Font = new System.Drawing.Font("Times New Roman", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtCustomer.Location = new System.Drawing.Point(407, 561); this.txtCustomer.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.txtCustomer.Name = "txtCustomer"; this.txtCustomer.Size = new System.Drawing.Size(632, 42); this.txtCustomer.TabIndex = 2; // // txtPrice // this.txtPrice.Font = new System.Drawing.Font("Times New Roman", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtPrice.Location = new System.Drawing.Point(407, 420); this.txtPrice.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.txtPrice.Name = "txtPrice"; this.txtPrice.Size = new System.Drawing.Size(632, 42); this.txtPrice.TabIndex = 1; // // txtID // this.txtID.Font = new System.Drawing.Font("Times New Roman", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtID.Location = new System.Drawing.Point(407, 138); this.txtID.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.txtID.Name = "txtID"; this.txtID.ReadOnly = true; this.txtID.Size = new System.Drawing.Size(632, 42); this.txtID.TabIndex = 9; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Times New Roman", 26.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.Location = new System.Drawing.Point(35, 559); this.label5.Margin = new System.Windows.Forms.Padding(8, 0, 8, 0); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(342, 51); this.label5.TabIndex = 2; this.label5.Text = "Customer Name:"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Times New Roman", 26.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(251, 416); this.label4.Margin = new System.Windows.Forms.Padding(8, 0, 8, 0); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(135, 51); this.label4.TabIndex = 3; this.label4.Text = "Price:"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Times New Roman", 26.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(195, 276); this.label3.Margin = new System.Windows.Forms.Padding(8, 0, 8, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(186, 51); this.label3.TabIndex = 4; this.label3.Text = "Product:"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Times New Roman", 26.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(304, 134); this.label2.Margin = new System.Windows.Forms.Padding(8, 0, 8, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(86, 51); this.label2.TabIndex = 5; this.label2.Text = "ID:"; // // btnMenu // this.btnMenu.Font = new System.Drawing.Font("Times New Roman", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnMenu.Location = new System.Drawing.Point(832, 688); this.btnMenu.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnMenu.Name = "btnMenu"; this.btnMenu.Size = new System.Drawing.Size(243, 116); this.btnMenu.TabIndex = 5; this.btnMenu.Text = "Menu"; this.btnMenu.UseVisualStyleBackColor = true; this.btnMenu.Click += new System.EventHandler(this.btnMenu_Click); // // btnSubmit // this.btnSubmit.Font = new System.Drawing.Font("Times New Roman", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnSubmit.Location = new System.Drawing.Point(463, 688); this.btnSubmit.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnSubmit.Name = "btnSubmit"; this.btnSubmit.Size = new System.Drawing.Size(243, 116); this.btnSubmit.TabIndex = 4; this.btnSubmit.Text = "Submit"; this.btnSubmit.UseVisualStyleBackColor = true; this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click); // // btnSaveOrder // this.btnSaveOrder.Font = new System.Drawing.Font("Times New Roman", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnSaveOrder.Location = new System.Drawing.Point(93, 688); this.btnSaveOrder.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnSaveOrder.Name = "btnSaveOrder"; this.btnSaveOrder.Size = new System.Drawing.Size(243, 116); this.btnSaveOrder.TabIndex = 3; this.btnSaveOrder.Text = "Save New Order"; this.btnSaveOrder.UseVisualStyleBackColor = true; this.btnSaveOrder.Click += new System.EventHandler(this.btnSaveOrder_Click); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Times New Roman", 26.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(475, 32); this.label1.Margin = new System.Windows.Forms.Padding(8, 0, 8, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(231, 51); this.label1.TabIndex = 12; this.label1.Text = "Add Order"; // // cmbProducts // this.cmbProducts.Font = new System.Drawing.Font("Times New Roman", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cmbProducts.FormattingEnabled = true; this.cmbProducts.Location = new System.Drawing.Point(407, 279); this.cmbProducts.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.cmbProducts.Name = "cmbProducts"; this.cmbProducts.Size = new System.Drawing.Size(632, 43); this.cmbProducts.TabIndex = 0; this.cmbProducts.SelectedIndexChanged += new System.EventHandler(this.cmbProducts_SelectedIndexChanged); // // frmAddOrder // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1192, 850); this.ControlBox = false; this.Controls.Add(this.cmbProducts); this.Controls.Add(this.label1); this.Controls.Add(this.btnMenu); this.Controls.Add(this.btnSaveOrder); this.Controls.Add(this.btnSubmit); this.Controls.Add(this.txtCustomer); this.Controls.Add(this.txtPrice); this.Controls.Add(this.txtID); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.Name = "frmAddOrder"; this.Text = "Add Order"; this.Load += new System.EventHandler(this.frmAddOrder_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox txtCustomer; private System.Windows.Forms.TextBox txtPrice; private System.Windows.Forms.TextBox txtID; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button btnMenu; private System.Windows.Forms.Button btnSubmit; private System.Windows.Forms.Button btnSaveOrder; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox cmbProducts; } }
51.726027
165
0.579008
[ "Apache-2.0" ]
MarleneBoyce/Midterm
PosSystem/PosSystem/frmAddOrder.Designer.cs
11,330
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace AcoRaf.Models { public class ExternalLoginConfirmationViewModel { [Required] [Display(Name = "Email")] public string Email { get; set; } } public class ExternalLoginListViewModel { public string ReturnUrl { get; set; } } public class SendCodeViewModel { public string SelectedProvider { get; set; } public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; } public string ReturnUrl { get; set; } public bool RememberMe { get; set; } } public class VerifyCodeViewModel { [Required] public string Provider { get; set; } [Required] [Display(Name = "Code")] public string Code { get; set; } public string ReturnUrl { get; set; } [Display(Name = "Remember this browser?")] public bool RememberBrowser { get; set; } public bool RememberMe { get; set; } } public class ForgotViewModel { [Required] [Display(Name = "Email")] public string Email { get; set; } } public class LoginViewModel { [Required] [Display(Name = "Email")] [EmailAddress] public string Email { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } } public class RegisterViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public class ResetPasswordViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string Code { get; set; } } public class ForgotPasswordViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } } }
27.477876
110
0.587762
[ "MIT" ]
churko/AcoRaf
AcoRaf/Models/AccountViewModels.cs
3,107
C#
namespace AngleSharp.Css.Values { /// <summary> /// Represents a CSS shape. /// https://developer.mozilla.org/en-US/docs/Web/CSS/shape /// </summary> public sealed class Shape { #region Fields readonly Length _top; readonly Length _right; readonly Length _bottom; readonly Length _left; #endregion #region ctor /// <summary> /// Creates a new shape value. /// </summary> /// <param name="top">The top position.</param> /// <param name="right">The right position.</param> /// <param name="bottom">The bottom position.</param> /// <param name="left">The left position.</param> public Shape(Length top, Length right, Length bottom, Length left) { _top = top; _right = right; _bottom = bottom; _left = left; } #endregion #region Properties /// <summary> /// Gets the top side. /// </summary> public Length Top { get { return _top; } } /// <summary> /// Gets the right side. /// </summary> public Length Right { get { return _right; } } /// <summary> /// Gets the bottom side. /// </summary> public Length Bottom { get { return _bottom; } } /// <summary> /// Gets the left side. /// </summary> public Length Left { get { return _left; } } #endregion } }
22.121622
74
0.473427
[ "MIT" ]
ArmyMedalMei/AngleSharp
src/AngleSharp/Css/Values/Shape.cs
1,639
C#
/******************************************************* * Filename: MEFDependencyResolver.cs * File description: * * Version: 1.0 * Created: 07/01/2015 3:29:37 PM * Author: JackyLi * *****************************************************/ using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using System.Web; using System.Web.Mvc; namespace MEF.Mvc { /// <summary> /// MEFDependencyResolver /// </summary> public class MEFDependencyResolver : IDependencyResolver { private const string HttpContextKey = "perRequestContainer"; private ComposablePartCatalog _catalog; public MEFDependencyResolver(ComposablePartCatalog catalog) { _catalog = catalog; } public CompositionContainer ChildContainer { get { var childContainer = HttpContext.Current.Items[HttpContextKey] as CompositionContainer; if (childContainer == null) { childContainer = new CompositionContainer(_catalog); HttpContext.Current.Items[HttpContextKey] = childContainer; } return childContainer; } } public object GetService(Type serviceType) { string contractName = AttributedModelServices.GetContractName(serviceType); return ChildContainer.GetExportedValueOrDefault<object>(contractName); } public IEnumerable<object> GetServices(Type serviceType) { string contractName = AttributedModelServices.GetContractName(serviceType); return ChildContainer.GetExportedValues<object>(contractName); } public static void DisposeOfChildContainer() { var childContainer = HttpContext.Current.Items[HttpContextKey] as CompositionContainer; if (childContainer != null) { childContainer.Dispose(); } } } }
25.458333
91
0.705401
[ "Apache-2.0" ]
JackyLi918/HKH
HKHProjects/MEF.Web/Mvc/MEFDependencyResolver.cs
1,837
C#
// (c) Copyright HutongGames, LLC 2010-2013. All rights reserved. #if !(UNITY_IPHONE || UNITY_ANDROID || UNITY_FLASH || UNITY_PS3 || UNITY_BLACKBERRY || UNITY_METRO || UNITY_WP8 || UNITY_WEBGL) using UnityEngine; namespace HutongGames.PlayMaker.Actions { [ActionCategory(ActionCategory.Movie)] [Tooltip("Stops playing the Movie Texture, and rewinds it to the beginning.")] public class StopMovieTexture : FsmStateAction { [RequiredField] [ObjectType(typeof(MovieTexture))] public FsmObject movieTexture; public override void Reset() { movieTexture = null; } public override void OnEnter() { var movie = movieTexture.Value as MovieTexture; if (movie != null) { movie.Stop(); } Finish(); } } } #endif
20.861111
127
0.707057
[ "Apache-2.0" ]
Drestat/Zombie-Shooter
ZombieShooter/Assets/PlayMaker/Actions/StopMovieTexture.cs
751
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; namespace Azure.Search.Models { internal static class VisualFeatureExtensions { public static string ToSerialString(this VisualFeature value) => value switch { VisualFeature.Adult => "adult", VisualFeature.Brands => "brands", VisualFeature.Categories => "categories", VisualFeature.Description => "description", VisualFeature.Faces => "faces", VisualFeature.Objects => "objects", VisualFeature.Tags => "tags", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown VisualFeature value.") }; public static VisualFeature ToVisualFeature(this string value) { if (string.Equals(value, "adult", StringComparison.InvariantCultureIgnoreCase)) return VisualFeature.Adult; if (string.Equals(value, "brands", StringComparison.InvariantCultureIgnoreCase)) return VisualFeature.Brands; if (string.Equals(value, "categories", StringComparison.InvariantCultureIgnoreCase)) return VisualFeature.Categories; if (string.Equals(value, "description", StringComparison.InvariantCultureIgnoreCase)) return VisualFeature.Description; if (string.Equals(value, "faces", StringComparison.InvariantCultureIgnoreCase)) return VisualFeature.Faces; if (string.Equals(value, "objects", StringComparison.InvariantCultureIgnoreCase)) return VisualFeature.Objects; if (string.Equals(value, "tags", StringComparison.InvariantCultureIgnoreCase)) return VisualFeature.Tags; throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown VisualFeature value."); } } }
47.74359
131
0.696026
[ "MIT" ]
manish1604/azure-sdk-for-net
sdk/search/Azure.Search/src/Generated/Models/VisualFeature.Serialization.cs
1,862
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SimpleCrm { public enum InteractionMethod { None = 0, Email = 1, Phone = 2 } }
15.1875
33
0.646091
[ "MIT" ]
MadHattressWatson/aspnet-core-fundamentals-v3
SimpleCrm/SimpleCrm/InteractionMethod.cs
245
C#
using System; using System.Collections.Generic; using System.Text; namespace SLW.Media.Wave.Wave.Native { /// <summary> /// This class holds MMSYSERR errors. /// </summary> internal class MMSYSERR { /// <summary> /// Success. /// </summary> public const int NOERROR = 0; /// <summary> /// Unspecified error. /// </summary> public const int ERROR = 1; /// <summary> /// Device ID out of range. /// </summary> public const int BADDEVICEID = 2; /// <summary> /// Driver failed enable. /// </summary> public const int NOTENABLED = 3; /// <summary> /// Device already allocated. /// </summary> public const int ALLOCATED = 4; /// <summary> /// Device handle is invalid. /// </summary> public const int INVALHANDLE = 5; /// <summary> /// No device driver present. /// </summary> public const int NODRIVER = 6; /// <summary> /// Memory allocation error. /// </summary> public const int NOMEM = 7; /// <summary> /// Function isn't supported. /// </summary> public const int NOTSUPPORTED = 8; /// <summary> /// Error value out of range. /// </summary> public const int BADERRNUM = 9; /// <summary> /// Invalid flag passed. /// </summary> public const int INVALFLAG = 1; /// <summary> /// Invalid parameter passed. /// </summary> public const int INVALPARAM = 11; /// <summary> /// Handle being used simultaneously on another thread (eg callback). /// </summary> public const int HANDLEBUSY = 12; /// <summary> /// Specified alias not found. /// </summary> public const int INVALIDALIAS = 13; /// <summary> /// Bad registry database. /// </summary> public const int BADDB = 14; /// <summary> /// Registry key not found. /// </summary> public const int KEYNOTFOUND = 15; /// <summary> /// Registry read error. /// </summary> public const int READERROR = 16; /// <summary> /// Registry write error. /// </summary> public const int WRITEERROR = 17; /// <summary> /// Eegistry delete error. /// </summary> public const int DELETEERROR = 18; /// <summary> /// Registry value not found. /// </summary> public const int VALNOTFOUND = 19; /// <summary> /// Driver does not call DriverCallback. /// </summary> public const int NODRIVERCB = 20; /// <summary> /// Last error in range. /// </summary> public const int LASTERROR = 20; } }
28.882353
77
0.496266
[ "BSD-2-Clause" ]
7956968/gb28181-sip
GB28181.Client/Player/Media/Wave/native/MMSYSERR.cs
2,946
C#
using NUnit.Framework; namespace Mirage.SocketLayer.Tests { [Category("SocketLayer")] public class ByteUtilsTest { [Test] public void WriteReadByteTest() { byte[] buffer = new byte[10]; int offset = 3; byte value = 100; ByteUtils.WriteByte(buffer, ref offset, value); Assert.That(offset, Is.EqualTo(4), "Should have moved offset by 1"); Assert.That(buffer[3], Is.Not.Zero, "Should have written to buffer"); offset = 3; byte outValue = ByteUtils.ReadByte(buffer, ref offset); Assert.That(offset, Is.EqualTo(4), "Should have moved offset by 1"); Assert.That(outValue, Is.EqualTo(value), "Out value should be equal to in value"); } [Test] public void WriteReadUShortTest() { byte[] buffer = new byte[10]; int offset = 3; ushort value = 1000; ByteUtils.WriteUShort(buffer, ref offset, value); Assert.That(offset, Is.EqualTo(5), "Should have moved offset by 2"); Assert.That(buffer[3], Is.Not.Zero, "Should have written to buffer"); Assert.That(buffer[4], Is.Not.Zero, "Should have written to buffer"); offset = 3; ushort outValue = ByteUtils.ReadUShort(buffer, ref offset); Assert.That(offset, Is.EqualTo(5), "Should have moved offset by 2"); Assert.That(outValue, Is.EqualTo(value), "Out value should be equal to in value"); } [Test] public void WriteReadUIntTest() { byte[] buffer = new byte[10]; int offset = 3; // value large enough to use all 4 bytes uint value = 0x12_34_56_78; ByteUtils.WriteUInt(buffer, ref offset, value); Assert.That(offset, Is.EqualTo(7), "Should have moved offset by 4"); Assert.That(buffer[3], Is.Not.Zero, "Should have written to buffer"); Assert.That(buffer[4], Is.Not.Zero, "Should have written to buffer"); Assert.That(buffer[5], Is.Not.Zero, "Should have written to buffer"); Assert.That(buffer[6], Is.Not.Zero, "Should have written to buffer"); offset = 3; uint outValue = ByteUtils.ReadUInt(buffer, ref offset); Assert.That(offset, Is.EqualTo(7), "Should have moved offset by 4"); Assert.That(outValue, Is.EqualTo(value), "Out value should be equal to in value"); } [Test] public void WriteReadULongTest() { byte[] buffer = new byte[20]; int offset = 3; // value large enough to use all 4 bytes ulong value = 0x12_34_56_78_90_24_68_02ul; ByteUtils.WriteULong(buffer, ref offset, value); Assert.That(offset, Is.EqualTo(11), "Should have moved offset by 8"); Assert.That(buffer[3], Is.Not.Zero, "Should have written to buffer"); Assert.That(buffer[4], Is.Not.Zero, "Should have written to buffer"); Assert.That(buffer[5], Is.Not.Zero, "Should have written to buffer"); Assert.That(buffer[6], Is.Not.Zero, "Should have written to buffer"); Assert.That(buffer[7], Is.Not.Zero, "Should have written to buffer"); Assert.That(buffer[8], Is.Not.Zero, "Should have written to buffer"); Assert.That(buffer[9], Is.Not.Zero, "Should have written to buffer"); Assert.That(buffer[10], Is.Not.Zero, "Should have written to buffer"); offset = 3; ulong outValue = ByteUtils.ReadULong(buffer, ref offset); Assert.That(offset, Is.EqualTo(11), "Should have moved offset by 8"); Assert.That(outValue, Is.EqualTo(value), "Out value should be equal to in value"); } [Test] [Ignore("c# only lets you bit shift by max of 63, It only takes first 6 bits, so will drop any extra bits and try to shift anyway")] public void UlongShift() { ulong value = 0xfUL; ulong shifted = value << 56; ulong expected = 0x0F00_0000_0000_0000UL; Assert.That(shifted, Is.EqualTo(expected)); } [Test] [Description("this test should fail")] [Ignore("c# only lets you bit shift by max of 63. It only takes first 6 bits, so will drop any extra bits and try to shift anyway")] public void UlongShift_ShouldFail() { ulong value = 0xfUL; ulong shifted = value << 64; ulong expected = 0; // expected to shift value 64 times and end up with 0 // but instead it shifts 0 times (64 & 0xFFF === 0) // this leaves the final result same as value Assert.That(shifted, Is.EqualTo(expected)); } } }
41.084034
140
0.580487
[ "MIT" ]
SoftwareGuy/Mirage
Assets/Tests/SocketLayer/ByteUtilsTest.cs
4,889
C#
/* MIT License Copyright(c) 2020 Kyle Givler https://github.com/JoyfulReaper 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 AlarmClock.Models; using System; using System.Drawing; using System.Windows.Forms; namespace AlarmClock { public partial class frmAlarmFired : Form { private bool switchColor = true; private AlarmModel alarm; public frmAlarmFired(AlarmModel alarm) { InitializeComponent(); this.alarm = alarm; lblName.Text = $"Alarm: {alarm.Name}"; textBoxMessage.Text = $"{alarm.Message}"; lblAlarmTime.Text = $"Set for: {alarm.AlarmDateTime}"; //TODO do something better! var mediaPlayer = new MediaPlayer.MediaPlayer(); mediaPlayer.FileName = @".\default.mp3"; mediaPlayer.Play(); UpdateLabels(); } private void UpdateLabels() { TimeSpan overdue = DateTime.Now - alarm.AlarmDateTime; lblElapsed.Text = $"Elapsed: {overdue.Days} Days {overdue.Hours} Hours {overdue.Minutes} Minutes {overdue.Seconds} Seconds"; } private void ColorTimer_Tick(object sender, System.EventArgs e) { if (switchColor) { switchColor = false; lblAlarmHeader.ForeColor = Color.Red; } else { switchColor = true; lblAlarmHeader.ForeColor = Color.Navy; } UpdateLabels(); } private void btnAcknowledge_Click(object sender, EventArgs e) { this.Close(); } } }
31.352941
136
0.652908
[ "MIT" ]
JoyfulReaper/ProgrammersIdeaBook
ProgrammersIdeaBook/AlarmClock/Forms/frmAlarmFired.cs
2,667
C#
using System; using System.Collections.Generic; using System.Linq; namespace _02._Change_List { class Program { static void Main(string[] args) { List<int> numbers = Console.ReadLine().Split (' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList(); string input = Console.ReadLine(); while (input != "end") { string[] command = input.Split(); if (command[0] == "Delete") { int number = int.Parse(command[1]); numbers.RemoveAll(n => n == number); } else if (command[0] == "Insert") { int number = int.Parse(command[1]); int index = int.Parse(command[2]); numbers.Insert(index, number); } input = Console.ReadLine(); } Console.WriteLine(string.Join(' ', numbers)); } } }
28.888889
88
0.459615
[ "MIT" ]
rythm-net/SoftUni
Fundamentals with C#/T12 - List/exercise/02. Change List/Program.cs
1,042
C#
namespace Identity.API.Configuration { public class AppSetting { public Jwt Jwt { get; set; } } public class Jwt { public string Key { get; set; } public string Issuer { get; set; } public string Audience { get; set; } public string TokenUserName { get; set; } public string TokenPassword { get; set; } public int TokenExpirationSeconds { get; set; } } }
23.105263
55
0.583144
[ "MIT" ]
nirajramshrestha/AspnetMicroservices
src/Services/Identity/Identity.API/Configuration/AppSetting.cs
441
C#
using MongoDB.Driver; namespace LinFx.Extensions.MongoDB { public interface IMongoDbContext { IMongoDatabase Database { get; } IMongoCollection<T> Collection<T>(); } }
16.583333
44
0.663317
[ "MIT" ]
ailuozhu/LinFx
src/LinFx/Extensions/MongoDB/IMongoDbContext.cs
201
C#
// *********************************************************************** // Assembly : ACBr.Net.NFSe // Author : Rafael Dias // Created : 12-26-2017 // // Last Modified By : Rafael Dias // Last Modified On : 12-26-2017 // *********************************************************************** // <copyright file="LayoutImpressao.cs" company="ACBr.Net"> // The MIT License (MIT) // Copyright (c) 2016 Grupo ACBr.Net // // 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. // </copyright> // <summary></summary> // *********************************************************************** namespace ACBr.Net.NFSe { public enum LayoutImpressao { ABRASF, ABRASF2, DSF, Ginfes } }
43.634146
83
0.613751
[ "MIT" ]
ACBrNet/ACBr.Net.NFSe
src/ACBr.Net.NFSe/LayoutImpressao.cs
1,789
C#
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. // // ███╗ ██╗ ██████╗ ████████╗██╗ ██████╗███████╗ // ████╗ ██║██╔═══██╗╚══██╔══╝██║██╔════╝██╔════╝ // ██╔██╗ ██║██║ ██║ ██║ ██║██║ █████╗ // ██║╚██╗██║██║ ██║ ██║ ██║██║ ██╔══╝ // ██║ ╚████║╚██████╔╝ ██║ ██║╚██████╗███████╗ // ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝ // ------------------------------------------------ // // This file is automatically generated. // Please do not edit these files manually. // // ------------------------------------------------ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text.Json; using System.Text.Json.Serialization; #nullable restore namespace Elastic.Clients.Elasticsearch { public partial class FlushStats { [JsonInclude] [JsonPropertyName("periodic")] public long Periodic { get; init; } [JsonInclude] [JsonPropertyName("total")] public long Total { get; init; } [JsonInclude] [JsonPropertyName("total_time")] public string? TotalTime { get; init; } [JsonInclude] [JsonPropertyName("total_time_in_millis")] public long TotalTimeInMillis { get; init; } } }
29.355556
76
0.514762
[ "Apache-2.0" ]
SimonCropp/elasticsearch-net
src/Elastic.Clients.Elasticsearch/_Generated/Types/FlushStats.g.cs
1,767
C#
// Copyright 2013 Jon Skeet. All rights reserved. Use of this source code is governed by the Apache License 2.0, as found in the LICENSE.txt file. using System; namespace WhatTheHeck { class Program { static void Main(string[] args) { var limit = 10; limit = "five"; for (var x = 0; x < limit; x++) { Console.WriteLine(x); Console.WriteLine("The current value of x is: {0}", x); } } } }
25.85
147
0.520309
[ "Apache-2.0" ]
23dproject/DemoCode
Abusing CSharp/Code/WhatTheHeck/Program.cs
519
C#
namespace LetsPlayAGame.Data.Models.Enums { public enum QuestStatus { Active, Finalized, Failed, Inactive } }
14.090909
42
0.56129
[ "MIT" ]
Snooking/Let-s-play-a-game
Server/LetsPlayAGame/LetsPlayAGame.Data/Models/Enums/QuestStatus.cs
157
C#
namespace Problem_2.Customer { public class Payment { public Payment(string productName, decimal price) { ProductName = productName; Price = price; } public string ProductName { get; set; } public decimal Price { get; set; } } }
20.466667
57
0.557003
[ "MIT" ]
Supbads/Softuni-Education
02. CSharp OOP 11.15/8. OOP-Common-Type-System-Homework/Problem 2. Customer/Payment.cs
309
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 19.10.2021. using Microsoft.EntityFrameworkCore.Migrations.Operations; using NUnit.Framework; using xEFCore=Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Migrations.Generations.SET001.DataTypes.Clr.Guid{ //////////////////////////////////////////////////////////////////////////////// using T_DATA=System.Guid; //////////////////////////////////////////////////////////////////////////////// //class TestSet_ERR001__bad_TypeName public static class TestSet_ERR001__bad_TypeName { private const string c_testTableName ="EFCORE_TTABLE_DUMMY"; private const string c_testColumnName ="MY_COLUMN"; //----------------------------------------------------------------------- [Test] public static void Test_0000__BLABLABLA() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "BLABLABLA", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unknown_StoreTypeName_1 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__TypeMappingSource__Base, "BLABLABLA"); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0000__BLABLABLA //----------------------------------------------------------------------- [Test] public static void Test_0001__DOUBLE_PRECISION() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "DOUBLE PRECISION", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__DOUBLE, typeof(T_DATA), typeof(double)); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0001__DOUBLE_PRECISION //----------------------------------------------------------------------- [Test] public static void Test_0002__FLOAT() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "FLOAT", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__FLOAT, typeof(T_DATA), typeof(float)); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0002__FLOAT //----------------------------------------------------------------------- [Test] public static void Test_0003__SMALLINT() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "SMALLINT", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__SMALLINT, typeof(T_DATA), typeof(short)); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0003__SMALLINT //----------------------------------------------------------------------- [Test] public static void Test_0004__INTEGER() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "INTEGER", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__INTEGER, typeof(T_DATA), typeof(int)); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0004__INTEGER //----------------------------------------------------------------------- [Test] public static void Test_0005__BIGINT() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "BIGINT", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__BIGINT, typeof(T_DATA), typeof(long)); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0005__BIGINT //----------------------------------------------------------------------- [Test] public static void Test_0006__NUMERIC_5_1() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "NUMERIC(5,1)", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__NUMERIC, typeof(T_DATA), typeof(decimal)); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0006__NUMERIC_5_1 //----------------------------------------------------------------------- [Test] public static void Test_0007__DECIMAL_5_1() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "DECIMAL(5,1)", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__DECIMAL, typeof(T_DATA), typeof(decimal)); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0007__DECIMAL_5_1 //----------------------------------------------------------------------- [Test] public static void Test_0008__TIMESTAMP() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "TIMESTAMP", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__TIMESTAMP, typeof(T_DATA), typeof(System.DateTime)); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0008__TIMESTAMP //----------------------------------------------------------------------- // [Test] // public static void Test_0009__TIME() // { // var operation // =new CreateTableOperation // { // Name // =c_testTableName, // // Columns // ={ // new AddColumnOperation // { // Name = c_testColumnName, // Table = c_testTableName, // ClrType = typeof(T_DATA), // ColumnType = "TIME", // IsNullable = false, // }, // }, // };//operation // // try // { // TestHelper.Exec // (new[]{operation}); // } // catch(xEFCore.LcpiOleDb__DataToolException e) // { // CheckErrors.PrintException_OK(e); // // Assert.AreEqual // (2, // TestUtils.GetRecordCount(e)); // // CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 // (TestUtils.GetRecord(e,0), // CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping_D3__TYPE_TIME__as_TimeOnly, // typeof(T_DATA), // typeof(System.TimeOnly)); // // CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 // (TestUtils.GetRecord(e,1), // CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, // c_testTableName, // c_testColumnName); // // return; // }//catch // // TestServices.ThrowWeWaitError(); // }//Test_0009__TIME //----------------------------------------------------------------------- [Test] public static void Test_0010__DATE() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "DATE", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping_D3__TYPE_DATE__as_DateOnly, typeof(T_DATA), typeof(System.DateOnly)); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0010__DATE //----------------------------------------------------------------------- [Test] public static void Test_0011__BLOB() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "BLOB", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__BLOB_BINARY, typeof(T_DATA), typeof(byte[])); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0011__BLOB //----------------------------------------------------------------------- [Test] public static void Test_0012__BLOB__SUB_TYPE__BINARY() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "BLOB SUB_TYPE BINARY", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__BLOB_BINARY, typeof(T_DATA), typeof(byte[])); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0012__BLOB__SUB_TYPE__BINARY //----------------------------------------------------------------------- [Test] public static void Test_0013__BLOB__SUB_TYPE__TEXT() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "BLOB SUB_TYPE TEXT", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__BLOB_TEXT, typeof(T_DATA), typeof(string)); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0013__BLOB__SUB_TYPE__TEXT //----------------------------------------------------------------------- [Test] public static void Test_0014__BLOB__SUB_TYPE__TEXT__CS_UTF8() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "BLOB SUB_TYPE TEXT CHARACTER SET UTF8", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__BLOB_TEXT, typeof(T_DATA), typeof(string)); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0014__BLOB__SUB_TYPE__TEXT__CS_UTF8 //----------------------------------------------------------------------- [Test] public static void Test_0015__VARCHAR_32() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "VARCHAR(32)", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__VARCHAR, typeof(T_DATA), typeof(string)); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0015__VARCHAR_32 //----------------------------------------------------------------------- [Test] public static void Test_0015__VARCHAR_32__CS_UTF8() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "VARCHAR(32) CHARACTER SET UTF8", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__VARCHAR, typeof(T_DATA), typeof(string)); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0015__VARCHAR_32__CS_UTF8 //----------------------------------------------------------------------- [Test] public static void Test_0016__CHAR_32() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "CHAR(32)", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__CHAR, typeof(T_DATA), typeof(string)); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0016__CHAR_32 //----------------------------------------------------------------------- [Test] public static void Test_0017__CHAR_32__CS_UTF8() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "CHAR(32) CHARACTER SET UTF8", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__CHAR, typeof(T_DATA), typeof(string)); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0017__CHAR_32__CS_UTF8 //----------------------------------------------------------------------- [Test] public static void Test_0018__BOOLEAN() { var operation =new CreateTableOperation { Name =c_testTableName, Columns ={ new AddColumnOperation { Name = c_testColumnName, Table = c_testTableName, ClrType = typeof(T_DATA), ColumnType = "BOOLEAN", IsNullable = false, }, }, };//operation try { TestHelper.Exec (new[]{operation}); } catch(xEFCore.LcpiOleDb__DataToolException e) { CheckErrors.PrintException_OK(e); Assert.AreEqual (3, TestUtils.GetRecordCount(e)); CheckErrors.CheckErrorRecord__type_mapping_err__unexpected_ClrType_2 (TestUtils.GetRecord(e,0), CheckErrors.c_src__EFCoreDataProvider__FB_Common__TypeMapping__BOOLEAN, typeof(T_DATA), typeof(bool)); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_column_definition__2 (TestUtils.GetRecord(e,1), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName, c_testColumnName); CheckErrors.CheckErrorRecord__msql_gen_err__failed_to_generate_table_creation_script__1 (TestUtils.GetRecord(e,2), CheckErrors.c_src__EFCoreDataProvider__FB_V03_0_0__MigrationSqlGenerator, c_testTableName); return; }//catch TestServices.ThrowWeWaitError(); }//Test_0018__BOOLEAN };//class TestSet_ERR001__bad_TypeName //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Migrations.Generations.SET001.DataTypes.Clr.Guid
26.239401
122
0.651492
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Migrations/Generations/SET001/DataTypes/Clr/Guid/TestSet_ERR001__bad_TypeName.cs
31,568
C#
using System.Web.Http; using Owin; using RestApi; using RestApi.Interfaces; using Unity; namespace RestApiTest { /// <summary> /// Used to configure the testing OWIN server /// </summary> public class Startup { /// <summary> /// Configures the host /// </summary> public void Configuration(IAppBuilder appBuilder) { var config = new HttpConfiguration(); var configUtil = new TestConfigurationUtility(config); configUtil.ConfigureRoutes(); configUtil.ConfigureDependencies(); appBuilder.UseWebApi(config); } } }
18.3
57
0.708561
[ "Unlicense" ]
abhijitharmandevtest/patientapi
RestApiTest/Startup.cs
551
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using FluentAssertions; using MediatR; using Moq; using NUnit.Framework; using SFA.DAS.EmployerAccounts.Data; using SFA.DAS.EmployerAccounts.Dtos; using SFA.DAS.EmployerAccounts.Mappings; using SFA.DAS.EmployerAccounts.Models; using SFA.DAS.EmployerAccounts.Queries.GetHealthCheck; using SFA.DAS.EmployerAccounts.UnitTests.Builders; using SFA.DAS.Testing; using SFA.DAS.Testing.EntityFramework; namespace SFA.DAS.EmployerAccounts.UnitTests.Queries { [TestFixture] public class GetHealthCheckQueryHandlerTests : FluentTest<GetHealthCheckQueryHandlerTestsFixture> { [Test] public Task Handle_WhenHandlingAGetHealthCheckQuery_ThenShouldReturnAGetHealthCheckQueryResponse() { return RunAsync(f => f.Handle(), (f, r) => { r.Should().NotBeNull(); r.HealthCheck.Should().NotBeNull().And.Match<HealthCheckDto>(d => d.Id == f.HealthChecks[1].Id); }); } } public class GetHealthCheckQueryHandlerTestsFixture { public GetHealthCheckQuery GetHealthCheckQuery { get; set; } public IAsyncRequestHandler<GetHealthCheckQuery, GetHealthCheckQueryResponse> Handler { get; set; } public Mock<EmployerAccountsDbContext> Db { get; set; } public IConfigurationProvider ConfigurationProvider { get; set; } public List<HealthCheck> HealthChecks { get; set; } public GetHealthCheckQueryHandlerTestsFixture() { GetHealthCheckQuery = new GetHealthCheckQuery(); Db = new Mock<EmployerAccountsDbContext>(); ConfigurationProvider = new MapperConfiguration(c => c.AddProfile<HealthCheckMappings>()); HealthChecks = new List<HealthCheck> { new HealthCheckBuilder().WithId(1).Build(), new HealthCheckBuilder().WithId(2).Build() }; Db.Setup(d => d.HealthChecks).Returns(new DbSetStub<HealthCheck>(HealthChecks)); Handler = new GetHealthCheckQueryHandler(new Lazy<EmployerAccountsDbContext>(() => Db.Object), ConfigurationProvider); } public Task<GetHealthCheckQueryResponse> Handle() { return Handler.Handle(GetHealthCheckQuery); } } }
36.338462
130
0.685436
[ "MIT" ]
SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerAccounts.UnitTests/Queries/GetHealthCheckQueryHandlerTests.cs
2,364
C#
namespace SIS.MvcFramework.Routing { using System; using SIS.HTTP.Enums; using SIS.HTTP.Requests; using SIS.HTTP.Responses; public interface IServerRoutingTable { void Add(HttpRequestMethod method, string path, Func<IHttpRequest, IHttpResponse> func); bool Contains(HttpRequestMethod method, string path); Func<IHttpRequest, IHttpResponse> Get(HttpRequestMethod requestMethod, string path); } }
26.529412
96
0.718404
[ "MIT" ]
ivan-nikolov/SIS
SIS.MvcFramework/Routing/IServerRoutingTable.cs
453
C#
using Microsoft.ApplicationInsights.Extensibility; using Microsoft.Crm.Tools.SolutionPackager; using Microsoft.PowerPlatform.Tooling.BatchedTelemetry; using System; using System.Collections.Generic; using System.CommandLine; using System.CommandLine.Invocation; using System.Diagnostics; using System.IO; using DanielsToolbox.Extensions; using System.Text.Json; namespace DanielsToolbox.Models.CommandLine.Dataverse { public class SolutionPackagerCommandLine { private readonly PackagerArguments _arguments = new(); public CommandAction Action { init => _arguments.Action = value; } public AllowDelete AllowDeletes { init => _arguments.AllowDeletes = value; } public AllowWrite AllowWrites { init => _arguments.AllowWrites = value; } public bool Clobber { init => _arguments.Clobber = value; } public TraceLevel ErrorLevel { init => _arguments.ErrorLevel = value; } public DirectoryInfo Folder { init => _arguments.Folder = value.FullName; } public string LocaleTemplate { init => _arguments.LocaleTemplate = value; } public bool Localize { init => _arguments.Localize = value; } public FileInfo LogFile { init => _arguments.LogFile = value.FullName; } public FileInfo MappingFile { init => _arguments.MappingFile = value.FullName; } public bool NoLogo { init => _arguments.NoLogo = value; } public SolutionPackageType PackageType { init => _arguments.PackageType = value; } public FileInfo PathToZipFile { init => _arguments.PathToZipFile = value.FullName; } public bool RepackOnPackForTesting { init => _arguments.RepackOnPackForTesting = value; } public string SingleComponent { init => _arguments.SingleComponent = value; } public bool UseLcid { init => _arguments.UseLcid = value; } public bool UseUnmanagedFileForManaged { init => _arguments.UseUnmanagedFileForManaged = value; } public static IEnumerable<Symbol> Arguments() => new Symbol[] { new Argument<DirectoryInfo>("folder", "Path to solution folder").LegalFilePathsOnly(), new Option<CommandAction>("--action", "Action to Perform"), new Option<FileInfo>("--path-to-zip-file", "Path to file containing solution"), new Option<FileInfo>("--mapping-file", "Path to mapping file").ExistingOnly(), new Option<FileInfo>("--log-file").ExistingOnly(), new Option<TraceLevel>("--error-level"), new Option<SolutionPackageType>("--package-type"), new Option<AllowDelete>("--allow-deletes"), new Option<AllowWrite>("--allow-writes"), new Option<bool>("--clobber"), new Option<string>("--single-component", () => "NONE", "Default NONE") }; public static Command Create() { var command = new Command("packager", "Calls solution packager") { Arguments() }; command.Handler = CommandHandler.Create<SolutionPackagerCommandLine>(a => a.RunSolutionPackager()); return command; } public void RunSolutionPackager() { _arguments.DisableTelemetry = true; var defaultTelemetryConfiguration = TelemetryConfiguration.CreateDefault(); defaultTelemetryConfiguration.DisableTelemetry = true; var telemetryClient = new AppTelemetryClient(defaultTelemetryConfiguration); var packager = new SolutionPackager(_arguments, telemetryClient); packager.Run(); if (_arguments.Action == CommandAction.Extract) { foreach (var flowDefinition in new DirectoryInfo(Path.Combine(_arguments.Folder, "Workflows/")).GetFiles("*.json")) { var doc = JsonDocument.Parse(File.ReadAllText(flowDefinition.FullName)); using Stream waypointsStreamWriter = new FileStream(flowDefinition.FullName, FileMode.OpenOrCreate); var utf8MemoryWriter = new Utf8JsonWriter(waypointsStreamWriter, new JsonWriterOptions { Indented = true }); doc.WriteTo(utf8MemoryWriter); utf8MemoryWriter.Flush(); } } Console.WriteLine("Solution extracted"); } } }
44.86
131
0.636424
[ "MIT" ]
reager/DanielsToolbox
src/DanielsToolbox/Models/CommandLine/Dataverse/SolutionPackagerCommandLine.cs
4,488
C#
using LoggerLibrary.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WindowsLibrary { public class WindowsLibraryFactory : IWindowsLibraryFactory { public FileSystemHelper GetFilesystemHelper(ISimpleLogger logFile) => new FileSystemHelper(logFile); public HostsFileHelper GetHostsFileHelper() => new HostsFileHelper(); public NetworkAdapterHelper GetNetworkAdapterHelper(ISimpleLogger logFile) => new NetworkAdapterHelper(logFile); public NetworkHelper GetNetworkHelper(ISimpleLogger logFile) => new NetworkHelper(logFile); public PageFileHelper GetPageFileHelper(ISimpleLogger logFile) => new PageFileHelper(logFile); public ProcessHelper GetProcessHelper(ISimpleLogger logFile) => new ProcessHelper(logFile); public RegistryHelper GetRegistryHelper(ISimpleLogger logFile) => new RegistryHelper(logFile); public ServiceHelper GetServiceHelper(ISimpleLogger logFile) => new ServiceHelper(logFile); public WindowsHelper GetWindowsHelper(ISimpleLogger logFile) => new WindowsHelper(logFile); public WmiHelper GetWmiHelper(ISimpleLogger logFile) => new WmiHelper(logFile); } }
52.375
120
0.782021
[ "MIT" ]
CodeFontana/WindowsHelpers-Net-Core
WindowsHelpers/WindowsLibraryFactory.cs
1,259
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.AccessControl; using System.Security.Principal; using Microsoft.ML.Data; using Microsoft.ML.Internal.Utilities; namespace Microsoft.ML.Transforms.TensorFlow { public static class TensorFlowUtils { public const string OpType = "OpType"; public const string InputOps = "InputOps"; internal static Schema GetModelSchema(IExceptionContext ectx, TFGraph graph, string opType = null) { var res = new List<KeyValuePair<string, ColumnType>>(); var opTypeGetters = new List<MetadataUtils.MetadataGetter<ReadOnlyMemory<char>>>(); var inputOpsGetters = new List<MetadataUtils.MetadataGetter<VBuffer<ReadOnlyMemory<char>>>>(); var inputOpsLengths = new List<int>(); foreach (var op in graph) { if (opType != null && opType != op.OpType) continue; var tfType = op[0].OutputType; var mlType = Tf2MlNetTypeOrNull(tfType); // If the type is not supported in ML.NET then we cannot represent it as a column in an ISchema. // We also cannot output it with a TensorFlowTransform, so we skip it. if (mlType == null) continue; var shape = graph.GetTensorShape(op[0]); var shapeArray = shape.ToIntArray(); inputOpsLengths.Add(op.NumInputs); MetadataUtils.MetadataGetter<VBuffer<ReadOnlyMemory<char>>> inputOpsGetter = null; if (op.NumInputs > 0) { var inputOps = new ReadOnlyMemory<char>[op.NumInputs]; for (int i = 0; i < op.NumInputs; i++) { var input = op.GetInput(i); inputOps[i] = new ReadOnlyMemory<char>(input.Operation.Name.ToArray()); } inputOpsGetter = (int col, ref VBuffer<ReadOnlyMemory<char>> dst) => dst = new VBuffer<ReadOnlyMemory<char>>(op.NumInputs, inputOps); } inputOpsGetters.Add(inputOpsGetter); MetadataUtils.MetadataGetter<ReadOnlyMemory<char>> opTypeGetter = (int col, ref ReadOnlyMemory<char> dst) => dst = new ReadOnlyMemory<char>(op.OpType.ToArray()); opTypeGetters.Add(opTypeGetter); var columnType = Utils.Size(shapeArray) == 1 && shapeArray[0] <= 0 ? new VectorType(mlType) : Utils.Size(shapeArray) > 0 && shapeArray.Skip(1).All(x => x > 0) ? new VectorType(mlType, shapeArray[0] > 0 ? shapeArray : shapeArray.Skip(1).ToArray()) : new VectorType(mlType); res.Add(new KeyValuePair<string, ColumnType>(op.Name, columnType)); } return Schema.Create(new TensorFlowSchema(ectx, res.ToArray(), opTypeGetters.ToArray(), inputOpsGetters.ToArray(), inputOpsLengths.ToArray())); } /// <summary> /// This method retrieves the information about the graph nodes of a TensorFlow model as an <see cref="ISchema"/>. /// For every node in the graph that has an output type that is compatible with the types supported by /// <see cref="TensorFlowTransform"/>, the output schema contains a column with the name of that node, and the /// type of its output (including the item type and the shape, if it is known). Every column also contains metadata /// of kind <see cref="OpType"/>, indicating the operation type of the node, and if that node has inputs in the graph, /// it contains metadata of kind <see cref="InputOps"/>, indicating the names of the input nodes. /// </summary> /// <param name="ectx">An <see cref="IExceptionContext"/>.</param> /// <param name="modelFile">The name of the file containing the TensorFlow model. Currently only frozen model /// format is supported.</param> public static Schema GetModelSchema(IExceptionContext ectx, string modelFile) { var bytes = File.ReadAllBytes(modelFile); var session = LoadTFSession(ectx, bytes, modelFile); return GetModelSchema(ectx, session.Graph); } /// <summary> /// This is a convenience method for iterating over the nodes of a TensorFlow model graph. It /// iterates over the columns of the <see cref="ISchema"/> returned by <see cref="GetModelSchema(IExceptionContext, string)"/>, /// and for each one it returns a tuple containing the name, operation type, column type and an array of input node names. /// This method is convenient for filtering nodes based on certain criteria, for example, by the operation type. /// </summary> /// <param name="modelFile"></param> /// <returns></returns> public static IEnumerable<(string, string, ColumnType, string[])> GetModelNodes(string modelFile) { var schema = GetModelSchema(null, modelFile); for (int i = 0; i < schema.Count; i++) { var name = schema[i].Name; var type = schema[i].Type; var metadataType = schema[i].Metadata.Schema.GetColumnOrNull(TensorFlowUtils.OpType)?.Type; Contracts.Assert(metadataType != null && metadataType is TextType); ReadOnlyMemory<char> opType = default; schema[i].Metadata.GetValue(TensorFlowUtils.OpType, ref opType); metadataType = schema[i].Metadata.Schema.GetColumnOrNull(TensorFlowUtils.InputOps)?.Type; VBuffer<ReadOnlyMemory<char>> inputOps = default; if (metadataType != null) { Contracts.Assert(metadataType.IsKnownSizeVector && metadataType.ItemType is TextType); schema[i].Metadata.GetValue(TensorFlowUtils.InputOps, ref inputOps); } string[] inputOpsResult = inputOps.DenseValues() .Select(input => input.ToString()) .ToArray(); yield return (name, opType.ToString(), type, inputOpsResult); } } internal static PrimitiveType Tf2MlNetType(TFDataType type) { var mlNetType = Tf2MlNetTypeOrNull(type); if (mlNetType == null) throw new NotSupportedException("TensorFlow type not supported."); return mlNetType; } private static PrimitiveType Tf2MlNetTypeOrNull(TFDataType type) { switch (type) { case TFDataType.Float: return NumberType.R4; case TFDataType.Float_ref: return NumberType.R4; case TFDataType.Double: return NumberType.R8; case TFDataType.UInt16: return NumberType.U2; case TFDataType.UInt8: return NumberType.U1; case TFDataType.UInt32: return NumberType.U4; case TFDataType.UInt64: return NumberType.U8; case TFDataType.Int16: return NumberType.I2; case TFDataType.Int32: return NumberType.I4; case TFDataType.Int64: return NumberType.I8; default: return null; } } internal static TFSession LoadTFSession(IExceptionContext ectx, byte[] modelBytes, string modelFile = null) { var graph = new TFGraph(); try { graph.Import(modelBytes, ""); } catch (Exception ex) { if (!string.IsNullOrEmpty(modelFile)) throw ectx.Except($"TensorFlow exception triggered while loading model from '{modelFile}'"); #pragma warning disable MSML_NoMessagesForLoadContext throw ectx.ExceptDecode(ex, "Tensorflow exception triggered while loading model."); #pragma warning restore MSML_NoMessagesForLoadContext } return new TFSession(graph); } private static TFSession LoadTFSession(IHostEnvironment env, string exportDirSavedModel) { Contracts.Check(env != null, nameof(env)); env.CheckValue(exportDirSavedModel, nameof(exportDirSavedModel)); var sessionOptions = new TFSessionOptions(); var tags = new string[] { "serve" }; var graph = new TFGraph(); var metaGraphDef = new TFBuffer(); return TFSession.FromSavedModel(sessionOptions, null, exportDirSavedModel, tags, graph, metaGraphDef); } // A TensorFlow frozen model is a single file. An un-frozen (SavedModel) on the other hand has a well-defined folder structure. // Given a modelPath, this utility method determines if we should treat it as a SavedModel or not internal static bool IsSavedModel(IHostEnvironment env, string modelPath) { Contracts.Check(env != null, nameof(env)); env.CheckNonWhiteSpace(modelPath, nameof(modelPath)); FileAttributes attr = File.GetAttributes(modelPath); return attr.HasFlag(FileAttributes.Directory); } // Currently used in TensorFlowTransform to protect temporary folders used when working with TensorFlow's SavedModel format. // Models are considered executable code, so we need to ACL tthe temp folders for high-rights process (so low-rights process can’t access it). /// <summary> /// Given a folder path, create it with proper ACL if it doesn't exist. /// Fails if the folder name is empty, or can't create the folder. /// </summary> internal static void CreateFolderWithAclIfNotExists(IHostEnvironment env, string folder) { Contracts.Check(env != null, nameof(env)); env.CheckNonWhiteSpace(folder, nameof(folder)); //if directory exists, do nothing. if (Directory.Exists(folder)) return; WindowsIdentity currentIdentity = null; try { currentIdentity = WindowsIdentity.GetCurrent(); } catch (PlatformNotSupportedException) { } if (currentIdentity != null && new WindowsPrincipal(currentIdentity).IsInRole(WindowsBuiltInRole.Administrator)) { // Create high integrity dir and set no delete policy for all files under the directory. // In case of failure, throw exception. CreateTempDirectoryWithAcl(folder, currentIdentity.User.ToString()); } else { try { Directory.CreateDirectory(folder); } catch (Exception exc) { throw Contracts.ExceptParam(nameof(folder), $"Failed to create folder for the provided path: {folder}. \nException: {exc.Message}"); } } } internal static void DeleteFolderWithRetries(IHostEnvironment env, string folder) { Contracts.Check(env != null, nameof(env)); int currentRetry = 0; int maxRetryCount = 10; using (var ch = env.Start("Delete folder")) { for (; ; ) { try { currentRetry++; Directory.Delete(folder, true); break; } catch (IOException e) { if (currentRetry > maxRetryCount) throw; ch.Info("Error deleting folder. {0}. Retry,", e.Message); } } } } private static void CreateTempDirectoryWithAcl(string folder, string identity) { // Dacl Sddl string: // D: Dacl type // D; Deny access // OI; Object inherit ace // SD; Standard delete function // wIdentity.User Sid of the given user. // A; Allow access // OICI; Object inherit, container inherit // FA File access // BA Built-in administrators // S: Sacl type // ML;; Mandatory Label // NW;;; No write policy // HI High integrity processes only string sddl = "D:(D;OI;SD;;;" + identity + ")(A;OICI;FA;;;BA)S:(ML;OI;NW;;;HI)"; try { var dir = Directory.CreateDirectory(folder); DirectorySecurity dirSec = new DirectorySecurity(); dirSec.SetSecurityDescriptorSddlForm(sddl); dirSec.SetAccessRuleProtection(true, false); // disable inheritance dir.SetAccessControl(dirSec); // Cleaning out the directory, in case someone managed to sneak in between creation and setting ACL. DirectoryInfo dirInfo = new DirectoryInfo(folder); foreach (FileInfo file in dirInfo.GetFiles()) { file.Delete(); } foreach (DirectoryInfo subDirInfo in dirInfo.GetDirectories()) { subDirInfo.Delete(true); } } catch (Exception exc) { throw Contracts.ExceptParam(nameof(folder), $"Failed to create folder for the provided path: {folder}. \nException: {exc.Message}"); } } public static TensorFlowModelInfo LoadTensorFlowModel(IHostEnvironment env, string modelPath) { var session = GetSession(env, modelPath); return new TensorFlowModelInfo(env, session, modelPath); } internal static TFSession GetSession(IHostEnvironment env, string modelPath) { Contracts.Check(env != null, nameof(env)); if (IsSavedModel(env, modelPath)) { env.CheckUserArg(Directory.Exists(modelPath), nameof(modelPath)); return LoadTFSession(env, modelPath); } env.CheckUserArg(File.Exists(modelPath), nameof(modelPath)); var bytes = File.ReadAllBytes(modelPath); return LoadTFSession(env, bytes, modelPath); } internal static unsafe void FetchData<T>(IntPtr data, Span<T> result) { var dataSpan = new Span<T>(data.ToPointer(), result.Length); dataSpan.CopyTo(result); } internal static bool IsTypeSupported(TFDataType tfoutput) { switch (tfoutput) { case TFDataType.Float: case TFDataType.Double: case TFDataType.UInt8: case TFDataType.UInt16: case TFDataType.UInt32: case TFDataType.UInt64: case TFDataType.Int16: case TFDataType.Int32: case TFDataType.Int64: return true; default: return false; } } private sealed class TensorFlowSchema : SimpleSchemaBase { private readonly MetadataUtils.MetadataGetter<ReadOnlyMemory<char>>[] _opTypeGetters; private readonly MetadataUtils.MetadataGetter<VBuffer<ReadOnlyMemory<char>>>[] _inputOpsGetters; private readonly int[] _inputOpsLengths; public TensorFlowSchema(IExceptionContext ectx, KeyValuePair<string, ColumnType>[] columns, MetadataUtils.MetadataGetter<ReadOnlyMemory<char>>[] opTypeGetters, MetadataUtils.MetadataGetter<VBuffer<ReadOnlyMemory<char>>>[] inputOpsGetters, int[] inputOpsLengths) : base(ectx, columns) { ectx.CheckParam(Utils.Size(opTypeGetters) == ColumnCount, nameof(opTypeGetters)); ectx.CheckParam(Utils.Size(inputOpsGetters) == ColumnCount, nameof(inputOpsGetters)); ectx.CheckParam(Utils.Size(inputOpsLengths) == ColumnCount, nameof(inputOpsLengths)); _opTypeGetters = opTypeGetters; _inputOpsGetters = inputOpsGetters; _inputOpsLengths = inputOpsLengths; } protected override void GetMetadataCore<TValue>(string kind, int col, ref TValue value) { Ectx.Assert(0 <= col && col < ColumnCount); if (kind == OpType) _opTypeGetters[col].Marshal(col, ref value); else if (kind == InputOps && _inputOpsGetters[col] != null) _inputOpsGetters[col].Marshal(col, ref value); else throw Ectx.ExceptGetMetadata(); } protected override ColumnType GetMetadataTypeOrNullCore(string kind, int col) { Ectx.Assert(0 <= col && col < ColumnCount); if (kind == OpType) return TextType.Instance; if (kind == InputOps && _inputOpsGetters[col] != null) return new VectorType(TextType.Instance, _inputOpsLengths[col]); return null; } protected override IEnumerable<KeyValuePair<string, ColumnType>> GetMetadataTypesCore(int col) { Ectx.Assert(0 <= col && col < ColumnCount); yield return new KeyValuePair<string, ColumnType>(OpType, TextType.Instance); if (_inputOpsGetters[col] != null) yield return new KeyValuePair<string, ColumnType>(InputOps, new VectorType(TextType.Instance, _inputOpsLengths[col])); } } } }
45.149144
155
0.569696
[ "MIT" ]
xadupre/machinelearning
src/Microsoft.ML.TensorFlow/TensorFlow/TensorflowUtils.cs
18,470
C#
using System.Collections.Generic; namespace InstaSharper.Classes.Models { public class InstaHashtagSearch : List<InstaHashtag> { public bool MoreAvailable { get; set; } public string RankToken { get; set; } } }
21.909091
56
0.680498
[ "MIT" ]
a-legotin/InstaSharper
InstaSharper/Classes/Models/InstaHashtagSearch.cs
243
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 System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.Cdn.Model.V20180510 { public class CreateRealTimeLogDeliveryResponse : AcsResponse { private string requestId; public string RequestId { get { return requestId; } set { requestId = value; } } } }
26.55814
63
0.71979
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-cdn/Cdn/Model/V20180510/CreateRealTimeLogDeliveryResponse.cs
1,142
C#
using System.Runtime.Serialization; using System.Text.Json.Serialization; namespace Betfair.Betting { [JsonConverter(typeof(JsonStringEnumConverter))] public enum Side { [DataMember(Name = "BACK", EmitDefaultValue = false)] Back, [DataMember(Name = "LAY", EmitDefaultValue = false)] Lay, } }
22.8
61
0.660819
[ "MIT" ]
KelvinVail/Betfair
src/Betfair.Betting/Side.cs
344
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace DiagramInteraccionColumnas { static class Program { /// <summary> /// Punto de entrada principal para la aplicación. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
23.043478
65
0.626415
[ "MIT" ]
JairFrancesco/Diagrama-Interaccion-columnas
DiagramInteraccionColumnas/Program.cs
533
C#
using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using MyFirstABPProject.Authorization; using MyFirstABPProject.Authorization.Roles; using MyFirstABPProject.Authorization.Users; using MyFirstABPProject.Editions; using MyFirstABPProject.MultiTenancy; namespace MyFirstABPProject.Identity { public static class IdentityRegistrar { public static IdentityBuilder Register(IServiceCollection services) { services.AddLogging(); return services.AddAbpIdentity<Tenant, User, Role>() .AddAbpTenantManager<TenantManager>() .AddAbpUserManager<UserManager>() .AddAbpRoleManager<RoleManager>() .AddAbpEditionManager<EditionManager>() .AddAbpUserStore<UserStore>() .AddAbpRoleStore<RoleStore>() .AddAbpLogInManager<LogInManager>() .AddAbpSignInManager<SignInManager>() .AddAbpSecurityStampValidator<SecurityStampValidator>() .AddAbpUserClaimsPrincipalFactory<UserClaimsPrincipalFactory>() .AddPermissionChecker<PermissionChecker>() .AddDefaultTokenProviders(); } } }
37.69697
79
0.678457
[ "Apache-2.0" ]
HvaiY/MyCoreStudy
MyFirstABPProject/3.9.0/aspnet-core/src/MyFirstABPProject.Core/Identity/IdentityRegistrar.cs
1,246
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V4200</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V4200 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="UKCT_MT144037UK01.SupportingInfo", Namespace="urn:hl7-org:v3")] [System.Xml.Serialization.XmlRootAttribute("UKCT_MT144037UK01.SupportingInfo", Namespace="urn:hl7-org:v3")] public partial class UKCT_MT144037UK01SupportingInfo { private ST valueField; private UKCT_MT144037UK01SupportingInfoCode codeField; private string nullFlavorField; private string classCodeField; private string moodCodeField; private static System.Xml.Serialization.XmlSerializer serializer; public UKCT_MT144037UK01SupportingInfo() { this.classCodeField = "OBS"; this.moodCodeField = "EVN"; } public ST value { get { return this.valueField; } set { this.valueField = value; } } public UKCT_MT144037UK01SupportingInfoCode code { get { return this.codeField; } set { this.codeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string nullFlavor { get { return this.nullFlavorField; } set { this.nullFlavorField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string classCode { get { return this.classCodeField; } set { this.classCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string moodCode { get { return this.moodCodeField; } set { this.moodCodeField = value; } } private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(UKCT_MT144037UK01SupportingInfo)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current UKCT_MT144037UK01SupportingInfo object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an UKCT_MT144037UK01SupportingInfo object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output UKCT_MT144037UK01SupportingInfo object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out UKCT_MT144037UK01SupportingInfo obj, out System.Exception exception) { exception = null; obj = default(UKCT_MT144037UK01SupportingInfo); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out UKCT_MT144037UK01SupportingInfo obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static UKCT_MT144037UK01SupportingInfo Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((UKCT_MT144037UK01SupportingInfo)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current UKCT_MT144037UK01SupportingInfo object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an UKCT_MT144037UK01SupportingInfo object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output UKCT_MT144037UK01SupportingInfo object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out UKCT_MT144037UK01SupportingInfo obj, out System.Exception exception) { exception = null; obj = default(UKCT_MT144037UK01SupportingInfo); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out UKCT_MT144037UK01SupportingInfo obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static UKCT_MT144037UK01SupportingInfo LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this UKCT_MT144037UK01SupportingInfo object /// </summary> public virtual UKCT_MT144037UK01SupportingInfo Clone() { return ((UKCT_MT144037UK01SupportingInfo)(this.MemberwiseClone())); } #endregion } }
42.335968
1,358
0.580711
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V4200/Generated/UKCT_MT144037UK01SupportingInfo.cs
10,711
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class RegisterCommand : Command { private IHarvesterController harvesterController; private IProviderController providerController; public RegisterCommand(IList<string> args, IHarvesterController harvesterController, IProviderController providerController) : base(args) { this.harvesterController = harvesterController; this.providerController = providerController; } public override string Execute() { string entityType = this.Arguments[0]; string result = string.Empty; if (entityType == nameof(Harvester)) { result = this.harvesterController.Register(this.Arguments.Skip(1).ToList()); } else if (entityType == nameof(Provider)) { result = this.providerController.Register(this.Arguments.Skip(1).ToList()); } return result; } }
28.657143
141
0.687936
[ "MIT" ]
alexdimitrov2000/MinedraftExam-OOPAdvanced
Structure_Skeleton/Core/Commands/RegisterCommand.cs
1,005
C#
using System; namespace Sys.Workflow.Engine.Impl.Cmd { using Sys.Workflow.Engine.Impl.Interceptor; [Serializable] public class GetTableNameCmd : ICommand<string> { private const long serialVersionUID = 1L; private Type entityClass; public GetTableNameCmd(Type entityClass) { this.entityClass = entityClass; } public virtual string Execute(ICommandContext commandContext) { if (entityClass == null) { throw new ActivitiIllegalArgumentException("entityClass is null"); } return commandContext.TableDataManager.GetTableName(entityClass, true); } } }
22.46875
83
0.616134
[ "Apache-2.0" ]
18502079446/cusss
NActiviti/Sys.Bpm.Engine/Engine/impl/cmd/GetTableNameCmd.cs
721
C#
using PPDFrameworkCore; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web; using System.Xml; namespace PPDFramework.Web { /// <summary> /// PPDWebへのマネージャークラスです。 /// </summary> public class WebManager : PPDFrameworkCore.Web.WebManager { private const int Version = 6; private static WebManager webManager = new WebManager(); private static AccountInfo currentAccount = new AccountInfo(); /// <summary> /// インスタンスを取得します。 /// </summary> public static WebManager Instance { get { return webManager; } } /// <summary> /// ログインしているかどうかを取得します。 /// </summary> public bool IsLogined { get { return currentAccount.IsValid; } } /// <summary> /// 現在のアカウントのIDを取得します。 /// </summary> public string CurrentAccountId { get { return currentAccount.AccountId; } } /// <summary> /// 現在のアカウントのユーザー名を取得します。 /// </summary> public string CurrentUserName { get { return currentAccount.UserName; } } private WebManager() { } /// <summary> /// ログインします。 /// </summary> /// <param name="username">ユーザー名。</param> /// <param name="password">パスワード。</param> public ErrorReason Login(string username, string password) { var url = String.Format("{0}/api/login?username={1}&password={2}&version={3}", BaseUrl, username, password, Version); try { var req = CreateRequest(url); using (WebResponse res = req.GetResponse()) { using (XmlReader reader = GetXmlReader(res)) { while (reader.Read()) { if (reader.IsStartElement("Root")) { var result = reader.GetAttribute("Result"); if (result != "0") { return (ErrorReason)int.Parse(result); } string accountId = reader.GetAttribute("AccountID"), nickname = reader.GetAttribute("Nickname"), token = reader.GetAttribute("Token"), ppdy = reader.GetAttribute("PPDY"); currentAccount = new AccountInfo(accountId, nickname, token, int.Parse(ppdy)); break; } } } } } catch { return ErrorReason.NetworkError; } return ErrorReason.OK; } /// <summary> /// ログアウトします /// </summary> public void Logout() { currentAccount = new AccountInfo(); } /// <summary> /// アカウントの情報を更新します /// </summary> public void UpdateAccountInfo() { var data = new Dictionary<string, string>(); if (!currentAccount.IsValid) { return; } ErrorReason reason = ErrorReason.OK; var url = String.Format("{0}/api/update-account-info", BaseUrl); try { var query = new SortedDictionary<string, string>{ {"accountid", currentAccount.AccountId}, { "nonce", new Random().Next().ToString()}, { "token",currentAccount.Token} }; var validateKey = CreateValidateKey(query); query["validatekey"] = validateKey; query.Remove("token"); var req = CreatePostRequest(url, query); using (WebResponse res = req.GetResponse()) { using (XmlReader reader = GetXmlReader(res)) { while (reader.Read()) { if (reader.IsStartElement("Root")) { while (reader.MoveToNextAttribute()) { data.Add(reader.Name, reader.Value); } if (!data.ContainsKey("Result")) { reason = ErrorReason.NetworkError; } else { if (int.TryParse(data["Result"], out int val)) { reason = (ErrorReason)val; } else { reason = ErrorReason.NetworkError; } } if (reason == ErrorReason.OK) { currentAccount.UserName = data["Nickname"]; currentAccount.PPDY = int.Parse(data["PPDY"]); } } } } } } catch { reason = ErrorReason.NetworkError; } } /// <summary> /// パーフェクトトライアルを行います。 /// </summary> /// <param name="scoreHash">譜面のハッシュです。</param> /// <param name="data">データです。</param> /// <returns></returns> public ErrorReason PerfectTrialPrepare(byte[] scoreHash, out Dictionary<string, string> data) { return PerfectTrialPrepare(CryptographyUtility.Getx2Encoding(scoreHash), out data); } /// <summary> /// パーフェクトトライアルを行います。 /// </summary> /// <param name="scoreHash">譜面のハッシュです。</param> /// <param name="data">データです。</param> /// <returns></returns> public ErrorReason PerfectTrialPrepare(string scoreHash, out Dictionary<string, string> data) { data = new Dictionary<string, string>(); if (!currentAccount.IsValid) { return ErrorReason.AuthFailed; } ErrorReason reason = ErrorReason.OK; var url = String.Format("{0}/api/perfect-trial-prepare", BaseUrl); try { var query = new SortedDictionary<string, string>{ {"accountid", currentAccount.AccountId}, { "nonce", new Random().Next().ToString()}, { "token",currentAccount.Token}, { "scorehash",scoreHash}, }; var validateKey = CreateValidateKey(query); query["validatekey"] = validateKey; query.Remove("token"); var req = CreatePostRequest(url, query); using (WebResponse res = req.GetResponse()) { using (XmlReader reader = GetXmlReader(res)) { while (reader.Read()) { if (reader.IsStartElement("Root")) { while (reader.MoveToNextAttribute()) { data.Add(reader.Name, reader.Value); } if (!data.ContainsKey("Result")) { reason = ErrorReason.NetworkError; } else { if (int.TryParse(data["Result"], out int val)) { reason = (ErrorReason)val; } else { reason = ErrorReason.NetworkError; } } } } } } } catch { reason = ErrorReason.NetworkError; } return reason; } /// <summary> /// ゴーストを取得します。 /// </summary> /// <param name="scoreHash"></param> /// <param name="maxCount"></param> /// <param name="ghosts"></param> /// <returns></returns> public ErrorReason GetGhost(string scoreHash, int maxCount, out GhostInfo[] ghosts) { if (!currentAccount.IsValid) { ghosts = new GhostInfo[0]; return ErrorReason.AuthFailed; } ErrorReason reason = ErrorReason.OK; var url = String.Format("{0}/api/ghost", BaseUrl); var ret = new List<GhostInfo>(); try { var query = new SortedDictionary<string, string>{ {"accountid", currentAccount.AccountId}, { "nonce", new Random().Next().ToString()}, { "token",currentAccount.Token}, { "scorehash",scoreHash}, { "maxcount",maxCount.ToString()} }; var validateKey = CreateValidateKey(query); query["validatekey"] = validateKey; query.Remove("token"); var req = CreatePostRequest(url, query); using (WebResponse res = req.GetResponse()) { using (XmlReader reader = GetXmlReader(res)) { while (reader.Read()) { if (reader.IsStartElement("Root")) { var result = int.Parse(reader.GetAttribute("Result")); using (var subReader = reader.ReadSubtree()) { while (subReader.Read()) { if (subReader.IsStartElement("Ghost")) { var id = int.Parse(subReader.GetAttribute("ID")); var accountId = subReader.GetAttribute("AccountID"); var accountName = subReader.GetAttribute("AccountName"); var showScore = subReader.GetAttribute("ShowScore") == "1"; var showEvaluate = subReader.GetAttribute("ShowEvaluate") == "1"; var showLife = subReader.GetAttribute("ShowLife") == "1"; var data = subReader.ReadString(); ret.Add(new GhostInfo(id, accountId, accountName, CryptographyUtility.GetBytesFromBase64String(data), showScore, showEvaluate, showLife)); } } } } } } } } catch { reason = ErrorReason.NetworkError; } ghosts = ret.ToArray(); return reason; } /// <summary> /// プレイ結果を送信します /// </summary> /// <param name="scoreHash">スコアのハッシュ</param> /// <param name="score">スコア</param> /// <param name="coolCount">Coolの回数</param> /// <param name="goodCount">Goddの回数</param> /// <param name="safeCount">Safeの回数</param> /// <param name="sadCount">Sadの回数</param> /// <param name="worstCount">Worstの回数</param> /// <param name="maxCombo">MaxComboの回数</param> /// <param name="startTime">開始時間</param> /// <param name="endTime">終了時間</param> /// <param name="inputs">入力データ</param> /// <param name="retryCount">リトライの回数</param> /// <param name="data">出力情報。</param> /// <param name="perfectTrialToken">トークン。</param> public ErrorReason PlayResult(byte[] scoreHash, int score, int coolCount, int goodCount, int safeCount, int sadCount, int worstCount, int maxCombo, float startTime, float endTime, byte[] inputs, int retryCount, string perfectTrialToken, out Dictionary<string, string> data) { data = new Dictionary<string, string>(); ErrorReason reason = ErrorReason.OK; int tryCount = 0; while (tryCount <= retryCount) { reason = PlayResult(CryptographyUtility.Getx2Encoding(scoreHash), score, coolCount, goodCount, safeCount, sadCount, worstCount, maxCombo, startTime, endTime, CryptographyUtility.GetBase64String(inputs), perfectTrialToken, out data); if (reason != ErrorReason.NetworkError) { break; } tryCount++; } return reason; } /// <summary> /// プレイ結果を送信します /// </summary> /// <param name="scoreHash">スコアのハッシュ</param> /// <param name="score">スコア</param> /// <param name="coolCount">Coolの回数</param> /// <param name="goodCount">Goddの回数</param> /// <param name="safeCount">Safeの回数</param> /// <param name="sadCount">Sadの回数</param> /// <param name="worstCount">Worstの回数</param> /// <param name="maxCombo">MaxComboの回数</param> /// <param name="startTime">開始時間</param> /// <param name="endTime">終了時間</param> /// <param name="inputs">入力データ</param> /// <param name="data">出力情報</param> /// <param name="perfectTrialToken">パーフェクトトライアルのトークン</param> public ErrorReason PlayResult(string scoreHash, int score, int coolCount, int goodCount, int safeCount, int sadCount, int worstCount, int maxCombo, float startTime, float endTime, string inputs, string perfectTrialToken, out Dictionary<string, string> data) { data = new Dictionary<string, string>(); if (!currentAccount.IsValid) { return ErrorReason.AuthFailed; } ErrorReason reason = ErrorReason.OK; var url = String.Format("{0}/api/playresult2", BaseUrl); try { var query = new SortedDictionary<string, string>{ {"accountid", currentAccount.AccountId}, { "nonce", new Random().Next().ToString()}, { "token",currentAccount.Token}, { "scorehash",scoreHash}, { "coolcount",coolCount.ToString()}, { "goodcount",goodCount.ToString()}, { "safecount",safeCount.ToString()}, { "sadcount",sadCount.ToString()}, { "worstcount",worstCount.ToString()}, { "maxcombo",maxCombo.ToString()}, { "score",score.ToString()}, { "inputs",inputs}, { "starttime",startTime.ToString(CultureInfo.InvariantCulture)}, { "endtime",endTime.ToString(CultureInfo.InvariantCulture)} }; var validateKey = CreateValidateKey(query); query["validatekey"] = validateKey; query.Remove("token"); query["perfecttrialtoken"] = perfectTrialToken; var req = CreatePostRequest(url, query); using (WebResponse res = req.GetResponse()) { using (XmlReader reader = GetXmlReader(res)) { while (reader.Read()) { if (reader.IsStartElement("Root")) { while (reader.MoveToNextAttribute()) { data.Add(reader.Name, reader.Value); } if (!data.ContainsKey("Result")) { reason = ErrorReason.NetworkError; } else { if (int.TryParse(data["Result"], out int val)) { reason = (ErrorReason)val; } else { reason = ErrorReason.NetworkError; } } } } } } } catch { reason = ErrorReason.NetworkError; } return reason; } /// <summary> /// ランキングを取得します /// </summary> /// <param name="scoreId">スコアのID</param> /// <returns></returns> public Ranking GetRanking(string scoreId) { var easy = new List<RankingInfo>(); var normal = new List<RankingInfo>(); var hard = new List<RankingInfo>(); var extreme = new List<RankingInfo>(); var url = String.Format("{0}/api/ranking?id={1}", BaseUrl, scoreId); try { var req = CreateRequest(url); using (WebResponse res = req.GetResponse()) { using (XmlReader reader = GetXmlReader(res)) { while (reader.Read()) { if (reader.IsStartElement("Root")) { if (reader.GetAttribute("Result") != "0") { return null; } } else if (reader.IsStartElement("Ranks")) { var difficulty = reader.GetAttribute("Difficulty"); List<RankingInfo> target = null; switch (difficulty) { case "0": target = easy; break; case "1": target = normal; break; case "2": target = hard; break; default: target = extreme; break; } using (XmlReader subReader = reader.ReadSubtree()) { while (subReader.Read()) { if (subReader.IsStartElement("Rank")) { target.Add(new RankingInfo(subReader.GetAttribute("Nickname"), int.Parse(subReader.GetAttribute("Score")), subReader.GetAttribute("ID"), int.Parse(subReader.GetAttribute("Rank")))); } } } } } } } } catch { return null; } return new Ranking(easy.ToArray(), normal.ToArray(), hard.ToArray(), extreme.ToArray()); } /// <summary> /// ランキングを取得します /// </summary> /// <param name="scoreId">スコアのID</param> /// <returns></returns> public Ranking GetRivalRanking(string scoreId) { if (!currentAccount.IsValid) { return new Ranking(new RankingInfo[0], new RankingInfo[0], new RankingInfo[0], new RankingInfo[0]); } var easy = new List<RankingInfo>(); var normal = new List<RankingInfo>(); var hard = new List<RankingInfo>(); var extreme = new List<RankingInfo>(); var url = String.Format("{0}/api/rival-ranking", BaseUrl); try { var query = new SortedDictionary<string, string>{ {"accountid", currentAccount.AccountId}, { "nonce", new Random().Next().ToString()}, { "token",currentAccount.Token}, { "scoreid",scoreId} }; var validateKey = CreateValidateKey(query); query["validatekey"] = validateKey; query.Remove("token"); var req = CreatePostRequest(url, query); using (WebResponse res = req.GetResponse()) { using (XmlReader reader = GetXmlReader(res)) { while (reader.Read()) { if (reader.IsStartElement("Root")) { if (reader.GetAttribute("Result") != "0") { return null; } } else if (reader.IsStartElement("Ranks")) { var difficulty = reader.GetAttribute("Difficulty"); List<RankingInfo> target = null; switch (difficulty) { case "0": target = easy; break; case "1": target = normal; break; case "2": target = hard; break; default: target = extreme; break; } using (XmlReader subReader = reader.ReadSubtree()) { while (subReader.Read()) { if (subReader.IsStartElement("Rank")) { target.Add(new RankingInfo(subReader.GetAttribute("Nickname"), int.Parse(subReader.GetAttribute("Score")), subReader.GetAttribute("ID"), int.Parse(subReader.GetAttribute("Rank")))); } } } } } } } } catch { return null; } return new Ranking(easy.ToArray(), normal.ToArray(), hard.ToArray(), extreme.ToArray()); } /// <summary> /// パーフェクトトライアルの一覧を取得します。 /// </summary> /// <returns></returns> public PerfectTrialInfo[] GetPerfectTrials() { var data = new Dictionary<string, string>(); if (!currentAccount.IsValid) { return new PerfectTrialInfo[0]; } ErrorReason reason = ErrorReason.OK; var url = String.Format("{0}/api/get-perfect-trial-list", BaseUrl); try { var query = new SortedDictionary<string, string>{ {"accountid", currentAccount.AccountId}, { "nonce", new Random().Next().ToString()}, { "token",currentAccount.Token} }; var validateKey = CreateValidateKey(query); query["validatekey"] = validateKey; query.Remove("token"); var req = CreatePostRequest(url, query); var trials = new List<PerfectTrialInfo>(); using (WebResponse res = req.GetResponse()) { using (XmlReader reader = GetXmlReader(res)) { while (reader.Read()) { if (reader.IsStartElement("Root")) { while (reader.MoveToNextAttribute()) { data.Add(reader.Name, reader.Value); } if (!data.ContainsKey("Result")) { reason = ErrorReason.NetworkError; } else { if (int.TryParse(data["Result"], out int val)) { reason = (ErrorReason)val; } else { reason = ErrorReason.NetworkError; } } if (reason != ErrorReason.OK) { return new PerfectTrialInfo[0]; } } else if (reader.IsStartElement("Trial")) { trials.Add(new PerfectTrialInfo( int.Parse(reader.GetAttribute("Id")), reader.GetAttribute("ScoreLibraryId"), reader.GetAttribute("ScoreHash"), (Difficulty)int.Parse(reader.GetAttribute("Difficulty")))); } } } } return trials.ToArray(); } catch { reason = ErrorReason.NetworkError; } return new PerfectTrialInfo[0]; } /// <summary> /// リストの一覧を取得します。 /// </summary> /// <returns></returns> public ListInfo[] GetListInfos() { var data = new Dictionary<string, string>(); if (!currentAccount.IsValid) { return new ListInfo[0]; } var url = String.Format("{0}/api/get-list-info", BaseUrl); try { var query = new SortedDictionary<string, string>{ {"accountid", currentAccount.AccountId}, { "nonce", new Random().Next().ToString()}, { "token",currentAccount.Token} }; var validateKey = CreateValidateKey(query); query["validatekey"] = validateKey; query.Remove("token"); var req = CreatePostRequest(url, query); var lists = new List<ListInfo>(); using (WebResponse res = req.GetResponse()) { using (XmlReader reader = GetXmlReader(res)) { while (reader.Read()) { if (reader.IsStartElement("List")) { var title = reader.GetAttribute("Title"); var isWatch = reader.GetAttribute("Watch") == "1"; var list = new ListInfo(title, isWatch); lists.Add(list); ReadListInfo(reader.ReadSubtree(), list); } } } } return lists.ToArray(); } catch { return new ListInfo[0]; } } private void ReadListInfo(XmlReader reader, ListInfo listInfo) { using (reader) { while (reader.Read()) { if (reader.IsStartElement("Score")) { var id = reader.GetAttribute("ID"); var title = reader.GetAttribute("Title"); listInfo.Add(new ListScoreInfo(listInfo, id, title)); } } } } /// <summary> /// 購入したリプレイの一覧を取得します。 /// </summary> /// <returns></returns> public ReplayInfo[] GetReplayInfos() { var data = new Dictionary<string, string>(); if (!currentAccount.IsValid) { return new ReplayInfo[0]; } ErrorReason reason = ErrorReason.OK; var url = String.Format("{0}/api/get-replay-list", BaseUrl); try { var query = new SortedDictionary<string, string>{ {"accountid", currentAccount.AccountId}, { "nonce", new Random().Next().ToString()}, { "token",currentAccount.Token} }; var validateKey = CreateValidateKey(query); query["validatekey"] = validateKey; query.Remove("token"); var req = CreatePostRequest(url, query); var replays = new List<ReplayInfo>(); using (WebResponse res = req.GetResponse()) { using (XmlReader reader = GetXmlReader(res)) { while (reader.Read()) { if (reader.IsStartElement("Root")) { while (reader.MoveToNextAttribute()) { data.Add(reader.Name, reader.Value); } if (!data.ContainsKey("Result")) { reason = ErrorReason.NetworkError; } else { if (int.TryParse(data["Result"], out int val)) { reason = (ErrorReason)val; } else { reason = ErrorReason.NetworkError; } } if (reason != ErrorReason.OK) { return new ReplayInfo[0]; } } else if (reader.IsStartElement("Purchase")) { replays.Add(new ReplayInfo( int.Parse(reader.GetAttribute("Id")), int.Parse(reader.GetAttribute("ResultId")), int.Parse(reader.GetAttribute("Score")), int.Parse(reader.GetAttribute("CoolCount")), int.Parse(reader.GetAttribute("GoodCount")), int.Parse(reader.GetAttribute("SafeCount")), int.Parse(reader.GetAttribute("SadCount")), int.Parse(reader.GetAttribute("WorstCount")), int.Parse(reader.GetAttribute("MaxCombo")), reader.GetAttribute("ScoreLibraryId"), reader.GetAttribute("ScoreHash"), reader.GetAttribute("Nickname"))); } } } } return replays.ToArray(); } catch { reason = ErrorReason.NetworkError; } return new ReplayInfo[0]; } /// <summary> /// リプレイデータを取得します。 /// </summary> /// <param name="resultId">リザルトID。</param> /// <returns>リプレイデータ。</returns> public byte[] GetReplayData(int resultId) { var data = new Dictionary<string, string>(); if (!currentAccount.IsValid) { return null; } var url = String.Format("{0}/api/get-replay", BaseUrl); try { var query = new SortedDictionary<string, string>{ {"accountid", currentAccount.AccountId}, { "nonce", new Random().Next().ToString()}, { "token",currentAccount.Token}, { "resultid",resultId.ToString()} }; var validateKey = CreateValidateKey(query); query["validatekey"] = validateKey; query.Remove("token"); var req = CreatePostRequest(url, query); using (WebResponse res = req.GetResponse()) { var memoryStream = new MemoryStream(); byte[] buffer = new byte[1024]; using (var stream = res.GetResponseStream()) { while (true) { var readSize = stream.Read(buffer, 0, buffer.Length); if (readSize == 0) { break; } memoryStream.Write(buffer, 0, readSize); } } return memoryStream.ToArray(); } } catch { return null; } } /// <summary> /// スコアのIDを取得します /// </summary> /// <param name="scoreHash">スコアのハッシュ</param> /// <returns>スコアのID</returns> public string GetScoreId(byte[] scoreHash) { return GetScoreId(CryptographyUtility.Getx2Encoding(scoreHash)); } /// <summary> /// スコアのIDを取得します /// </summary> /// <param name="scoreHash">スコアのハッシュ</param> /// <returns>スコアのID</returns> public string GetScoreId(string scoreHash) { var detail = GetScoreDetail(scoreHash); if (detail != null) { return detail.Id; } return ""; } /// <summary> /// 譜面情報の詳細を取得します。 /// </summary> /// <param name="scoreHash">スコアのハッシュ</param> /// <returns>譜面情報の詳細</returns> public WebSongInformationDetail GetScoreDetail(byte[] scoreHash) { return GetScoreDetail(CryptographyUtility.Getx2Encoding(scoreHash)); } /// <summary> /// 譜面情報の詳細を取得します。 /// </summary> /// <param name="scoreHash">スコアのハッシュ</param> /// <returns>譜面情報の詳細</returns> public WebSongInformationDetail GetScoreDetail(string scoreHash) { var url = String.Format("{0}/api/find-score-id?hash={1}", BaseUrl, scoreHash); try { var req = CreateRequest(url); using (WebResponse res = req.GetResponse()) { using (XmlReader reader = GetXmlReader(res)) { while (reader.Read()) { if (reader.IsStartElement("Root")) { if (reader.GetAttribute("Result") == "0") { var id = reader.GetAttribute("ID"); float startTime = float.Parse(reader.GetAttribute("StartTime"), NumberStyles.Float, CultureInfo.InvariantCulture), endTime = float.Parse(reader.GetAttribute("EndTime"), NumberStyles.Float, CultureInfo.InvariantCulture); return new WebSongInformationDetail(id, startTime, endTime); } } } } } } catch { } return null; } private string CreateValidateKey(Dictionary<string, string> parameters) { var nonce = new Random().Next(); var p = new SortedDictionary<string, string>(parameters) { { "nonce", nonce.ToString() }, { "token", currentAccount.Token }, { "accountid", currentAccount.AccountId } }; return CreateValidateKey(p); } private string CreateValidateKey(SortedDictionary<string, string> parameters) { return ""; } /// <summary> /// アイテムの一覧を取得します。 /// </summary> /// <returns>アイテムの一覧。</returns> public ItemInfo[] GetItems() { if (!currentAccount.IsValid) { return new ItemInfo[0]; } var ret = new List<ItemInfo>(); try { var url = String.Format("{0}/api/get-item-list", BaseUrl); var query = new SortedDictionary<string, string>{ {"accountid", currentAccount.AccountId}, { "nonce", new Random().Next().ToString()}, { "token",currentAccount.Token} }; var validateKey = CreateValidateKey(query); query["validatekey"] = validateKey; query.Remove("token"); var req = CreateRequest(url, query); using (WebResponse res = req.GetResponse()) { using (XmlReader reader = GetXmlReader(res)) { while (reader.Read()) { if (reader.IsStartElement("Root")) { if (reader.GetAttribute("Result") != "0") { break; } using (XmlReader subtree = reader.ReadSubtree()) { while (subtree.Read()) { if (reader.IsStartElement("Item")) { var itemId = int.Parse(reader.GetAttribute("ID")); var itemType = (ItemType)int.Parse(reader.GetAttribute("Type")); ret.Add(new ItemInfo(itemId, itemType)); } } } } } } } } catch { } return ret.ToArray(); } /// <summary> /// アイテムを使用します。 /// </summary> /// <param name="itemInfo">アイテムの情報。</param> /// <returns>成功したかどうか。</returns> public bool UseItem(ItemInfo itemInfo) { if (!currentAccount.IsValid) { return false; } bool ret = false; try { var url = String.Format("{0}/api/use-item", BaseUrl); var query = new SortedDictionary<string, string>{ {"accountid", currentAccount.AccountId}, { "nonce", new Random().Next().ToString()}, { "token",currentAccount.Token}, { "id",itemInfo.ItemId.ToString()} }; var validateKey = CreateValidateKey(query); query["validatekey"] = validateKey; query.Remove("token"); var req = CreatePostRequest(url, query); using (WebResponse res = req.GetResponse()) { using (XmlReader reader = GetXmlReader(res)) { while (reader.Read()) { if (reader.IsStartElement("Root")) { ret = reader.GetAttribute("Result") == "0"; } } } } } catch { ret = false; } itemInfo.IsUsed |= ret; return ret; } /// <summary> /// レビューをします。 /// </summary> /// <param name="comment">レビュー文字列。</param> /// <param name="score">レート。</param> /// <param name="scoreHash">スコアのハッシュ。</param> /// <returns></returns> public bool Review(string comment, int score, byte[] scoreHash) { if (!currentAccount.IsValid) { return false; } bool ret = false; try { var url = String.Format("{0}/api/review", BaseUrl); var query = new SortedDictionary<string, string>{ {"accountid", currentAccount.AccountId}, { "nonce", new Random().Next().ToString()}, { "token",currentAccount.Token}, { "scorehash",CryptographyUtility.Getx2Encoding(scoreHash)}, { "comment",comment}, { "score",score.ToString()} }; var validateKey = CreateValidateKey(query); query["validatekey"] = validateKey; query.Remove("token"); var req = CreatePostRequest(url, query); using (WebResponse res = req.GetResponse()) { using (XmlReader reader = GetXmlReader(res)) { while (reader.Read()) { if (reader.IsStartElement("Root")) { ret = reader.GetAttribute("Result") == "0"; } } } } } catch { return false; } return ret; } /// <summary> /// ランキングが利用可能な譜面かどうかを調べます。 /// </summary> /// <param name="primaryHash">プライマリハッシュ。</param> /// <returns></returns> public bool IsRankingAvailable(byte[] primaryHash) { return RankingCache.Cache.IsRankingAvailable(primaryHash); } /// <summary> /// Webに登録されている譜面情報を取得します。 /// </summary> /// <returns></returns> public WebSongInformation[] GetScores() { return GetScores(null); } /// <summary> /// Webに登録されている譜面情報を取得します。 /// </summary> /// <returns></returns> public WebSongInformation[] GetScores(bool onlyActiveScore) { var activeScores = GetActiveScores(); var indexes = new Dictionary<string, int>(); var iter = 0; foreach (var activeScore in activeScores) { indexes.Add(activeScore.Hash, iter); iter++; } var list = GetScores(s => activeScores.FirstOrDefault(active => active.Hash == s.Hash) != null); Array.Sort(list, (w1, w2) => { return indexes[w1.Hash] - indexes[w2.Hash]; }); return list; } private WebSongInformation[] GetScores(Func<WebSongInformation, bool> filter) { var list = new List<WebSongInformation>(); try { var str = GetString(String.Format("{0}/api/all-score-list", BaseUrl)); using (XmlReader reader = GetXmlReader(str)) { while (reader.Read()) { if (reader.IsStartElement("Score")) { string title = reader.GetAttribute("Title"), hash = reader.GetAttribute("Hash"), movieUrl = reader.GetAttribute("MovieUrl"), revision = reader.GetAttribute("Revision"); var info = new WebSongInformation(title, hash, movieUrl, int.Parse(revision)); if (filter != null && !filter(info)) { continue; } list.Add(info); ParseDifficulty(reader.ReadSubtree(), info); info.CheckNewOrCanUpdate(); } } } } catch { } return list.ToArray(); } private void ParseDifficulty(XmlReader reader, WebSongInformation songInfo) { while (reader.Read()) { if (reader.IsStartElement("ScoreDifficulty")) { string difficulty = reader.GetAttribute("Difficulty"), hash = reader.GetAttribute("Hash"), revision = reader.GetAttribute("Revision"); songInfo.AddDifficulty(new WebSongInformationDifficulty(songInfo, (Difficulty)int.Parse(difficulty), int.Parse(revision), hash)); } } reader.Close(); } /// <summary> /// Webに登録されているランキング対象譜面の一覧を取得します。 /// </summary> /// <returns></returns> public WebSongInformation[] GetActiveScores() { var list = new List<WebSongInformation>(); try { var str = GetString(String.Format("{0}/api/active-score", BaseUrl)); using (XmlReader reader = GetXmlReader(str)) { while (reader.Read()) { if (reader.IsStartElement("Entry")) { string title = reader.GetAttribute("Title"), hash = reader.GetAttribute("ID"); var info = new WebSongInformation(title, hash, null, -1); list.Add(info); } } } } catch { } return list.ToArray(); } /// <summary> /// Webに登録されているMod情報を取得します。 /// </summary> /// <returns></returns> public WebModInfo[] GetMods() { var list = new List<WebModInfo>(); try { var str = GetString(String.Format("{0}/api/all-mod-list", BaseUrl)); using (XmlReader reader = GetXmlReader(str)) { while (reader.Read()) { if (reader.IsStartElement("Mod")) { string name = reader.GetAttribute("Name"), id = reader.GetAttribute("ID"), revision = reader.GetAttribute("Revision"); var info = new WebModInfo(name, id, int.Parse(revision)); list.Add(info); ParseDetail(reader.ReadSubtree(), info); } } } } catch { } return list.ToArray(); } private void ParseDetail(XmlReader reader, WebModInfo modInfo) { while (reader.Read()) { if (reader.IsStartElement("ModFile")) { string hash = reader.GetAttribute("Hash"), revision = reader.GetAttribute("Revision"); modInfo.AddDetail(new WebModInfoDetail(modInfo, hash, int.Parse(revision))); } } reader.Close(); } /// <summary> /// 譜面ページのURLを取得します。 /// </summary> /// <param name="scoreLibraryId">スコアのID。</param> /// <returns>URL。</returns> public string GetScorePageUrl(string scoreLibraryId) { return String.Format("{0}/score/index/id/{1}", BaseUrl, scoreLibraryId); } /// <summary> /// アカウントの画像を取得します。 /// </summary> /// <param name="accountId"></param> /// <param name="size"></param> /// <returns></returns> public byte[] GetAccountImage(string accountId, int size = 128) { var url = String.Format("{0}/api/get-avator/s/{1}/id/{2}", PPDFrameworkCore.Web.WebManager.BaseUrl, size, accountId); try { var req = CreateRequest(url); using (WebResponse res = req.GetResponse()) { using (MemoryStream memoryStream = new MemoryStream()) { byte[] buffer = new byte[1024]; using (Stream stream = res.GetResponseStream()) { while (true) { var readSize = stream.Read(buffer, 0, buffer.Length); if (readSize == 0) { break; } memoryStream.Write(buffer, 0, readSize); } } return memoryStream.ToArray(); } } } catch { } return new byte[0]; } /// <summary> /// Webからファイルをダウンロードします。 /// </summary> /// <param name="songInfo">ウェブの譜面情報。</param> /// <param name="filePath">ファイルパス。</param> public void DownloadFile(WebSongInformation songInfo, string filePath) { DownloadFile(songInfo, filePath, BaseUrl); } /// <summary> /// Webからファイルをダウンロードします。 /// </summary> /// <param name="songInfo">ウェブの譜面情報。</param> /// <param name="filePath">ファイルパス。</param> /// <param name="BaseUrl">既定のホスト。</param> public void DownloadFile(WebSongInformation songInfo, string filePath, string BaseUrl) { DownloadFile(String.Format("{0}/score-library/download/id/{1}", BaseUrl, songInfo.Hash), filePath); } /// <summary> /// Webからファイルをダウンロードします。 /// </summary> /// <param name="modInfo">WebのMod情報。</param> /// <param name="filePath">ファイルパス。</param> public void DownloadFile(WebModInfo modInfo, string filePath) { DownloadFile(modInfo, filePath, BaseUrl); } /// <summary> /// Webからファイルをダウンロードします。 /// </summary> /// <param name="modInfo">WebのMod情報。</param> /// <param name="filePath">ファイルパス。</param> /// <param name="BaseUrl">既定のホスト。</param> public void DownloadFile(WebModInfo modInfo, string filePath, string BaseUrl) { DownloadFile(String.Format("{0}/script-library/download/id/{1}", BaseUrl, modInfo.Id), filePath); } /// <summary> /// Webからファイルをダウンロードします。 /// </summary> /// <param name="url">URL。</param> /// <param name="filePath">ファイルパス。</param> public void DownloadFile(string url, string filePath) { var req = CreateRequest(url); using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) { using (FileStream fs = File.Open(filePath, FileMode.Create)) { using (Stream stream = response.GetResponseStream()) { byte[] buffer = new byte[512]; while (true) { var readSize = stream.Read(buffer, 0, buffer.Length); if (readSize == 0) { break; } fs.Write(buffer, 0, readSize); } } } } } /// <summary> /// コンテストの情報を取得します。 /// </summary> /// <returns>コンテストの情報。</returns> public ContestInfo GetContestInfo() { try { var str = GetString(String.Format("{0}/api/get-latest-contest", BaseUrl)); using (XmlReader reader = GetXmlReader(str)) { while (reader.Read()) { if (reader.IsStartElement("Root")) { var info = new ContestInfo(int.Parse(reader.GetAttribute("Id")), reader.GetAttribute("ScoreLibraryId"), reader.GetAttribute("ScoreHash"), (Difficulty)int.Parse(reader.GetAttribute("Difficulty")), ParseDateString(reader.GetAttribute("StartTime")), ParseDateString(reader.GetAttribute("CurrentTime")), ParseDateString(reader.GetAttribute("EndTime")), reader.GetAttribute("Title")); return info; } } } } catch { return null; } return null; } /// <summary> /// コンテストのランキングを取得します。 /// </summary> /// <returns>コンテストのランキング。</returns> public RankingInfo[] GetContestRanking() { var ret = new List<RankingInfo>(); try { var str = GetString(String.Format("{0}/api/get-latest-contest-result", BaseUrl)); using (XmlReader reader = GetXmlReader(str)) { while (reader.Read()) { if (reader.IsStartElement("Result")) { ret.Add(new RankingInfo(reader.GetAttribute("Nickname"), int.Parse(reader.GetAttribute("Score")), reader.GetAttribute("AccountId"), int.Parse(reader.GetAttribute("Rank")))); } } } } catch { } return ret.ToArray(); } private DateTime ParseDateString(string str) { return DateTime.ParseExact(str, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); } private HttpWebRequest CreateRequest(string url, IDictionary<string, string> parameters) { var paramList = new List<string>(); foreach (KeyValuePair<string, string> kvp in parameters) { paramList.Add(String.Format("{0}={1}", kvp.Key, HttpUtility.UrlEncode(kvp.Value))); } return CreateRequest(String.Format("{0}?{1}", url, String.Join("&", paramList.ToArray()))); } private HttpWebRequest CreateRequest(string url) { var request = (HttpWebRequest)HttpWebRequest.Create(url); request.Timeout = 15000; #if DEBUG if (File.Exists("credentials")) { var lines = File.ReadAllLines("credentials"); if (lines.Length >= 2) { request.Credentials = new NetworkCredential(lines[0], lines[1]); } } #endif return request; } private string GetString(string url) { var req = CreateRequest(url); using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } } private HttpWebRequest CreatePostRequest(string url, IDictionary<string, string> param) { var paramList = new List<string>(); foreach (KeyValuePair<string, string> kvp in param) { paramList.Add(String.Format("{0}={1}", kvp.Key, HttpUtility.UrlEncode(kvp.Value))); } var postData = String.Join("&", paramList.ToArray()); var postDataBytes = System.Text.Encoding.ASCII.GetBytes(postData); var req = CreateRequest(url); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = postDataBytes.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(postDataBytes, 0, postDataBytes.Length); } return req; } private XmlReader GetXmlReader(WebResponse res, bool dump = false) { if (dump) { string text = null; using (StreamReader reader = new StreamReader(res.GetResponseStream())) { text = reader.ReadToEnd(); Console.WriteLine(text); } var memStream = new MemoryStream(); var bytes = Encoding.UTF8.GetBytes(text); memStream.Write(bytes, 0, bytes.Length); memStream.Seek(0, SeekOrigin.Begin); return XmlReader.Create(memStream); } else { return XmlReader.Create(res.GetResponseStream()); } } private XmlReader GetXmlReader(string text) { #if DUMP Console.WriteLine(text); #endif var memStream = new MemoryStream(); var bytes = Encoding.UTF8.GetBytes(text); memStream.Write(bytes, 0, bytes.Length); memStream.Seek(0, SeekOrigin.Begin); return XmlReader.Create(memStream); } } }
38.274134
165
0.402047
[ "Apache-2.0" ]
KHCmaster/PPD
Win/PPDFramework/Web/WebManager.cs
63,853
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace ProjetoSimplesMVC.Migrations { public partial class AddBookToDb : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Book", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Name = table.Column<string>(nullable: false), Author = table.Column<string>(nullable: true), ISBN = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Book", x => x.Id); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Book"); } } }
31.71875
71
0.506404
[ "MIT" ]
luiscarlosjunior/courses-content-dotnet
.Net core/Sample ASP.NET Core/ProjetoSimplesMVC/Migrations/20200709011005_AddBookToDb.cs
1,017
C#
using System; using System.Collections.Generic; using System.Reflection; using System.Text; using Xamarin.Forms; namespace Xamarin.AttributeValidation.Models { internal class ValidationModel { internal View UiElement { get; set; } internal PropertyInfo ViewModelProperty { get; set; } internal List<string> ValidationResult { get; set; } } }
23.75
61
0.715789
[ "Apache-2.0" ]
kevin-mueller/Xamarin.AttributeValidation
Xamarin.Validation/Models/ValidationModel.cs
382
C#