content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.ComponentModel.DataAnnotations; using EPiServer.Core; using EPiServer.DataAbstraction; using EPiServer.DataAnnotations; namespace Boost.Seo.Ascend.Playground.Models.Pages { /// <summary> /// Used for campaign or landing pages, commonly used for pages linked in online advertising such as AdWords /// </summary> [SiteContentType( GUID = "DBED4258-8213-48DB-A11F-99C034172A54", GroupName = Global.GroupNames.Specialized)] [SiteImageUrl] public class LandingPage : SitePageData { [Display( GroupName = SystemTabNames.Content, Order=310)] [CultureSpecific] public virtual ContentArea MainContentArea { get; set; } public override void SetDefaultValues(ContentType contentType) { base.SetDefaultValues(contentType); HideSiteFooter = true; HideSiteHeader = true; } } }
29.15625
112
0.666667
[ "MIT" ]
mariajemaria/Boost.Seo.Ascend.Playground
Boost.Seo.Ascend.Playground/Models/Pages/LandingPage.cs
933
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using MAVN.Common.Encryption; using MAVN.Common.MsSql; using MAVN.Service.CustomerProfile.Domain.Enums; using MAVN.Service.CustomerProfile.Domain.Models; using MAVN.Service.CustomerProfile.Domain.Repositories; using MAVN.Service.CustomerProfile.MsSqlRepositories.Entities; using Microsoft.EntityFrameworkCore; namespace MAVN.Service.CustomerProfile.MsSqlRepositories.Repositories { public class AdminProfileRepository : IAdminProfileRepository { private readonly MsSqlContextFactory<CustomerProfileContext> _contextFactory; private readonly IMapper _mapper; private readonly IEncryptionService _encryptionService; public AdminProfileRepository( MsSqlContextFactory<CustomerProfileContext> contextFactory, IMapper mapper, IEncryptionService encryptionService) { _contextFactory = contextFactory; _mapper = mapper; _encryptionService = encryptionService; } public async Task<IReadOnlyList<AdminProfile>> GetAllAsync() { using (var context = _contextFactory.CreateDataContext()) { var entities = await context.AdminProfiles.ToListAsync(); return entities .Select(entity => _mapper.Map<AdminProfile>(_encryptionService.Decrypt(entity))) .ToList(); } } public async Task<IReadOnlyList<AdminProfile>> GetAsync(IReadOnlyList<Guid> identifiers) { using (var context = _contextFactory.CreateDataContext()) { var entities = await context.AdminProfiles .Where(entity => identifiers.Contains(entity.AdminId)) .ToListAsync(); return entities .Select(entity => _mapper.Map<AdminProfile>(_encryptionService.Decrypt(entity))) .ToList(); } } public async Task<AdminProfile> GetByIdAsync(Guid adminId) { using (var context = _contextFactory.CreateDataContext()) { var entity = await context.AdminProfiles.FindAsync(adminId); return entity != null ? _mapper.Map<AdminProfile>(_encryptionService.Decrypt(entity)) : null; } } public async Task<AdminProfileErrorCodes> InsertAsync(AdminProfile adminProfile) { using (var context = _contextFactory.CreateDataContext()) { var entity = await context.AdminProfiles.FindAsync(adminProfile.AdminId); if (entity != null) return AdminProfileErrorCodes.AdminProfileAlreadyExists; entity = _mapper.Map<AdminProfileEntity>(adminProfile); entity = _encryptionService.Encrypt(entity); context.AdminProfiles.Add(entity); await context.SaveChangesAsync(); } return AdminProfileErrorCodes.None; } public async Task<AdminProfileErrorCodes> UpdateAsync(AdminProfile adminProfile) { using (var context = _contextFactory.CreateDataContext()) { var entity = await context.AdminProfiles.FindAsync(adminProfile.AdminId); if (entity == null) return AdminProfileErrorCodes.AdminProfileDoesNotExist; _encryptionService.Decrypt(entity); entity.Update(adminProfile); _encryptionService.Encrypt(entity); await context.SaveChangesAsync(); } return AdminProfileErrorCodes.None; } public async Task DeleteAsync(Guid adminId) { using (var context = _contextFactory.CreateDataContext()) { var entity = await context.AdminProfiles.FindAsync(adminId); if (entity == null) return; using (var transaction = context.Database.BeginTransaction()) { var archiveEntity = new AdminProfileArchiveEntity(entity); context.AdminProfilesArchive.Add(archiveEntity); context.AdminProfiles.Remove(entity); await context.SaveChangesAsync(); transaction.Commit(); } } } public async Task<(AdminProfileErrorCodes error, bool wasVerfiedBefore)> SetEmailVerifiedAsync(Guid adminId) { using (var context = _contextFactory.CreateDataContext()) { var entity = await context.AdminProfiles .IgnoreQueryFilters() .FirstOrDefaultAsync(c => c.AdminId == adminId); if (entity == null) return (AdminProfileErrorCodes.AdminProfileDoesNotExist, false); var wasEmailPreviouslyVerified = entity.WasEmailEverVerified; if (entity.IsEmailVerified) return (AdminProfileErrorCodes.AdminProfileEmailAlreadyVerified, wasEmailPreviouslyVerified); entity.IsEmailVerified = true; entity.WasEmailEverVerified = true; await context.SaveChangesAsync(); return (AdminProfileErrorCodes.None, wasEmailPreviouslyVerified); } } } }
34.7125
116
0.60731
[ "MIT" ]
IliyanIlievPH/MAVN.Service.CustomerProfile
src/MAVN.Service.CustomerProfile.MsSqlRepositories/Repositories/AdminProfileRepository.cs
5,554
C#
using Microsoft.SharePoint; using System; using System.Linq; namespace TITcs.SharePoint.Commons.Extensions { public static class SPSiteExtensions { /// <summary> /// Run code with elevated privileges onto the site. /// </summary> /// <param name="site">The current site.</param> /// <param name="codeToRunElevated">Code to run elevated.</param> public static void RunWithElevatedPrivileges(this SPSite site, Action<SPSite> codeToRunElevated) { var siteId = site.ID; SPSecurity.RunWithElevatedPrivileges(() => { using (var newSite = new SPSite(siteId)) { codeToRunElevated(newSite); } }); } /// <summary> /// Activate the specified feature at the web context. /// </summary> /// <param name="site">Site context in which to activate the feature.</param> /// <param name="guid">ID of the feature to activate.</param> public static void ActivateFeature(this SPSite site, string guid) { var featureId = new Guid(guid); if (site.Features.Cast<SPFeature>().Any(f => f.DefinitionId == featureId)) { site.Features.Add(featureId, true); } } } }
31.627907
104
0.558088
[ "MIT" ]
TITcs/TITcs.SharePoint.Commons
src/TITcs.SharePoint.Commons/Extensions/SPSiteExtensions.cs
1,362
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the chime-2018-05-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Chime.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Chime.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for CreateMeeting operation /// </summary> public class CreateMeetingResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { CreateMeetingResponse response = new CreateMeetingResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Meeting", targetDepth)) { var unmarshaller = MeetingUnmarshaller.Instance; response.Meeting = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException")) { return BadRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ForbiddenException")) { return ForbiddenExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceLimitExceededException")) { return ResourceLimitExceededExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceFailureException")) { return ServiceFailureExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException")) { return ServiceUnavailableExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottledClientException")) { return ThrottledClientExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("UnauthorizedClientException")) { return UnauthorizedClientExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonChimeException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static CreateMeetingResponseUnmarshaller _instance = new CreateMeetingResponseUnmarshaller(); internal static CreateMeetingResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateMeetingResponseUnmarshaller Instance { get { return _instance; } } } }
41.164179
188
0.636331
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Chime/Generated/Model/Internal/MarshallTransformations/CreateMeetingResponseUnmarshaller.cs
5,516
C#
//------------------------------------------------------------------------------ // <auto-generated>This code was generated by LLBLGen Pro v5.6.</auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; namespace EFCore.Bencher.EntityClasses { /// <summary>Class which represents the entity 'SalesOrderDetail'.</summary> public partial class SalesOrderDetail : CommonEntityBase { /// <summary>Method called from the constructor</summary> partial void OnCreated(); /// <summary>Initializes a new instance of the <see cref="SalesOrderDetail"/> class.</summary> public SalesOrderDetail() : base() { OnCreated(); } /// <summary>Gets or sets the CarrierTrackingNumber field. </summary> public System.String CarrierTrackingNumber { get; set; } /// <summary>Gets or sets the LineTotal field. </summary> public System.Decimal LineTotal { get; set; } /// <summary>Gets or sets the ModifiedDate field. </summary> public System.DateTime ModifiedDate { get; set; } /// <summary>Gets or sets the OrderQty field. </summary> public System.Int16 OrderQty { get; set; } /// <summary>Gets or sets the ProductId field. </summary> public System.Int32 ProductId { get; set; } /// <summary>Gets or sets the Rowguid field. </summary> public System.Guid Rowguid { get; set; } /// <summary>Gets or sets the SalesOrderDetailId field. </summary> public System.Int32 SalesOrderDetailId { get; set; } /// <summary>Gets or sets the SalesOrderId field. </summary> public System.Int32 SalesOrderId { get; set; } /// <summary>Gets or sets the SpecialOfferId field. </summary> public System.Int32 SpecialOfferId { get; set; } /// <summary>Gets or sets the UnitPrice field. </summary> public System.Decimal UnitPrice { get; set; } /// <summary>Gets or sets the UnitPriceDiscount field. </summary> public System.Decimal UnitPriceDiscount { get; set; } /// <summary>Represents the navigator which is mapped onto the association 'SalesOrderDetail.SalesOrderHeader - SalesOrderHeader.SalesOrderDetails (m:1)'</summary> public virtual SalesOrderHeader SalesOrderHeader { get; set; } /// <summary>Represents the navigator which is mapped onto the association 'SalesOrderDetail.SpecialOfferProduct - SpecialOfferProduct.SalesOrderDetails (m:1)'</summary> public virtual SpecialOfferProduct SpecialOfferProduct { get; set; } } }
49.979592
171
0.686811
[ "MIT" ]
FransBouma/RawDataAccessBencher
EFCore/Model/EntityClasses/SalesOrderDetail.cs
2,451
C#
namespace T3000.Forms { partial class HolidaysForm { /// <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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(HolidaysForm)); this.saveButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.clearSelectedRowButton = new System.Windows.Forms.Button(); this.view = new T3000.Controls.TView(); this.NumberColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.DescriptionColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.AutoManualColumn = new System.Windows.Forms.DataGridViewButtonColumn(); this.ValueColumn = new System.Windows.Forms.DataGridViewButtonColumn(); this.LabelColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.HolidaysColumn = new System.Windows.Forms.DataGridViewButtonColumn(); ((System.ComponentModel.ISupportInitialize)(this.view)).BeginInit(); this.SuspendLayout(); // // saveButton // resources.ApplyResources(this.saveButton, "saveButton"); this.saveButton.Name = "saveButton"; this.saveButton.UseVisualStyleBackColor = true; this.saveButton.Click += new System.EventHandler(this.Save); // // cancelButton // resources.ApplyResources(this.cancelButton, "cancelButton"); this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Name = "cancelButton"; this.cancelButton.UseVisualStyleBackColor = true; this.cancelButton.Click += new System.EventHandler(this.Cancel); // // clearSelectedRowButton // resources.ApplyResources(this.clearSelectedRowButton, "clearSelectedRowButton"); this.clearSelectedRowButton.Name = "clearSelectedRowButton"; this.clearSelectedRowButton.UseVisualStyleBackColor = true; this.clearSelectedRowButton.Click += new System.EventHandler(this.ClearSelectedRow); // // view // this.view.AllowUserToAddRows = false; this.view.AllowUserToDeleteRows = false; resources.ApplyResources(this.view, "view"); this.view.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; this.view.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.view.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.NumberColumn, this.DescriptionColumn, this.AutoManualColumn, this.ValueColumn, this.LabelColumn, this.HolidaysColumn}); this.view.MultiSelect = false; this.view.Name = "view"; // // NumberColumn // this.NumberColumn.FillWeight = 55F; resources.ApplyResources(this.NumberColumn, "NumberColumn"); this.NumberColumn.Name = "NumberColumn"; this.NumberColumn.ReadOnly = true; // // DescriptionColumn // this.DescriptionColumn.FillWeight = 150F; resources.ApplyResources(this.DescriptionColumn, "DescriptionColumn"); this.DescriptionColumn.Name = "DescriptionColumn"; // // AutoManualColumn // resources.ApplyResources(this.AutoManualColumn, "AutoManualColumn"); this.AutoManualColumn.Name = "AutoManualColumn"; // // ValueColumn // resources.ApplyResources(this.ValueColumn, "ValueColumn"); this.ValueColumn.Name = "ValueColumn"; this.ValueColumn.Resizable = System.Windows.Forms.DataGridViewTriState.True; // // LabelColumn // resources.ApplyResources(this.LabelColumn, "LabelColumn"); this.LabelColumn.Name = "LabelColumn"; // // HolidaysColumn // resources.ApplyResources(this.HolidaysColumn, "HolidaysColumn"); this.HolidaysColumn.Name = "HolidaysColumn"; // // HolidaysForm // this.AcceptButton = this.saveButton; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cancelButton; this.Controls.Add(this.clearSelectedRowButton); this.Controls.Add(this.cancelButton); this.Controls.Add(this.saveButton); this.Controls.Add(this.view); this.Name = "HolidaysForm"; ((System.ComponentModel.ISupportInitialize)(this.view)).EndInit(); this.ResumeLayout(false); } #endregion private T3000.Controls.TView view; private System.Windows.Forms.Button saveButton; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Button clearSelectedRowButton; private System.Windows.Forms.DataGridViewTextBoxColumn NumberColumn; private System.Windows.Forms.DataGridViewTextBoxColumn DescriptionColumn; private System.Windows.Forms.DataGridViewButtonColumn AutoManualColumn; private System.Windows.Forms.DataGridViewButtonColumn ValueColumn; private System.Windows.Forms.DataGridViewTextBoxColumn LabelColumn; private System.Windows.Forms.DataGridViewButtonColumn HolidaysColumn; } }
44.791946
144
0.620467
[ "MIT" ]
Fance/T3000_CrossPlatform
T3000/Forms/HolidaysForm/HolidaysForm.Designer.cs
6,676
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("XamarinFormsGoogleDriveAPI.Droid")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("XamarinFormsGoogleDriveAPI.Droid")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] // Add some common permissions, these can be removed if not needed [assembly: UsesPermission(Android.Manifest.Permission.Internet)] [assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
37.457143
84
0.762014
[ "MIT" ]
Dineshbala1/GoogleDriveAPI-XamarinForms
XamarinFormsGoogleDriveAPI/XamarinFormsGoogleDriveAPI.Droid/Properties/AssemblyInfo.cs
1,314
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Axe.Windows.Automation; using Axe.Windows.Core.Bases; using Axe.Windows.Core.Enums; using Axe.Windows.Core.Results; using Axe.Windows.Core.Types; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; namespace Axe.Windows.AutomationTests { [TestClass()] public class ScanResultsAssemblerTests { ScanResultsAssembler assembler = new ScanResultsAssembler(); [TestMethod] [Timeout(2000)] public void AssembleScanResultsFromElement_AssemblesErrors() { A11yElement element = GenerateA11yElementWithChild(); List<RuleId> expectedRuleIDs = GetExpectedRuleIDs(); ElementInfo expectedParentInfo = new ElementInfo { Patterns = element.Patterns.ConvertAll<string>(x => x.Name), Properties = null, }; ElementInfo expectedChildInfo = new ElementInfo { Patterns = null, Properties = element.Children[0].Properties.ToDictionary(p => p.Value.Name, p => p.Value.TextValue), }; var scanResults = assembler.AssembleScanResultsFromElement(element); var errors = scanResults.Errors.ToList(); // the first half of the results are from the parent element; the second half are from the child element // we'll separate them here to improve the clarity of later validations var parentErrors = errors.GetRange(0, errors.Count / 2); var childErrors = errors.GetRange(errors.Count / 2, errors.Count / 2); // there should be the proper number of errors Assert.AreEqual(8, errors.Count); Assert.AreEqual(8, scanResults.ErrorCount); // the patterns for the parent errors should be as expected foreach (var error in parentErrors) { Assert.AreEqual(expectedParentInfo.Properties, error.Element.Properties); Assert.IsTrue(expectedParentInfo.Patterns.SequenceEqual(error.Element.Patterns)); } // the patterns for the child errors and their parents should be as expected foreach (var error in childErrors) { Assert.AreEqual(expectedChildInfo.Patterns, error.Element.Patterns); Assert.IsTrue(expectedChildInfo.Properties.SequenceEqual(error.Element.Properties)); Assert.AreEqual(expectedParentInfo.Properties, error.Element.Parent.Properties); Assert.IsTrue(expectedParentInfo.Patterns.SequenceEqual(error.Element.Parent.Patterns)); } // the errors should have the correct rule results for (int x = 0; x < errors.Count; x++) { Assert.AreEqual(Rules.Rules.All[expectedRuleIDs[x]], errors[x].Rule, $"Error number {x}"); } // the elements from the child element's parents are the same as the elements from the parent elements for (int x = 0; x < errors.Count / 2; x++) { Assert.AreEqual(parentErrors[x].Element, childErrors[x].Element.Parent, $"Error number {x}"); } } [TestMethod] [Timeout(2000)] public void AssembleScanResultsFromElement_AssemblesNoErrors() { A11yElement element = UnitTestSharedLibrary.Utility.LoadA11yElementsFromJSON("Snapshots/MonsterEdit.snapshot"); var scanResults = assembler.AssembleScanResultsFromElement(element); // if there were no rule violations, there should be no results. Assert.AreEqual(0, scanResults.ErrorCount); Assert.AreEqual(0, scanResults.Errors.Count()); } [TestMethod] [Timeout(1000)] public void AssembleScanResults_ThrowsArgumentNullException_NullErrors() { A11yElement element = new A11yElement() { ScanResults = null }; Assert.ThrowsException<ArgumentNullException>(() => ScanResultsAssembler.AssembleErrorsFromElement(null, element, null)); } [TestMethod] [Timeout(1000)] public void AssembleScanResults_ThrowsArgumentNullException_NullElement() { var errors = new List<Automation.ScanResult>(); Assert.ThrowsException<ArgumentNullException>(() => ScanResultsAssembler.AssembleErrorsFromElement(errors, null, null)); } [TestMethod] [Timeout(1000)] public void AssembleScanResults_ThrowsKeyNotFoundException_BadResults() { A11yElement element = GenerateA11yElementWithBadScanResults(); var errors = new List<Automation.ScanResult>(); Assert.ThrowsException<KeyNotFoundException>(() => ScanResultsAssembler.AssembleErrorsFromElement(errors, element, null)); } private List<RuleId> GetExpectedRuleIDs() => new List<RuleId>() { RuleId.BoundingRectangleCompletelyObscuresContainer, RuleId.ControlViewButtonStructure , RuleId.LandmarkNoDuplicateContentInfo , RuleId.BoundingRectangleCompletelyObscuresContainer, RuleId.BoundingRectangleCompletelyObscuresContainer, RuleId.ControlViewButtonStructure , RuleId.LandmarkNoDuplicateContentInfo , RuleId.BoundingRectangleCompletelyObscuresContainer, }; private A11yElement GenerateA11yElementWithChild() { A11yElement element = new A11yElement() { ScanResults = new Core.Results.ScanResults(), Children = new List<A11yElement>(), }; element.Properties = null; element.Patterns = GetFillerPatterns(); element.ScanResults.Items.AddRange(GetFillerScanResults()); element.Children.Add(GenerateA11yElementWithoutChild()); return element; } private A11yElement GenerateA11yElementWithoutChild() { A11yElement element = new A11yElement() { ScanResults = new Core.Results.ScanResults() }; element.Properties = GetFillerProperties(); element.Patterns = null; element.ScanResults.Items.AddRange(GetFillerScanResults()); return element; } private A11yElement GenerateA11yElementWithBadScanResults() { A11yElement element = new A11yElement() { ScanResults = new Core.Results.ScanResults() }; element.ScanResults.Items.AddRange(GetBadScanResults()); return element; } private Dictionary<int, A11yProperty> GetFillerProperties() => new Dictionary<int, A11yProperty>() { { PropertyType.UIA_AriaRolePropertyId, new A11yProperty(PropertyType.UIA_AriaRolePropertyId, "Nice property")}, { PropertyType.UIA_CulturePropertyId, new A11yProperty(PropertyType.UIA_CulturePropertyId, "A culture")}, { PropertyType.UIA_DescribedByPropertyId, new A11yProperty(PropertyType.UIA_DescribedByPropertyId, "Descriptor")}, }; private List<A11yPattern> GetFillerPatterns() => new List<A11yPattern>() { new A11yPattern() { Name = "Pat" }, new A11yPattern() { Name = "Tern" }, }; private List<Core.Results.ScanResult> GetBadScanResults() => new List<Core.Results.ScanResult>() { new Core.Results.ScanResult() { Items = new List<RuleResult>() { new RuleResult() { Status = ScanStatus.Uncertain, Rule = RuleId.BoundingRectangleNotNull }, new RuleResult() { Status = ScanStatus.Fail, Rule = RuleId.Indecisive }, new RuleResult() { Status = ScanStatus.NoResult, Rule = RuleId.ListItemSiblingsUnique }, new RuleResult() { Status = ScanStatus.Fail, Rule = RuleId.BoundingRectangleCompletelyObscuresContainer }, } } }; private List<Core.Results.ScanResult> GetFillerScanResults() => new List<Core.Results.ScanResult>() { new Core.Results.ScanResult() { Items = new List<RuleResult>() { new RuleResult() { Status = ScanStatus.Pass, Rule = RuleId.Indecisive }, new RuleResult() { Status = ScanStatus.Uncertain, Rule = RuleId.BoundingRectangleNotNull }, new RuleResult() { Status = ScanStatus.NoResult, Rule = RuleId.ListItemSiblingsUnique }, new RuleResult() { Status = ScanStatus.Fail, Rule = RuleId.BoundingRectangleCompletelyObscuresContainer }, } }, new Core.Results.ScanResult() { Items = new List<RuleResult>() { new RuleResult() { Status = ScanStatus.Fail, Rule = RuleId.ControlViewButtonStructure }, new RuleResult() { Status = ScanStatus.Pass, Rule = RuleId.TypicalTreeStructureRaw }, new RuleResult() { Status = ScanStatus.Fail, Rule = RuleId.LandmarkNoDuplicateContentInfo }, new RuleResult() { Status = ScanStatus.NoResult, Rule = RuleId.PatternsSupportedByControlType }, new RuleResult() { Status = ScanStatus.Fail, Rule = RuleId.BoundingRectangleCompletelyObscuresContainer }, } } }; } }
44.895928
135
0.61288
[ "MIT" ]
Bhaskers-Blu-Org2/axe-windows
src/AutomationTests/ScanResultsAssemblerTests.cs
9,704
C#
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved using System; using System.Threading.Tasks; using Windows.ApplicationModel.Activation; using Windows.ApplicationModel; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using SDKTemplateCS; namespace ToastsSampleCS { public partial class App { MainPage mainPage = null; public App() { InitializeComponent(); this.Suspending += new SuspendingEventHandler(OnSuspending); } async protected void OnSuspending(object sender, SuspendingEventArgs args) { SuspendingDeferral deferral = args.SuspendingOperation.GetDeferral(); await SuspensionManager.SaveAsync(); deferral.Complete(); } async protected override void OnLaunched(LaunchActivatedEventArgs args) { if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Do an asynchronous restore await SuspensionManager.RestoreAsync(); } if (mainPage == null) { var rootFrame = new Frame(); rootFrame.Navigate(typeof(MainPage)); Window.Current.Content = rootFrame; mainPage = rootFrame.Content as MainPage; mainPage.RootNamespace = this.GetType().Namespace; } if (args.Arguments != "") { (mainPage.ScenariosFrame.Content as ScenarioList).SelectedIndex = 4; (mainPage.InputFrame.Content as ScenarioInput5).LaunchedFromToast(args.Arguments); } Window.Current.Activate(); } } }
34.372881
99
0.602071
[ "MIT" ]
mfloresn90/CSharpSources
Toast notifications sample/C#/App.xaml.cs
2,028
C#
using GranSteL.Chatbot.Services; using MailRu.Marusia.Models; using MailRu.Marusia.Models.Input; namespace GranSteL.Chatbot.Messengers.Marusia { public interface IMarusiaService : IMessengerService<InputModel, OutputModel> { } }
24.2
81
0.785124
[ "MIT" ]
granstel/Templates.Chatbot
src/GranSteL.Chatbot.Messengers.Marusia/IMarusiaService.cs
244
C#
using System; using System.Windows; using VTility.Logic; using System.Linq; namespace VTility.Pages { public partial class PageTimer : BasePage { public PageTimer() { InitializeComponent(); } public UtilTimer SelectedTimer { get => UtilTimer.Current; set { UtilTimer.Current = value; } } public override void LoadSettings() { //TextBoxCountdown.Text = LoadPageSetting("lastCountdownValue") as string; //TextBoxCountdown.Text = UtilTimer.Current.countdownValue.ToString(); // Loads and displays all timers from registry //if (selectedTimer.countdownAction != null) // TextBoxCountdown.Text = LoadPageSetting(selectedTimer.countdownAction.ToString()) as string; // TODO Change icon //IconTimedActionType.Source = FindResource("") } public override void SaveSettings() { UtilTimer.SaveLast(SelectedTimer.Name); foreach(var cd in UtilTimer.AllCountdowns) cd.Save(); } private void button_play_click(object sender, RoutedEventArgs e) { Console.WriteLine("Playing/Pausing"); SelectedTimer.PlayPause(); } private void button_stop_click(object sender, RoutedEventArgs e) { if (SelectedTimer.HasTimeLeft) { Console.WriteLine("Stopping/Resetting"); SelectedTimer.ResetCountdown(); } } private void OnSelectionChange(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { var timerName = ComboSelectedTimer.SelectedItem.ToString(); var res = UtilTimer.AllCountdowns.Where((arg) => arg.Name.Equals(timerName)); foreach(var a in res) { Console.WriteLine("Setting new timer to current: " + a.Name); UtilTimer.Current = a; } } } }
31.955882
111
0.552692
[ "Apache-2.0" ]
vincelord/TimeR
VTility/Pages/PageTimer.xaml.cs
2,175
C#
using GServer.Messages; namespace GServer.Plugins.Matchmaking { public class MatchmakingManager<TGame, TAccountModel> : RoomManager<TGame, TAccountModel, MatchmakingRoom<TAccountModel, TGame>> where TAccountModel : AccountModel, new() where TGame : Game<TAccountModel>, new() { private Matchmaking<TAccountModel> _matchmaking; public MatchmakingManager(Matchmaking<TAccountModel> matchmaking) { _matchmaking = matchmaking; _matchmaking.RoomCreated += ManageRoom; } private void ManageRoom(TAccountModel[] clients) { var room = new MatchmakingRoom<TAccountModel, TGame>(clients); room.Send = (msg, con) => _host.Send(msg, con); room.InitRoom(); lock (_rooms) { _rooms.Add(room.RoomToken, room); } foreach (var player in room.Players) { _host.Send(new Message((short) MatchmakingMessages.GameFound, Mode.Reliable, room.RoomToken), player.Connection); } room.RoomClosed += () => { lock (_rooms) { foreach (var player in room.Players) { if (_rooms.ContainsKey(player.Connection.Token)) { _rooms.Remove(player.Connection.Token); } } } }; } } }
36.55
109
0.547196
[ "MIT" ]
TBringerOHW/GServer
GServer/GServer.Plugins/Matchmaking/MatchmakingManager.cs
1,464
C#
namespace SmartStore.Core.Domain.Catalog { /// <summary> /// Represents a backorder mode /// </summary> public enum BackorderMode { /// <summary> /// No backorders /// </summary> NoBackorders = 0, /// <summary> /// Allow qty below 0 /// </summary> AllowQtyBelow0 = 1, /// <summary> /// Allow qty below 0 and notify customer /// </summary> AllowQtyBelow0AndNotifyCustomer = 2, } }
22.727273
49
0.512
[ "MIT" ]
jenmcquade/csharp-snippets
SmartStoreNET-3.x/src/Libraries/SmartStore.Core/Domain/Catalog/BackorderMode.cs
500
C#
using Microsoft.IdentityModel.Clients.ActiveDirectory; using Microsoft.Rest; using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; namespace PipServices3.Azure.Metrics { public class CosmosDbClientCredentials : ServiceClientCredentials { private string _tenantId = null; private string _clientId = null; private string _clientSecret = null; private string _resource = "https://management.core.windows.net/"; private AuthenticationResult LatestAuthenticationResult { get; set; } public CosmosDbClientCredentials(string clientId, string clientSecret, string tenantId) { _tenantId = tenantId; _clientId = clientId; _clientSecret = clientSecret; } public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException("request"); } var bearerToken = await GetBearerTokenAsync(); if (bearerToken == null) { throw new InvalidOperationException("Token cannot be null"); } request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); await base.ProcessHttpRequestAsync(request, cancellationToken); } private async Task<string> GetBearerTokenAsync() { if (LatestAuthenticationResult?.ExpiresOn > DateTime.UtcNow) { return await Task.FromResult(LatestAuthenticationResult.AccessToken); } LoggerCallbackHandler.UseDefaultLogging = false; var authenticationContext = new AuthenticationContext($"https://login.windows.net/{_tenantId}"); var credential = new ClientCredential(_clientId, _clientSecret); LatestAuthenticationResult = await authenticationContext.AcquireTokenAsync(_resource, credential); if (LatestAuthenticationResult == null) { throw new InvalidOperationException("Failed to obtain the token"); } return await Task.FromResult(LatestAuthenticationResult.AccessToken); } } }
34.957143
123
0.658357
[ "MIT" ]
pip-services-dotnet/pip-services-azure-dotnet
src/Metrics/CosmosDbClientCredentials.cs
2,449
C#
/* * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * See https://github.com/openiddict/openiddict-core for more information concerning * the license and the contributors participating to this project. */ using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.ModelConfiguration; using System.Text; using OpenIddict.EntityFramework.Models; namespace OpenIddict.EntityFramework { /// <summary> /// Defines a relational mapping for the Token entity. /// </summary> /// <typeparam name="TToken">The type of the Token entity.</typeparam> /// <typeparam name="TApplication">The type of the Application entity.</typeparam> /// <typeparam name="TAuthorization">The type of the Authorization entity.</typeparam> /// <typeparam name="TKey">The type of the Key entity.</typeparam> [EditorBrowsable(EditorBrowsableState.Never)] public class OpenIddictTokenConfiguration<TToken, TApplication, TAuthorization, TKey> : EntityTypeConfiguration<TToken> where TToken : OpenIddictToken<TKey, TApplication, TAuthorization> where TApplication : OpenIddictApplication<TKey, TAuthorization, TToken> where TAuthorization : OpenIddictAuthorization<TKey, TApplication, TToken> where TKey : IEquatable<TKey> { public OpenIddictTokenConfiguration() { // Note: unlike Entity Framework Core 1.x/2.x, Entity Framework 6.x // always throws an exception when using generic types as entity types. // To ensure a better exception is thrown, a manual check is made here. if (typeof(TToken).IsGenericType) { throw new InvalidOperationException(new StringBuilder() .AppendLine("The token entity cannot be a generic type.") .Append("Consider creating a non-generic derived class.") .ToString()); } // Warning: optional foreign keys MUST NOT be added as CLR properties because // Entity Framework would throw an exception due to the TKey generic parameter // being non-nullable when using value types like short, int, long or Guid. HasKey(token => token.Id); Property(token => token.ConcurrencyToken) .HasMaxLength(50) .IsConcurrencyToken(); // Warning: the index on the ReferenceId property MUST NOT be declared as // a unique index, as Entity Framework 6.x doesn't support creating indexes // with null-friendly WHERE conditions, unlike Entity Framework Core 1.x/2.x. Property(token => token.ReferenceId) .HasMaxLength(100) .HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute())); Property(token => token.Status) .HasMaxLength(25) .IsRequired(); Property(token => token.Subject) .HasMaxLength(450); Property(token => token.Type) .HasMaxLength(25) .IsRequired(); ToTable("OpenIddictTokens"); } } }
43.763158
123
0.653939
[ "Apache-2.0" ]
ajfleming1/openiddict-core
src/OpenIddict.EntityFramework/Configurations/OpenIddictTokenConfiguration.cs
3,328
C#
/*********************************************************************\ *This file is part of My Nes * *A Nintendo Entertainment System Emulator. * * * *Copyright (C) 2009 - 2010 Ala Hadid * *E-mail: mailto:ahdsoftwares@hotmail.com * * * *My Nes is free software: you can redistribute it and/or modify * *it under the terms of the GNU General Public License as published by * *the Free Software Foundation, either version 3 of the License, or * *(at your option) any later version. * * * *My Nes 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 General Public License for more details. * * * *You should have received a copy of the GNU General Public License * *along with this program. If not, see <http://www.gnu.org/licenses/>.* \*********************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyNes.Nes { //[Serializable ()] /// <summary> /// The 6502 /// </summary> public class CPU { /// <summary> /// The 6502 /// </summary> /// <param name="Nes">The nes device</param> public CPU(NES Nes) { _Nes = Nes; MEM = Nes.Memory; } //Registers public byte REG_A = 0; public byte REG_X = 0; public byte REG_Y = 0; public byte REG_S = 0xFF; public ushort REG_PC = 0; //Flags public bool Flag_N = false; public bool Flag_V = false; public bool Flag_B = false; public bool Flag_D = false; public bool Flag_I = true; public bool Flag_Z = false; public bool Flag_C = false; /// <summary> /// IRQ Request ? /// </summary> public bool IRQRequest = false; /// <summary> /// NMI Request ? /// </summary> public bool NMIRequest = false; public bool DMA = false; //Clocks and timing stuff int CycleCounter = 0; //Others CPUMemory MEM; NES _Nes; byte OpCode = 0; /// <summary> /// Run the cpu looping /// </summary> public int Execute() { CycleCounter = 0; if (DMA) { DMA = false; return 512; } OpCode = MEM[REG_PC]; // We may not use both, but it's easier to grab them now byte arg1 = MEM[(ushort)(REG_PC + 1)]; byte arg2 = MEM[(ushort)(REG_PC + 2)]; byte M = 0xFF;//The value holder #region DO OPCODE switch (OpCode) { #region ADC case (0x61): M = IndirectX(arg1); ADC(M, 6, 2); break; case (0x65): M = ZeroPage(arg1); ADC(M, 3, 2); break; case (0x69): M = arg1; ADC(M, 2, 2); break; case (0x6D): M = Absolute(arg1, arg2); ADC(M, 4, 3); break; case (0x71): M = IndirectY(arg1, true); ADC(M, 5, 2); break; case (0x75): M = ZeroPageX(arg1); ADC(M, 4, 2); break; case (0x79): M = AbsoluteY(arg1, arg2, true); ADC(M, 4, 3); break; case (0x7D): M = AbsoluteX(arg1, arg2, true); ADC(M, 4, 3); break; #endregion #region AND case (0x21): M = IndirectX(arg1); AND(M, 6, 2); break; case (0x25): M = ZeroPage(arg1); AND(M, 3, 2); break; case (0x29): M = arg1; AND(M, 2, 2); break; case (0x2D): M = Absolute(arg1, arg2); AND(M, 4, 3); break; case (0x31): M = IndirectY(arg1, true); AND(M, 5, 2); break; case (0x35): M = ZeroPageX(arg1); AND(M, 4, 2); break; case (0x39): M = AbsoluteY(arg1, arg2, true); AND(M, 4, 3); break; case (0x3D): M = AbsoluteX(arg1, arg2, true); AND(M, 4, 3); break; #endregion #region ASL case (0x06): M = ZeroPage(arg1); ZeroPageWrite(arg1, ASL(M)); CycleCounter += 5; REG_PC += 2; break; case (0x0A): M = REG_A; REG_A = ASL(M); CycleCounter += 2; REG_PC += 1; break; case (0x0E): M = Absolute(arg1, arg2); AbsoluteWrite(arg1, arg2, ASL(M)); CycleCounter += 6; REG_PC += 3; break; case (0x16): M = ZeroPageX(arg1); ZeroPageXWrite(arg1, ASL(M)); CycleCounter += 6; REG_PC += 2; break; case (0x1E): M = AbsoluteX(arg1, arg2, false); AbsoluteXWrite(arg1, arg2, ASL(M)); CycleCounter += 7; REG_PC += 3; break; #endregion #region BCC case (0x90): Branch(!Flag_C, arg1); break; #endregion #region BCS case (0xb0): Branch(Flag_C, arg1); break; #endregion #region BEQ case (0xf0): Branch(Flag_Z, arg1); break; #endregion #region BIT case (0x24): M = ZeroPage(arg1); BIT(M, 3, 2); break; case (0x2c): M = Absolute(arg1, arg2); BIT(M, 4, 3); break; #endregion #region BMI case (0x30): Branch(Flag_N, arg1); break; #endregion #region BNE case (0xd0): Branch(!Flag_Z, arg1); break; #endregion #region BPL case (0x10): Branch(!Flag_N, arg1); break; #endregion #region BRK case (0x00): BRK(); break; #endregion #region BVC case (0x50): Branch(!Flag_V, arg1); break; #endregion #region BVS case (0x70): Branch(Flag_V, arg1); break; #endregion #region CLC case (0x18): CLC(); break; #endregion #region CLD case (0xd8): CLD(); break; #endregion #region CLI case (0x58): CLI(); break; #endregion #region CLV case (0xb8): CLV(); break; #endregion #region CMP case (0xC1): M = IndirectX(arg1); CMP(M, 6, 2); break; case (0xC5): M = ZeroPage(arg1); CMP(M, 3, 2); break; case (0xC9): M = arg1; CMP(M, 2, 2); break; case (0xCD): M = Absolute(arg1, arg2); CMP(M, 4, 3); break; case (0xd1): M = IndirectY(arg1, true); CMP(M, 5, 2); break; case (0xd5): M = ZeroPageX(arg1); CMP(M, 4, 2); break; case (0xd9): M = AbsoluteY(arg1, arg2, true); CMP(M, 4, 3); break; case (0xdd): M = AbsoluteX(arg1, arg2, true); CMP(M, 4, 3); break; #endregion #region CPX case (0xE0): M = arg1; CPX(M, 2, 2); break; case (0xE4): M = ZeroPage(arg1); CPX(M, 3, 2); break; case (0xEC): M = Absolute(arg1, arg2); CPX(M, 4, 3); break; #endregion #region CPY case (0xc0): M = arg1; CPY(M, 2, 2); break; case (0xc4): M = ZeroPage(arg1); CPY(M, 3, 2); break; case (0xcc): M = Absolute(arg1, arg2); CPY(M, 4, 3); break; #endregion #region DEC case (0xc6): M = ZeroPage(arg1); ZeroPageWrite(arg1, DEC(M)); CycleCounter += 5; REG_PC += 2; break; case (0xce): M = Absolute(arg1, arg2); AbsoluteWrite(arg1, arg2, DEC(M)); CycleCounter += 6; REG_PC += 3; break; case (0xd6): M = ZeroPageX(arg1); ZeroPageXWrite(arg1, DEC(M)); CycleCounter += 6; REG_PC += 2; break; case (0xde): M = AbsoluteX(arg1, arg2, false); AbsoluteXWrite(arg1, arg2, DEC(M)); CycleCounter += 7; REG_PC += 3; break; #endregion #region DEX case (0xca): DEX(); break; #endregion #region DEY case (0x88): DEY(); break; #endregion #region EOR case (0x41): M = IndirectX(arg1); EOR(M, 6, 2); break; case (0x45): M = ZeroPage(arg1); EOR(M, 3, 2); break; case (0x49): M = arg1; EOR(M, 2, 2); break; case (0x4d): M = Absolute(arg1, arg2); EOR(M, 4, 3); break; case (0x51): M = IndirectY(arg1, true); EOR(M, 5, 2); break; case (0x55): M = ZeroPageX(arg1); EOR(M, 4, 2); break; case (0x59): M = AbsoluteY(arg1, arg2, true); EOR(M, 4, 3); break; case (0x5d): M = AbsoluteX(arg1, arg2, true); EOR(M, 4, 3); break; #endregion #region INC case (0xe6): M = ZeroPage(arg1); ZeroPageWrite(arg1, INC(M)); CycleCounter += 5; REG_PC += 2; break; case (0xee): M = Absolute(arg1, arg2); AbsoluteWrite(arg1, arg2, INC(M)); CycleCounter += 6; REG_PC += 3; break; case (0xf6): M = ZeroPageX(arg1); ZeroPageXWrite(arg1, INC(M)); CycleCounter += 6; REG_PC += 2; break; case (0xfe): M = AbsoluteX(arg1, arg2, false); AbsoluteXWrite(arg1, arg2, INC(M)); CycleCounter += 7; REG_PC += 3; break; #endregion #region INX case (0xe8): INX(); break; #endregion #region INY case (0xc8): INY(); break; #endregion #region JMP case (0x4c): REG_PC = Read16((ushort)(REG_PC + 1)); CycleCounter += 3; break; case (0x6c): ushort myAddress = Read16((ushort)(REG_PC + 1)); if ((myAddress & 0x00FF) == 0x00FF) { REG_PC = MEM[myAddress]; myAddress &= 0xFF00; REG_PC |= (ushort)((MEM[myAddress]) << 8); } else REG_PC = Read16(myAddress); CycleCounter += 5; break; #endregion #region JSR case (0x20): JSR(arg1, arg2); break; #endregion #region LDA case (0xa1): REG_A = IndirectX(arg1); LDA(); CycleCounter += 6; REG_PC += 2; break; case (0xa5): REG_A = ZeroPage(arg1); CycleCounter += 3; REG_PC += 2; LDA(); break; case (0xa9): REG_A = arg1; CycleCounter += 2; REG_PC += 2; LDA(); break; case (0xad): REG_A = Absolute(arg1, arg2); CycleCounter += 4; REG_PC += 3; LDA(); break; case (0xb1): REG_A = IndirectY(arg1, true); CycleCounter += 5; REG_PC += 2; LDA(); break; case (0xb5): REG_A = ZeroPageX(arg1); CycleCounter += 4; REG_PC += 2; LDA(); break; case (0xb9): REG_A = AbsoluteY(arg1, arg2, true); CycleCounter += 4; REG_PC += 3; LDA(); break; case (0xbd): REG_A = AbsoluteX(arg1, arg2, true); CycleCounter += 4; REG_PC += 3; LDA(); break; #endregion #region LDX case (0xa2): REG_X = arg1; CycleCounter += 2; REG_PC += 2; LDX(); break; case (0xa6): REG_X = ZeroPage(arg1); CycleCounter += 3; REG_PC += 2; LDX(); break; case (0xae): REG_X = Absolute(arg1, arg2); CycleCounter += 4; REG_PC += 3; LDX(); break; case (0xb6): REG_X = ZeroPageY(arg1); CycleCounter += 4; REG_PC += 2; LDX(); break; case (0xbe): REG_X = AbsoluteY(arg1, arg2, true); CycleCounter += 4; REG_PC += 3; LDX(); break; #endregion #region LDY case (0xa0): REG_Y = arg1; CycleCounter += 2; REG_PC += 2; LDY(); break; case (0xa4): REG_Y = ZeroPage(arg1); CycleCounter += 3; REG_PC += 2; LDY(); break; case (0xac): REG_Y = Absolute(arg1, arg2); CycleCounter += 4; REG_PC += 3; LDY(); break; case (0xb4): REG_Y = ZeroPageX(arg1); CycleCounter += 4; REG_PC += 2; LDY(); break; case (0xbc): REG_Y = AbsoluteX(arg1, arg2, true); CycleCounter += 4; REG_PC += 3; LDY(); break; #endregion #region LSR case (0x46): M = ZeroPage(arg1); ZeroPageWrite(arg1, LSR(M)); CycleCounter += 5; REG_PC += 2; break; case (0x4a): M = REG_A; REG_A = LSR(M); CycleCounter += 2; REG_PC += 1; break; case (0x4e): M = Absolute(arg1, arg2); AbsoluteWrite(arg1, arg2, LSR(M)); CycleCounter += 6; REG_PC += 3; break; case (0x56): M = ZeroPageX(arg1); ZeroPageXWrite(arg1, LSR(M)); CycleCounter += 6; REG_PC += 2; break; case (0x5e): M = AbsoluteX(arg1, arg2, false); AbsoluteXWrite(arg1, arg2, LSR(M)); CycleCounter += 7; REG_PC += 3; break; #endregion #region NOP case (0xEA): NOP(); break; #endregion #region ORA case (0x01): M = IndirectX(arg1); ORA(M, 6, 2); break; case (0x05): M = ZeroPage(arg1); ORA(M, 3, 2); break; case (0x09): M = arg1; ORA(M, 2, 2); break; case (0x0d): M = Absolute(arg1, arg2); ORA(M, 4, 3); break; case (0x11): M = IndirectY(arg1, true); ORA(M, 5, 2); break; case (0x15): M = ZeroPageX(arg1); ORA(M, 4, 2); break; case (0x19): M = AbsoluteY(arg1, arg2, true); ORA(M, 4, 3); break; case (0x1d): M = AbsoluteX(arg1, arg2, true); ORA(M, 4, 3); break; #endregion #region PHA case (0x48): PHA(); break; #endregion #region PHP case (0x08): PHP(); break; #endregion #region PLA case (0x68): PLA(); break; #endregion #region PLP case (0x28): PLP(); break; #endregion #region ROL case (0x26): M = ZeroPage(arg1); ZeroPageWrite(arg1, ROL(M)); CycleCounter += 5; REG_PC += 2; break; case (0x2a): M = REG_A; REG_A = ROL(M); CycleCounter += 2; REG_PC += 1; break; case (0x2e): M = Absolute(arg1, arg2); AbsoluteWrite(arg1, arg2, ROL(M)); CycleCounter += 6; REG_PC += 3; break; case (0x36): M = ZeroPageX(arg1); ZeroPageXWrite(arg1, ROL(M)); CycleCounter += 6; REG_PC += 2; break; case (0x3e): M = AbsoluteX(arg1, arg2, false); AbsoluteXWrite(arg1, arg2, ROL(M)); CycleCounter += 7; REG_PC += 3; break; #endregion #region ROR case (0x66): M = ZeroPage(arg1); ZeroPageWrite(arg1, ROR(M)); CycleCounter += 5; REG_PC += 2; break; case (0x6a): M = REG_A; REG_A = ROR(M); CycleCounter += 2; REG_PC += 1; break; case (0x6e): M = Absolute(arg1, arg2); AbsoluteWrite(arg1, arg2, ROR(M)); CycleCounter += 6; REG_PC += 3; break; case (0x76): M = ZeroPageX(arg1); ZeroPageXWrite(arg1, ROR(M)); CycleCounter += 6; REG_PC += 2; break; case (0x7e): M = AbsoluteX(arg1, arg2, false); AbsoluteXWrite(arg1, arg2, ROR(M)); CycleCounter += 7; REG_PC += 3; break; #endregion #region RTI case (0x40): RTI(); break; #endregion #region RTS case (0x60): RTS(); break; #endregion #region SBC case (0xe1): M = IndirectX(arg1); SBC(M, 6, 2); break; case (0xe5): M = ZeroPage(arg1); SBC(M, 3, 2); break; case (0xe9): M = arg1; SBC(M, 2, 2); break; case (0xed): M = Absolute(arg1, arg2); SBC(M, 4, 3); break; case (0xf1): M = IndirectY(arg1, true); SBC(M, 5, 2); break; case (0xf5): M = ZeroPageX(arg1); SBC(M, 4, 2); break; case (0xf9): M = AbsoluteY(arg1, arg2, true); SBC(M, 4, 3); break; case (0xfd): M = AbsoluteX(arg1, arg2, true); SBC(M, 4, 3); break; #endregion #region SEC case (0x38): SEC(); break; #endregion #region SED case (0xf8): SED(); break; #endregion #region SEI case (0x78): SEI(); break; #endregion #region STA case (0x85): ZeroPageWrite(arg1, REG_A); CycleCounter += 3; REG_PC += 2; break; case (0x95): ZeroPageXWrite(arg1, REG_A); CycleCounter += 4; REG_PC += 2; break; case (0x8D): AbsoluteWrite(arg1, arg2, REG_A); CycleCounter += 4; REG_PC += 3; break; case (0x9D): AbsoluteXWrite(arg1, arg2, REG_A); CycleCounter += 5; REG_PC += 3; break; case (0x99): AbsoluteYWrite(arg1, arg2, REG_A); CycleCounter += 5; REG_PC += 3; break; case (0x81): IndirectXWrite(arg1, REG_A); CycleCounter += 6; REG_PC += 2; break; case (0x91): IndirectYWrite(arg1, REG_A); CycleCounter += 6; REG_PC += 2; break; #endregion #region STX case (0x86): ZeroPageWrite(arg1, REG_X); CycleCounter += 3; REG_PC += 2; break; case (0x96): ZeroPageYWrite(arg1, REG_X); CycleCounter += 4; REG_PC += 2; break; case (0x8E): AbsoluteWrite(arg1, arg2, REG_X); CycleCounter += 4; REG_PC += 3; break; #endregion #region STY case (0x84): ZeroPageWrite(arg1, REG_Y); CycleCounter += 3; REG_PC += 2; break; case (0x94): ZeroPageXWrite(arg1, REG_Y); CycleCounter += 4; REG_PC += 2; break; case (0x8C): AbsoluteWrite(arg1, arg2, REG_Y); CycleCounter += 4; REG_PC += 3; break; #endregion #region TAX case (0xaa): TAX(); break; #endregion #region TAY case (0xa8): TAY(); break; #endregion #region TSX case (0xba): TSX(); break; #endregion #region TXA case (0x8a): TXA(); break; #endregion #region TXS case (0x9a): TXS(); break; #endregion #region TYA case (0x98): TYA(); break; #endregion /*Illegal Opcodes*/ #region AAC case 0x0B: case 0x2B: M = arg1; AAC(M, 2, 2); break; #endregion #region AAX case 0x87: M = ZeroPage(arg1); ZeroPageWrite(arg1, AAX(M)); REG_PC += 2; CycleCounter += 3; break; case 0x97: M = ZeroPageY(arg1); ZeroPageYWrite(arg1, AAX(M)); REG_PC += 2; CycleCounter += 4; break; case 0x83: M = IndirectX(arg1); IndirectXWrite(arg1, AAX(M)); REG_PC += 2; CycleCounter += 6; break; case 0x8F: M = Absolute(arg1, arg2); AbsoluteWrite(arg1, arg2, AAX(M)); REG_PC += 3; CycleCounter += 4; break; #endregion #region ARR case 0x6B: M = arg1; ARR(M); break; #endregion #region ASR case 0x4B: M = arg1; ASR(M); break; #endregion #region ATX case 0xAB: ATX(arg1); break; #endregion #region AXA case 0x9F: M = AbsoluteY(arg1, arg2, false); AbsoluteYWrite(arg1, arg2, AXA(M)); REG_PC += 3; CycleCounter += 5; break; case 0x93: M = IndirectY(arg1, false); IndirectYWrite(arg1, AXA(M)); REG_PC += 2; CycleCounter += 6; break; #endregion #region AXS case 0xCB: AXS(arg1); break; #endregion #region DCP case 0xC7: M = ZeroPage(arg1); DCP(M, 5, 2); break; case 0xD7: M = ZeroPageX(arg1); DCP(M, 6, 2); break; case 0xCF: M = Absolute(arg1, arg2); DCP(M, 6, 3); break; case 0xDF: M = AbsoluteX(arg1, arg2, true); DCP(M, 7, 3); break; case 0xDB: M = AbsoluteY(arg1, arg2, true); DCP(M, 7, 3); break; case 0xC3: M = IndirectX(arg1); DCP(M, 8, 2); break; case 0xD3: M = IndirectY(arg1, true); DCP(M, 8, 2); break; #endregion #region DOP case 0x14: case 0x54: case 0x74: case 0xD4: case 0xF4: case 0x34: DOP(4, 2); break; case 0x04: case 0x64: case 0x44: DOP(3, 2); break; case 0x82: case 0x89: case 0xC2: case 0xE2: case 0x80: DOP(2, 2); break; #endregion #region ISC case 0xE7: M = ZeroPage(arg1); ISC(M, 5, 2); break; case 0xF7: M = ZeroPageX(arg1); ISC(M, 6, 2); break; case 0xEF: M = Absolute(arg1, arg2); ISC(M, 6, 3); break; case 0xFF: M = AbsoluteX(arg1, arg2, true); ISC(M, 7, 3); break; case 0xFB: M = AbsoluteY(arg1, arg2, true); ISC(M, 7, 3); break; case 0xE3: M = IndirectX(arg1); ISC(M, 8, 2); break; case 0xF3: M = IndirectY(arg1, true); ISC(M, 8, 2); break; #endregion #region KIL case 0x02: case 0x12: case 0x22: case 0x32: case 0x42: case 0x52: case 0x62: case 0x72: case 0x92: case 0xB2: case 0xD2: case 0xF2: KIL(); break; #endregion #region LAR case 0xBB: M = AbsoluteY(arg1, arg2, false); LAR(M, 4, 2); break; #endregion #region LAX case 0xA7: M = ZeroPage(arg1); LAX(M, 3, 2); break; case 0xB7: M = ZeroPageY(arg1); LAX(M, 4, 2); break; case 0xAF: M = Absolute(arg1, arg2); LAX(M, 4, 3); break; case 0xBF: M = AbsoluteY(arg1, arg2, true); LAX(M, 4, 3); break; case 0xA3: M = IndirectX(arg1); LAX(M, 6, 2); break; case 0xB3: M = IndirectY(arg1, true); LAX(M, 5, 2); break; #endregion #region NOP case 0x1A: case 0x3A: case 0x5A: case 0x7A: case 0xDA: case 0xFA: NOP(); break; #endregion #region RLA case 0x27: M = ZeroPage(arg1); RLA(M, 5, 2); break; case 0x37: M = ZeroPageX(arg1); RLA(M, 6, 2); break; case 0x2F: M = Absolute(arg1, arg2); RLA(M, 6, 3); break; case 0x3F: M = AbsoluteX(arg1, arg2, false); RLA(M, 7, 3); break; case 0x3B: M = AbsoluteY(arg1, arg2, false); RLA(M, 7, 3); break; case 0x23: M = IndirectX(arg1); RLA(M, 8, 2); break; case 0x33: M = IndirectY(arg1, false); RLA(M, 8, 2); break; #endregion #region RRA case 0x67: M = ZeroPage(arg1); RRA(M, 5, 2); break; case 0x77: M = ZeroPageX(arg1); RRA(M, 6, 2); break; case 0x6F: M = Absolute(arg1, arg2); RRA(M, 6, 3); break; case 0x7F: M = AbsoluteX(arg1, arg2, false); RRA(M, 7, 3); break; case 0x7B: M = AbsoluteY(arg1, arg2, false); RRA(M, 7, 3); break; case 0x63: M = IndirectX(arg1); RRA(M, 8, 2); break; case 0x73: M = IndirectY(arg1, false); RRA(M, 8, 2); break; #endregion #region SBC case 0xEB: M = arg1; SBC(M, 2, 2); break; #endregion #region SLO case 0x07: M = ZeroPage(arg1); SLO(M, 5, 2); break; case 0x17: M = ZeroPageX(arg1); SLO(M, 6, 2); break; case 0x0F: M = Absolute(arg1, arg2); SLO(M, 6, 3); break; case 0x1F: M = AbsoluteX(arg1, arg2, false); SLO(M, 7, 3); break; case 0x1B: M = AbsoluteY(arg1, arg2, false); SLO(M, 7, 3); break; case 0x03: M = IndirectX(arg1); SLO(M, 8, 2); break; case 0x13: M = IndirectY(arg1, false); SLO(M, 8, 2); break; #endregion #region SRE case 0x47: SRE(ZeroPage(arg1), 5, 2); break; case 0x57: SRE(ZeroPageX(arg1), 6, 2); break; case 0x4F: SRE(Absolute(arg1, arg2), 6, 3); break; case 0x5F: SRE(AbsoluteX(arg1, arg2, false), 7, 3); break; case 0x5B: SRE(AbsoluteY(arg1, arg2, false), 7, 3); break; case 0x43: SRE(IndirectX(arg1), 8, 2); break; case 0x53: SRE(IndirectY(arg1, false), 8, 2); break; #endregion #region SXA case 0x9E: AbsoluteYWrite(arg1, arg2, SXA(arg1)); break; #endregion #region SYA case 0x9C: AbsoluteXWrite(arg1, arg2, SYA(arg1)); break; #endregion #region TOP case 0x0C: TOP(4, 3); break; case 0x1C: case 0x3C: case 0x5C: case 0x7C: case 0xDC: case 0xFC: AbsoluteX(arg1, arg2, true); TOP(4, 3); break; #endregion #region XAA case 0x8B: XAA(2, 2); break; #endregion #region XAS case 0x9B: M = AbsoluteY(arg1, arg2, false); AbsoluteYWrite(arg1, arg2, XAS(M, arg1)); CycleCounter += 5; REG_PC += 3; break; #endregion default://Should not reach here MyNesDEBUGGER.WriteLine(this, "Unkown OPCODE : 0x" + string.Format("{0:X}", OpCode) + ", PC=0x" + string.Format("{0:X}", REG_PC), DebugStatus.Warning); break; } #endregion if (NMIRequest)//NMI { Flag_B = false; Push16(REG_PC); PushStatus(); Flag_I = true; REG_PC = Read16(0xFFFA); CycleCounter += 7; NMIRequest = false; } else if (!Flag_I & IRQRequest)//IRQ { Flag_B = false; Push16(REG_PC); PushStatus(); Flag_I = true; REG_PC = Read16(0xFFFE); CycleCounter += 7; IRQRequest = false; } return CycleCounter; } /// <summary> /// RST /// </summary> public void Reset() { REG_S = 0xFD; REG_A = 0; REG_X = 0; REG_Y = 0; Flag_N = false; Flag_V = false; Flag_B = false; Flag_D = false; Flag_I = true; Flag_Z = false; Flag_C = false; //Reset memory MEM[0x08] = 0xF7; MEM[0x09] = 0xEF; MEM[0x0A] = 0xDF; MEM[0x0F] = 0xBF; REG_PC = Read16(0xFFFC); MyNesDEBUGGER.WriteLine(this, "CPU RESET", DebugStatus.Warning); } /// <summary> /// Soft Reset /// </summary> public void SoftReset() { NMIRequest = IRQRequest = false; Flag_I = true; REG_S -= 3; REG_PC = Read16(0xFFFC); MEM.MAPPER.SoftReset(); _Nes.APU.SoftReset(); MyNesDEBUGGER.WriteLine(this, "SOFT RESET", DebugStatus.Warning); } /// <summary> /// get two bytes into a correct address /// </summary> /// <param name="c">Byte A</param> /// <param name="d">Byte B</param> /// <returns>ushort A & B togather</returns> ushort MakeAddress(byte c, byte d) { return (ushort)((d << 8) | c); } ushort Read16(ushort Address) { return (ushort)(MEM[Address] | (MEM[(ushort)(Address + 1)] << 8)); } #region Addressing Modes byte ZeroPage(ushort A) { return MEM[A]; } byte ZeroPageX(ushort A) { return MEM[(ushort)(0xFF & (A + REG_X))]; } byte ZeroPageY(ushort A) { return MEM[(ushort)(0xFF & (A + REG_Y))]; } byte Absolute(byte A, byte B) { return MEM[MakeAddress(A, B)]; } byte AbsoluteX(byte A, byte B, bool CheckPage) { if (CheckPage) { if ((MakeAddress(A, B) & 0xFF00) != ((MakeAddress(A, B) + REG_X) & 0xFF00)) { CycleCounter += 1; }; } return MEM[(ushort)(MakeAddress(A, B) + REG_X)]; } byte AbsoluteY(byte A, byte B, bool CheckPage) { if (CheckPage) { if ((MakeAddress(A, B) & 0xFF00) != ((MakeAddress(A, B) + REG_Y) & 0xFF00)) { CycleCounter += 1; }; } return MEM[(ushort)(MakeAddress(A, B) + REG_Y)]; } byte IndirectX(byte A) { byte l = MEM[(ushort)(0xFF & (A + REG_X))]; byte h = MEM[(ushort)(0xFF & ((A + REG_X) + 1))]; return MEM[(ushort)(l | h << 8)]; } byte IndirectY(byte A, bool CheckPage) { byte l = MEM[(ushort)(0xFF & A)]; byte h = MEM[(ushort)(0xFF & (A + 1))]; ushort addr = (ushort)((l | h << 8) + REG_Y); if (CheckPage) { if ((addr & 0xFF00) != ((l | h << 8) & 0xFF00)) { CycleCounter += 1; }; } return MEM[addr]; } void ZeroPageWrite(ushort A, byte data) { MEM[A] = data; } void ZeroPageXWrite(ushort A, byte data) { MEM[(ushort)(0xff & (A + REG_X))] = data; } void ZeroPageYWrite(ushort A, byte data) { MEM[(ushort)(0xff & (A + REG_Y))] = data; } void AbsoluteWrite(byte A, byte B, byte data) { MEM[MakeAddress(A, B)] = data; } void AbsoluteXWrite(byte A, byte B, byte data) { MEM[(ushort)(MakeAddress(A, B) + REG_X)] = data; } void AbsoluteYWrite(byte A, byte B, byte data) { MEM[(ushort)(MakeAddress(A, B) + REG_Y)] = data; } void IndirectXWrite(byte A, byte data) { byte l = MEM[(ushort)(0xFF & (A + REG_X))]; byte h = MEM[(ushort)(0xFF & ((A + REG_X) + 1))]; MEM[(ushort)(l | h << 8)] = data; } void IndirectYWrite(byte A, byte data) { byte l = MEM[(ushort)(0xFF & A)]; byte h = MEM[(ushort)(0xFF & (A + 1))]; ushort addr = (ushort)((l | h << 8) + REG_Y); MEM[addr] = data; } #endregion #region OPCODES void ADC(byte M, int count, ushort bytes) { int carry_flag = Flag_C ? 1 : 0; uint valueholder32 = (uint)(REG_A + M + carry_flag); //Set flags Flag_V = (((valueholder32 ^ REG_A) & (valueholder32 ^ M)) & 0x80) != 0; Flag_C = ((valueholder32 >> 8) != 0); Flag_Z = ((valueholder32 & 0xFF) == 0); Flag_N = ((valueholder32 & 0x80) == 0x80); REG_A = (byte)(valueholder32 & 0xff); //Advance CycleCounter += count; REG_PC += bytes; } void AND(byte M, int count, ushort bytes) { REG_A = (byte)(REG_A & M); //Flags Flag_Z = (REG_A == 0); Flag_N = ((REG_A & 0x80) == 0x80); //Advance CycleCounter += count; REG_PC += bytes; } byte ASL(byte M) { //Flags Flag_C = ((M & 0x80) == 0x80); M <<= 1; Flag_Z = (M == 0x0); Flag_N = ((M & 0x80) == 0x80); return M; } void Branch(bool COND, byte arg1) { REG_PC += 2; if (COND) { ushort adr = (ushort)(REG_PC + (sbyte)arg1); if ((adr & 0xFF00) != ((REG_PC) & 0xFF00)) { CycleCounter++; } CycleCounter++; REG_PC = adr; } CycleCounter += 2; } void BIT(byte M, int count, ushort bytes) { Flag_Z = ((REG_A & M) == 0x0); Flag_N = ((M & 0x80) == 0x80); Flag_V = ((M & 0x40) == 0x40); //Advance CycleCounter += count; REG_PC += bytes; } void BRK() { REG_PC +=2; Flag_B = true; Push16(REG_PC); PushStatus(); Flag_I = true; REG_PC = Read16(0xFFFE); CycleCounter += 7; } void CLC() { Flag_C = false; REG_PC += 1; CycleCounter += 2; } void CLD() { Flag_D = false; REG_PC += 1; CycleCounter += 2; } void CLI() { Flag_I = false; REG_PC += 1; CycleCounter += 2; } void CLV() { Flag_V = false; REG_PC += 1; CycleCounter += 2; } void CMP(byte M, int count, ushort bytes) { //Flags Flag_C = (REG_A >= M); Flag_Z = (REG_A == M); M = (byte)(REG_A - M); Flag_N = ((M & 0x80) == 0x80); //Advance CycleCounter += count; REG_PC += bytes; } void CPX(byte M, int count, ushort bytes) { Flag_C = (REG_X >= M); Flag_Z = (REG_X == M); M = (byte)(REG_X - M); Flag_N = ((M & 0x80) == 0x80); //Advance CycleCounter += count; REG_PC += bytes; } void CPY(byte M, int count, ushort bytes) { Flag_C = (REG_Y >= M); Flag_Z = (REG_Y == M); M = (byte)(REG_Y - M); Flag_N = ((M & 0x80) == 0x80); //Advance CycleCounter += count; REG_PC += bytes; } byte DEC(byte M) { M--; Flag_Z = (M == 0x0); Flag_N = ((M & 0x80) == 0x80); return M; } void DEX() { REG_X--; Flag_Z = (REG_X == 0x0); Flag_N = ((REG_X & 0x80) == 0x80); REG_PC++; CycleCounter += 2; } void DEY() { REG_Y--; Flag_Z = (REG_Y == 0x0); Flag_N = ((REG_Y & 0x80) == 0x80); REG_PC++; CycleCounter += 2; } void EOR(byte M, int count, ushort bytes) { REG_A = (byte)(REG_A ^ M); Flag_Z = (REG_A == 0); Flag_N = ((REG_A & 0x80) == 0x80); //Advance CycleCounter += count; REG_PC += bytes; } byte INC(byte M) { M++; Flag_Z = ((M & 0xff) == 0x0); Flag_N = ((M & 0x80) == 0x80); return M; } void INX() { REG_X++; Flag_Z = ((REG_X & 0xff) == 0x0); Flag_N = ((REG_X & 0x80) == 0x80); REG_PC++; CycleCounter += 2; } void INY() { REG_Y++; Flag_Z = ((REG_Y & 0xff) == 0x0); Flag_N = ((REG_Y & 0x80) == 0x80); REG_PC++; CycleCounter += 2; } void JSR(byte arg1, byte arg2) { ushort addr = MakeAddress(arg1, arg2); REG_PC += 2; Push16((ushort)(REG_PC)); REG_PC = addr; CycleCounter += 6; } void LDA() { Flag_Z = ((REG_A & 0xFF) == 0); Flag_N = ((REG_A & 0x80) == 0x80); } void LDX() { Flag_Z = (REG_X == 0); Flag_N = ((REG_X & 0x80) == 0x80); } void LDY() { Flag_Z = (REG_Y == 0); Flag_N = ((REG_Y & 0x80) == 0x80); } byte LSR(byte M) { Flag_C = ((M & 0x1) == 0x1); M = (byte)(M >> 1); Flag_Z = ((M & 0xff) == 0x0); Flag_N = ((M & 0x80) == 0x80); return M; } void NOP() { REG_PC++; CycleCounter += 2; } void ORA(byte M, int count, ushort bytes) { REG_A |= M; Flag_Z = ((REG_A & 0xff) == 0); Flag_N = ((REG_A & 0x80) == 0x80); //Advance CycleCounter += count; REG_PC += bytes; } void PHA() { Push8(REG_A); REG_PC += 1; CycleCounter += 3; } void PHP() { Flag_B = true; PushStatus(); REG_PC++; CycleCounter += 3; } void PLA() { REG_A = Pull8(); Flag_Z = (REG_A == 0); Flag_N = ((REG_A & 0x80) == 0x80); REG_PC += 1; CycleCounter += 4; } void PLP() { PullStatus(); REG_PC += 1; CycleCounter += 4; } byte ROL(byte M) { byte bitholder = 0; if ((M & 0x80) == 0x80) bitholder = 1; else bitholder = 0; byte carry_flag = (byte)(Flag_C ? 1 : 0); M = (byte)(M << 1); M = (byte)(M | carry_flag); carry_flag = bitholder; Flag_C = (bitholder == 1); Flag_Z = ((M & 0xff) == 0x0); Flag_N = ((M & 0x80) == 0x80); return M; } byte ROR(byte M) { byte bitholder = 0; byte carry_flag = (byte)(Flag_C ? 1 : 0); if ((M & 0x1) == 0x1) bitholder = 1; else bitholder = 0; M = (byte)(M >> 1); if (carry_flag == 1) M = (byte)(M | 0x80); Flag_C = (bitholder == 1); Flag_Z = ((M & 0xff) == 0x0); Flag_N = ((M & 0x80) == 0x80); return M; } void RTI() { PullStatus(); REG_PC = Pull16(); CycleCounter += 6; } void RTS() { REG_PC = Pull16(); CycleCounter += 6; REG_PC++; } void SBC(byte M, int count, ushort bytes) { int C = (!Flag_C) ? 1 : 0; ushort valueholder32 = (ushort)(REG_A - M - C); Flag_C = !((valueholder32 >> 8) != 0); Flag_Z = ((valueholder32 & 0xFF) == 0); Flag_V = ((REG_A ^ M) & (REG_A ^ valueholder32) & 0x80) != 0; Flag_N = ((valueholder32 & 0x80) == 0x80); REG_A = (byte)(valueholder32 & 0xFF); //Advance CycleCounter += count; REG_PC += bytes; } void SEC() { Flag_C = true; CycleCounter += 2; REG_PC += 1; } void SED() { Flag_D = true; CycleCounter += 2; REG_PC += 1; } void SEI() { Flag_I = true; CycleCounter += 2; REG_PC += 1; } void TAX() { REG_X = REG_A; Flag_Z = (REG_X == 0); Flag_N = ((REG_X & 0x80) == 0x80); REG_PC += 1; CycleCounter += 2; } void TAY() { REG_Y = REG_A; Flag_Z = (REG_Y == 0); Flag_N = ((REG_Y & 0x80) == 0x80); REG_PC += 1; CycleCounter += 2; } void TSX() { REG_X = REG_S; Flag_Z = (REG_X == 0); Flag_N = ((REG_X & 0x80) == 0x80); REG_PC += 1; CycleCounter += 2; } void TXA() { REG_A = REG_X; Flag_Z = (REG_A == 0); Flag_N = ((REG_A & 0x80) == 0x80); REG_PC += 1; CycleCounter += 2; } void TXS() { REG_S = REG_X; REG_PC += 1; CycleCounter += 2; } void TYA() { REG_A = REG_Y; Flag_Z = (REG_A == 0); Flag_N = ((REG_A & 0x80) == 0x80); REG_PC += 1; CycleCounter += 2; } /*Illegall Opcodes, not sure if all work*/ void AAC(byte M, int count, ushort bytes) { REG_A &= M; Flag_C = ((REG_A & 0x80) == 0x80); Flag_Z = ((REG_A & 0xFF) == 0); Flag_N = ((REG_A & 0x80) == 0x80); //Advance CycleCounter += count; REG_PC += bytes; } byte AAX(byte M) { //byte temp = (byte)((REG_X & REG_A) - M); //Flag_Z = (temp == 0); //Flag_N = ((temp & 0x80) == 0x80); return (byte)(REG_X & REG_A); } void ARR(byte M) { byte carry_flag = (byte)(Flag_C ? 1 : 0); REG_A = (byte)(((M & REG_A) >> 1) | (carry_flag << 7)); Flag_Z = ((REG_A & 0xFF) == 0x0); Flag_N = ((REG_A & 0x80) == 0x80); Flag_C = ((REG_A >> 6) & 0x1) == 0x1; Flag_V = ((REG_A >> 6 ^ REG_A >> 5) & 0x1) == 0x1; //Advance REG_PC += 2; CycleCounter += 2; } void ASR(byte M) { REG_A &= M; Flag_C = ((REG_A & 0x1) == 0x1); REG_A >>= 1; Flag_Z = ((REG_A & 0xFF) == 0x0); Flag_N = ((REG_A & 0x80) == 0x80); //Advance REG_PC += 2; CycleCounter += 2; } void ATX(byte M) { REG_A |= 0xEE; REG_A &= M; REG_X = REG_A; Flag_Z = ((REG_A & 0xFF) == 0); Flag_N = ((REG_A & 0x80) == 0x80); //Advance REG_PC += 2; CycleCounter += 2; } byte AXA(byte M) { M = (byte)((REG_A & REG_X) & 7); return M; } void AXS(byte M) { int tmp = ((REG_A & REG_X) - M); Flag_C = (tmp <= 0xFF); REG_X = (byte)(tmp & 0xFF); Flag_Z = ((REG_X & 0xFF) == 0); Flag_N = ((REG_X & 0x80) == 0x80); //Advance REG_PC += 2; CycleCounter += 2; } void DCP(byte M, int count, ushort bytes) { M = (byte)((M - 1) & 0xFF); CMP(M, count, bytes); //Flags //Flag_Z = (M == OldM); //M = (byte)(M - OldM); //Flag_N = ((M & 0x80) == 0x80); //Advance //CycleCounter += count; //REG_PC += bytes; } void DOP(int count, ushort bytes) { //Advance CycleCounter += count; REG_PC += bytes; } void ISC(byte M, int count, ushort bytes) { M++; SBC(M, count, bytes); } void KIL() { REG_PC++; } void LAR(byte M, int count, ushort bytes) { REG_X = REG_A = (REG_S &= M); Flag_Z = ((REG_X & 0xFF) == 0); Flag_N = ((REG_X & 0x80) == 0x80); //Advance CycleCounter += count; REG_PC += bytes; } void LAX(byte M, int count, ushort bytes) { REG_X = REG_A = M; Flag_Z = ((REG_A & 0xFF) == 0); Flag_N = ((REG_A & 0x80) == 0x80); //Advance CycleCounter += count; REG_PC += bytes; } void RLA(byte M, int count, ushort bytes) { byte d0 = (byte)(Flag_C ? 0x01 : 0x00); Flag_C = (M & 0x80) != 0; M <<= 1; M |= d0; REG_A &= M; Flag_Z = ((REG_A & 0xFF) == 0); Flag_N = ((REG_A & 0x80) == 0x80); //Advance CycleCounter += count; REG_PC += bytes; } void RRA(byte M, int count, ushort bytes) { M >>= 1; if (Flag_C) M |= 0x80; Flag_C = (M & 1) != 0; ADC(M, count, bytes); } void SLO(byte M, int count, ushort bytes) { Flag_C = (M >> 7) != 0; M = (byte)((M << 1) & 0xFF); REG_A |= M; Flag_Z = ((REG_A & 0xFF) == 0); Flag_N = ((REG_A & 0x80) == 0x80); //Advance CycleCounter += count; REG_PC += bytes; } void SRE(byte M, int count, ushort bytes) { Flag_C = (M & 0x80) != 0; M >>= 1; REG_A ^= M; Flag_Z = ((REG_A & 0xFF) == 0); Flag_N = ((REG_A & 0x80) == 0x80); //Advance CycleCounter += count; REG_PC += bytes; } byte SXA(byte M) { byte tmp = (byte)(REG_X & (M + 1)); //Advance CycleCounter += 5; REG_PC += 3; return tmp; } byte SYA(byte M) { byte tmp = (byte)(REG_Y & (M + 1)); //Advance CycleCounter += 5; REG_PC += 3; return tmp; } void TOP(int count, ushort bytes) { CycleCounter += count; REG_PC += bytes; } void XAA(int count, ushort bytes) { CycleCounter += count; REG_PC += bytes; } byte XAS(byte M, byte arg1) { REG_S = (byte)(REG_X & REG_A); return (byte)(REG_S & (arg1 + 1)); } #endregion #region Operations (pull, Push ...) void Push8(byte data) { MEM[(ushort)(0x100 + REG_S)] = data; REG_S--; } public void Push16(ushort data) { Push8((byte)((data & 0xFF00) >> 8)); Push8((byte)(data & 0x00FF)); } public void PushStatus() { byte statusdata = 0; if (Flag_N) statusdata = (byte)(statusdata | 0x80); if (Flag_V) statusdata = (byte)(statusdata | 0x40); statusdata = (byte)(statusdata | 0x20); if (Flag_B) statusdata = (byte)(statusdata | 0x10); if (Flag_D) statusdata = (byte)(statusdata | 0x08); if (Flag_I) statusdata = (byte)(statusdata | 0x04); if (Flag_Z) statusdata = (byte)(statusdata | 0x02); if (Flag_C) statusdata = (byte)(statusdata | 0x01); Push8(statusdata); } public byte StatusRegister() { byte statusdata = 0; if (Flag_N) statusdata = (byte)(statusdata | 0x80); if (Flag_V) statusdata = (byte)(statusdata | 0x40); statusdata = (byte)(statusdata | 0x20); if (Flag_B) statusdata = (byte)(statusdata | 0x10); if (Flag_D) statusdata = (byte)(statusdata | 0x08); if (Flag_I) statusdata = (byte)(statusdata | 0x04); if (Flag_Z) statusdata = (byte)(statusdata | 0x02); if (Flag_C) statusdata = (byte)(statusdata | 0x01); return statusdata; } byte Pull8() { REG_S++; return MEM[(ushort)(0x100 + REG_S)]; } ushort Pull16() { byte data1 = Pull8(); byte data2 = Pull8(); return MakeAddress(data1, data2); } void PullStatus() { byte statusdata = Pull8(); Flag_N = ((statusdata & 0x80) == 0x80); Flag_V = ((statusdata & 0x40) == 0x40); Flag_B = ((statusdata & 0x10) == 0x10); Flag_D = ((statusdata & 0x08) == 0x08); Flag_I = ((statusdata & 0x04) == 0x04); Flag_Z = ((statusdata & 0x02) == 0x02); Flag_C = ((statusdata & 0x01) == 0x01); } #endregion } }
33.313861
172
0.339678
[ "Apache-2.0" ]
evgenyvinnik/jvsc-windows-apps
Nes7/EmuSeven/NES/CPU/CPU.cs
62,732
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Microsoft.DotNet.Interactive.Notebook; namespace Microsoft.DotNet.Interactive.Commands { public class SerializeNotebook : KernelCommand { public string FileName { get; } public NotebookDocument Notebook { get; } public string NewLine { get; } public SerializeNotebook(string fileName, NotebookDocument notebook, string newLine, string targetKernelName = null) : base(targetKernelName) { FileName = fileName; Notebook = notebook; NewLine = newLine; } } }
31.666667
124
0.676316
[ "MIT" ]
AngelusGi/interactive
src/Microsoft.DotNet.Interactive/Commands/SerializeNotebook.cs
762
C#
namespace Orchard.OpenId.Constants { public class General { public const string AuthenticationErrorUrl = "/Authentication/Error"; public const string LogonCallbackUrl = "/Users/Account/LogonCallback"; public const string OpenIdOwinMiddlewarePriority = "10"; public const string LocalIssuer = "LOCAL AUTHORITY"; public const string FormsIssuer = "Forms"; } }
45.111111
78
0.706897
[ "BSD-3-Clause" ]
AndreaPiovanelliLaser/Orchard
src/Orchard.Web/Modules/Orchard.OpenId/Constants/General.cs
408
C#
using myoddweb.classifier.interfaces; using Outlook = Microsoft.Office.Interop.Outlook; namespace myoddweb.classifier.core { public class OutlookFolder : IFolder { /// <summary> /// Get access to the outlook folder. /// </summary> public readonly Outlook.MAPIFolder Folder; /// <summary> /// The cleanup name of the folder without the root folder. /// </summary> private readonly string _prettyFolderPath; public OutlookFolder(Outlook.MAPIFolder folder, string prettyFolderPath) { Folder = folder; _prettyFolderPath = prettyFolderPath; } /// <summary> /// The folder path, either the full path or the 'pretty' path. /// </summary> /// <param name="prettyDisplay">boolean if we want the pretty path or the full path.</param> /// <returns>string the path</returns> public string Path( bool prettyDisplay ) { return false == prettyDisplay ? Folder.FolderPath : _prettyFolderPath; } /// <summary> /// The unique folder id. /// </summary> /// <returns>string the unique folder id.</returns> public string Id() { return Folder.EntryID; } /// <summary> /// The folder name /// </summary> /// <returns>string folder name.</returns> public string Name() { return Folder.Name; } } }
25.433962
96
0.633531
[ "MIT" ]
FFMG/myoddweb.classifier
Classifier.Outlook/core/outlookfolder.cs
1,350
C#
namespace MassTransit { using System; /// <summary> /// Used to visit the state machine structure, so it can be displayed, etc. /// </summary> [Obsolete] public interface Visitable : IVisitable { } }
16.133333
79
0.590909
[ "ECL-2.0", "Apache-2.0" ]
AlexanderMeier/MassTransit
src/MassTransit.Abstractions/SagaStateMachine/Visitable.cs
242
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("PlayPass.Engine.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PlayPass.Engine.Test")] [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("f221dcd7-8c77-486a-9b06-d53ab9652f14")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.054054
84
0.747869
[ "MIT" ]
CodePenguin/PlayPass
PlayPass.Engine.Test/Properties/AssemblyInfo.cs
1,411
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace aws { [JsiiInterface(nativeType: typeof(IWafv2RuleGroupRuleStatementNotStatementStatementAndStatementStatementXssMatchStatementFieldToMatchSingleHeader), fullyQualifiedName: "aws.Wafv2RuleGroupRuleStatementNotStatementStatementAndStatementStatementXssMatchStatementFieldToMatchSingleHeader")] public interface IWafv2RuleGroupRuleStatementNotStatementStatementAndStatementStatementXssMatchStatementFieldToMatchSingleHeader { [JsiiProperty(name: "name", typeJson: "{\"primitive\":\"string\"}")] string Name { get; } [JsiiTypeProxy(nativeType: typeof(IWafv2RuleGroupRuleStatementNotStatementStatementAndStatementStatementXssMatchStatementFieldToMatchSingleHeader), fullyQualifiedName: "aws.Wafv2RuleGroupRuleStatementNotStatementStatementAndStatementStatementXssMatchStatementFieldToMatchSingleHeader")] internal sealed class _Proxy : DeputyBase, aws.IWafv2RuleGroupRuleStatementNotStatementStatementAndStatementStatementXssMatchStatementFieldToMatchSingleHeader { private _Proxy(ByRefValue reference): base(reference) { } [JsiiProperty(name: "name", typeJson: "{\"primitive\":\"string\"}")] public string Name { get => GetInstanceProperty<string>()!; } } } }
46.516129
294
0.75104
[ "MIT" ]
scottenriquez/cdktf-alpha-csharp-testing
resources/.gen/aws/aws/IWafv2RuleGroupRuleStatementNotStatementStatementAndStatementStatementXssMatchStatementFieldToMatchSingleHeader.cs
1,442
C#
using System; using System.Collections.Generic; using System.Text; namespace WildFarm.Animals.Felines.Factory { public class FelineFactory { public Feline CreateFeline(string type, string name, double weight, string livingRegion, string breed) { type = type.ToLower(); switch (type) { case "cat": return new Cat(name, weight, livingRegion, breed); case "tiger": return new Tiger(name, weight, livingRegion, breed); default: return null; } } } }
23.777778
110
0.529595
[ "MIT" ]
TodorNikolov89/SoftwareUniversity
CSharp_OOP_Basics/Polymorphism/WildFarm/Animals/Felines/Factory/FelineFactory.cs
644
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the elasticbeanstalk-2010-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.ElasticBeanstalk.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.ElasticBeanstalk.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for InstanceHealthSummary Object /// </summary> public class InstanceHealthSummaryUnmarshaller : IUnmarshaller<InstanceHealthSummary, XmlUnmarshallerContext>, IUnmarshaller<InstanceHealthSummary, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public InstanceHealthSummary Unmarshall(XmlUnmarshallerContext context) { InstanceHealthSummary unmarshalledObject = new InstanceHealthSummary(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("Degraded", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.Degraded = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Info", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.Info = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("NoData", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.NoData = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Ok", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.Ok = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Pending", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.Pending = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Severe", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.Severe = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Unknown", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.Unknown = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Warning", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.Warning = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return unmarshalledObject; } } return unmarshalledObject; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <returns></returns> public InstanceHealthSummary Unmarshall(JsonUnmarshallerContext context) { return null; } private static InstanceHealthSummaryUnmarshaller _instance = new InstanceHealthSummaryUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static InstanceHealthSummaryUnmarshaller Instance { get { return _instance; } } } }
40.417266
177
0.54361
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/ElasticBeanstalk/Generated/Model/Internal/MarshallTransformations/InstanceHealthSummaryUnmarshaller.cs
5,618
C#
using AutoMapper; using DREM_API.BusinessController; using DREM_API.Extensions; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DREM_API.Controllers { /// <summary> /// This controller manages api methods for image processor /// </summary> [ApiController] [Route("[controller]")] public class OrderController : ControllerBase { private readonly IConfiguration configuration; private readonly OrderBusinessController OrderBusinessController; /// <summary> /// Constructor /// </summary> /// <param name="configuration"></param> /// <param name="OrderBusinessController"></param> public OrderController( IConfiguration configuration, OrderBusinessController OrderBusinessController ) { this.configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); this.OrderBusinessController = OrderBusinessController; } /// <summary> /// Create Order /// </summary> /// <returns></returns> [Authorize] [HttpPost("Create")] [ProducesResponseType(200)] [ProducesResponseType(400)] public async Task<ActionResult<Model.DB.Order>> Create([FromBody] Model.Comm.OrderBase item) { try { if (!User.IsAdmin(configuration)) throw new Exception("You are not admin"); return Ok(await OrderBusinessController.CreateAsync(item)); } catch (Exception exc) { return BadRequest(new ProblemDetails() { Detail = exc.Message + (exc.InnerException != null ? $";\n{exc.InnerException.Message}" : "") + "\n" + exc.StackTrace, Title = exc.Message, Type = exc.GetType().ToString() }); } } /// <summary> /// Create Order /// </summary> /// <returns></returns> [Authorize] [HttpPut("Update/{orderId}")] [ProducesResponseType(200)] [ProducesResponseType(400)] public async Task<ActionResult<Model.DB.Order>> Update([FromRoute] string orderId, [FromBody] Model.Comm.OrderBase item) { try { if (!User.IsAdmin(configuration)) throw new Exception("You are not admin"); return Ok(await OrderBusinessController.UpdateAsync(orderId, item)); } catch (Exception exc) { return BadRequest(new ProblemDetails() { Detail = exc.Message + (exc.InnerException != null ? $";\n{exc.InnerException.Message}" : "") + "\n" + exc.StackTrace, Title = exc.Message, Type = exc.GetType().ToString() }); } } /// <summary> /// Delete Order /// </summary> /// <returns></returns> [Authorize] [HttpDelete("Delete/{orderId}")] [ProducesResponseType(200)] [ProducesResponseType(400)] public async Task<ActionResult<int>> Delete([FromRoute] string orderId) { try { if (!User.IsAdmin(configuration)) throw new Exception("You are not admin"); return Ok(await OrderBusinessController.DeleteAsync(new string[] { orderId })); } catch (Exception exc) { return BadRequest(new ProblemDetails() { Detail = exc.Message + (exc.InnerException != null ? $";\n{exc.InnerException.Message}" : "") + "\n" + exc.StackTrace, Title = exc.Message, Type = exc.GetType().ToString() }); } } /// <summary> /// List all asa bids /// </summary> /// <returns></returns> [Authorize] [HttpGet("ListAllBidsForProject/{asaId}")] [ProducesResponseType(200)] [ProducesResponseType(400)] public ActionResult<IEnumerable<Model.DB.Order>> ListAllBidsForProject(ulong asaId) { try { if (!User.IsAdmin(configuration)) throw new Exception("You are not admin"); return Ok(OrderBusinessController.ListAllBidsForProject(asaId)); } catch (Exception exc) { return BadRequest(new ProblemDetails() { Detail = exc.Message + (exc.InnerException != null ? $";\n{exc.InnerException.Message}" : "") + "\n" + exc.StackTrace, Title = exc.Message, Type = exc.GetType().ToString() }); } } /// <summary> /// List all asa bids /// </summary> /// <returns></returns> [Authorize] [HttpGet("ListAllOffersForProject/{asaId}")] [ProducesResponseType(200)] [ProducesResponseType(400)] public ActionResult<IEnumerable<Model.DB.Order>> ListAllOffersForProject(ulong asaId) { try { if (!User.IsAdmin(configuration)) throw new Exception("You are not admin"); return Ok(OrderBusinessController.ListAllOffersForProject(asaId)); } catch (Exception exc) { return BadRequest(new ProblemDetails() { Detail = exc.Message + (exc.InnerException != null ? $";\n{exc.InnerException.Message}" : "") + "\n" + exc.StackTrace, Title = exc.Message, Type = exc.GetType().ToString() }); } } } }
40.208633
232
0.578458
[ "MIT" ]
DREM-DAO/drem
market/api/DREM-API/DREM-API/Controllers/OrderController.cs
5,591
C#
using DataAccess.Interfaces; using Neo4j.Driver; using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DataAccess.Person { public class PersonRepository : IPersonRepository { private readonly IDictionary<string, string> _mutations; private readonly IDictionary<string, string> _queries; private readonly IRepository _repository; public PersonRepository(IRepository repository) { _repository = repository; _queries = new PersonQueries().Queries; _mutations = new PersonQueries().Mutations; } public async Task<Person> Add(Person person) { var entity = await _repository.Write<Person>(_mutations["UPDATE_PERSON"].Trim(), new Dictionary<string, object> { { "person", person } }); return entity; } public async Task<IEnumerable<Person>> All() { var x = new List<Person>(); const int First = 9999; const int Offset = 0; const string LABEL = "person"; var param = new Dictionary<string, object>() { //{ // "pages", ParameterSerializer.ToDictionary(new List<NodePaging> { new NodePaging(First, Offset) }) //}, { "offset", Offset }, { "first", First } }; var query = _queries["GET_PEOPLE"].Trim(); var records = await _repository.Read(query, param); x.AddRange(records.Select(record => ProcessProps(record, LABEL))); return x; } public async Task<string> Delete(string id) { var entity = await _repository.Write<Person>(_mutations["DEACTIVATE_PERSON"].Trim(), new Dictionary<string, object> { { "id", id } }); return entity.Id; } public async Task<Person> Get(string id) { var entity = await _repository.Read<Person>(_queries["GET_PERSON"].Trim(), new Dictionary<string, object> { { "id", id } }); return entity; } public async Task<Person> Update(Person person) { var entity = await _repository.Write<Person>(_mutations["UPDATE_PERSON_2"].Trim(), new Dictionary<string, object> { { "person", person } }); return entity; } private Person ProcessProps(IRecord record, string label) { var props = JsonConvert.SerializeObject(record[label]); var person = JsonConvert.DeserializeObject<Person>(props); if (person.Manager == null) { var managerProps = ((Dictionary<string, object>)record.Values.Values.First()).FirstOrDefault(v => v.Key == "manager"); person.Manager = managerProps.Value != null ? JsonConvert.DeserializeObject<Person>(JsonConvert.SerializeObject(managerProps.Value.As<INode>().Properties)) : null; } if (person.Line == null) { var lineProps = ((Dictionary<string, object>)record.Values.Values.First()).FirstOrDefault(v => v.Key == "line"); if (lineProps.Value != null && ((List<object>)lineProps.Value).Any()) { var lines = ((List<object>)lineProps.Value) .Select(l => JsonConvert.DeserializeObject<Person>(JsonConvert.SerializeObject(l.As<INode>().Properties))); person.Line = lines.ToList(); } else person.Line = new List<Person>(); } if (person.Team == null) { var teamProps = ((Dictionary<string, object>)record.Values.Values.First()).FirstOrDefault(v => v.Key == "team"); if (teamProps.Value != null && ((List<object>)teamProps.Value).Any()) { var team = ((List<object>)teamProps.Value) .Select(l => JsonConvert.DeserializeObject<Person>(JsonConvert.SerializeObject(l.As<INode>().Properties))); person.Team = team.ToList(); } else person.Team = new List<Person>(); } return person; } } }
38.946903
179
0.546694
[ "MIT" ]
psyphore/graphql-net_core-neo4j
DataAccess/Person/PersonRepository.cs
4,403
C#
using System.Collections.Generic; namespace TuduManayer.Domain.Todo.Search { public interface ISearchTodoService { IReadOnlyCollection<Models.Todo> Search(string searchText); } public class SearchTodoService : ISearchTodoService { private readonly ISearchTodoRepository repository; public SearchTodoService(ISearchTodoRepository repository) { this.repository = repository; } public IReadOnlyCollection<Models.Todo> Search(string searchText) { return repository.Search(searchText); } } }
25.083333
73
0.677741
[ "MIT" ]
seymourpoler/TuduManayer
dotnet/react.mvc-core.postgres.dapper/TuduManager/src/TuduManayer.Domain/Todo/Search/SearchTodoService.cs
602
C#
/* 2011 - This file is part of AcaLabelPrint AcaLabelPrint is free Software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AcaLabelprint 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 General Public License for more details. You should have received a copy of the GNU General Public License along with AcaLabelPrint. If not, see <http:www.gnu.org/licenses/>. We encourage you to use and extend the functionality of AcaLabelPrint, and send us an e-mail on the outlines of the extension you build. If it's generic, maybe we could add it to the project. Send your mail to the projectadmin at http:sourceforge.net/projects/labelprint/ */ using System; using System.Collections.Generic; using System.Text; using System.Xml; namespace ACA.LabelX.Paper { public class Offset { public Tools.Length TopMarginOffset = null; public Tools.Length LeftMarginOffset = null; public Tools.Length HorizontalInterlabelGapOffset = null; public Tools.Length VerticalInterlabelGapOffset = null; public String Machine = null; public String Printer = null; public Tools.CoordinateSystem.Units DefaultUnits = null; public Offset(Tools.CoordinateSystem.Units Units) { DefaultUnits = Units; } public Offset(System.Drawing.GraphicsUnit Unit) { DefaultUnits = new ACA.LabelX.Tools.CoordinateSystem.Units(Unit); } public void Parse(XmlNode node) { TopMarginOffset = null; LeftMarginOffset = null; HorizontalInterlabelGapOffset = null; VerticalInterlabelGapOffset = null; Machine = null; Printer = null; foreach (XmlAttribute attrib in node.Attributes) { if (attrib.Name.Equals("horzoffset", StringComparison.OrdinalIgnoreCase)) { LeftMarginOffset = new Tools.Length(Convert.ToInt32(attrib.Value), DefaultUnits); } else if (attrib.Name.Equals("vertoffset", StringComparison.OrdinalIgnoreCase)) { TopMarginOffset = new Tools.Length(Convert.ToInt32(attrib.Value), DefaultUnits); } else if (attrib.Name.Equals("horzinterlabelgapdelta", StringComparison.OrdinalIgnoreCase)) { HorizontalInterlabelGapOffset = new Tools.Length(Convert.ToInt32(attrib.Value), DefaultUnits); } else if (attrib.Name.Equals("vertinterlabeldelta", StringComparison.OrdinalIgnoreCase)) { VerticalInterlabelGapOffset = new Tools.Length(Convert.ToInt32(attrib.Value), DefaultUnits); } else if (attrib.Name.Equals("machine", StringComparison.OrdinalIgnoreCase)) { Machine = attrib.Value; } else if (attrib.Name.Equals("printer", StringComparison.OrdinalIgnoreCase)) { Printer = attrib.Value; } } } } public class LabelLayout { public UInt32 HorizontalCount = 0; public UInt32 VerticalCount = 0; public Tools.Length TopMargin = null; public Tools.Length LeftMargin = null; public Tools.Length HorizontalInterlabelGap = null; public Tools.Length VerticalInterlabelGap = null; public Tools.CoordinateSystem.Units DefaultUnits = null; public LabelLayout(Tools.CoordinateSystem.Units DefaultUnits) { this.DefaultUnits = DefaultUnits; } public LabelLayout(System.Drawing.GraphicsUnit unit) { this.DefaultUnits = new ACA.LabelX.Tools.CoordinateSystem.Units(unit); } public void Parse(XmlNode node) { HorizontalCount = 0; VerticalCount = 0; TopMargin = null; LeftMargin = null; HorizontalInterlabelGap = null; VerticalInterlabelGap = null; foreach (XmlNode nodex in node) { if (nodex.Name.Equals("horizontal", StringComparison.OrdinalIgnoreCase)) HorizontalCount = Convert.ToUInt32(nodex.InnerText); else if (nodex.Name.Equals("vertical", StringComparison.OrdinalIgnoreCase)) VerticalCount = Convert.ToUInt32(nodex.InnerText); else if (nodex.Name.Equals("horzoffset", StringComparison.OrdinalIgnoreCase)) { LeftMargin = new ACA.LabelX.Tools.Length(DefaultUnits); LeftMargin.Parse(nodex); } else if (nodex.Name.Equals("vertoffset", StringComparison.OrdinalIgnoreCase)) { TopMargin = new ACA.LabelX.Tools.Length(DefaultUnits); TopMargin.Parse(nodex); } else if (nodex.Name.Equals("horzinterlabelgap", StringComparison.OrdinalIgnoreCase)) { HorizontalInterlabelGap = new ACA.LabelX.Tools.Length(DefaultUnits); HorizontalInterlabelGap.Parse(nodex); } else if (nodex.Name.Equals("vertinterlabelgap", StringComparison.OrdinalIgnoreCase)) { VerticalInterlabelGap = new ACA.LabelX.Tools.Length(DefaultUnits); VerticalInterlabelGap.Parse(nodex); } } } } public class PaperDef { public String ID = ""; public Tools.CoordinateSystem coordinateSystem = null; public Tools.Size size = null; public LabelLayout labelLayout = null; public IDictionary<string, Offset> Offsets = new Dictionary<string, Offset>(); public String Machine = ""; public String Printer = ""; // //When the physical printing takes place some printers have a left and top //margin, which the printer can never print upon. In .NET these printing always //take place in respect to these margins. 0,0 actually is mapped upon //physical coordinates PhysicalLeftMargin, PhysicalTopMargin. So if we describe //our page and we do this in mm, it is best to subtract these physical margings //from the given coordinates, so all is where expected. //But because this is not done before printing (als we only known the margins then //it is set upon printing in the paperdef. When retrieving coordinates we subtract this value. // public ACA.LabelX.Tools.Length PhysicalLeftMargin; public ACA.LabelX.Tools.Length PhysicalTopMargin; public PaperDef() { PhysicalTopMargin = new Tools.Length(0,new ACA.LabelX.Tools.CoordinateSystem.Units(System.Drawing.GraphicsUnit.Millimeter)); PhysicalLeftMargin = new Tools.Length(0, new ACA.LabelX.Tools.CoordinateSystem.Units(System.Drawing.GraphicsUnit.Millimeter)); } public void SetDestination(String Machine, String Printer) { this.Machine = Machine; this.Printer = Printer; } public Tools.Length GetLeftMargin() { Tools.Length LeftMargin = labelLayout.LeftMargin; String OffsetKey = string.Format("{0}@{1}", Printer, Machine); if (Offsets.ContainsKey(OffsetKey)) // Use specific offset if it exists { Offset offset = Offsets[OffsetKey]; LeftMargin += offset.LeftMarginOffset; } else if (Offsets.ContainsKey("@")) //Use default offset if no specific one exists. { Offset offset = Offsets["@"]; LeftMargin += offset.LeftMarginOffset; } //if (LeftMargin > PhysicalLeftMargin) //{ LeftMargin -= PhysicalLeftMargin; //} //else //{ // LeftMargin = new Tools.Length(0, new ACA.LabelX.Tools.CoordinateSystem.Units(System.Drawing.GraphicsUnit.Millimeter)); //} return LeftMargin; } public Tools.Length GetTopMargin() { Tools.Length TopMargin = labelLayout.TopMargin; String OffsetKey = string.Format("{0}@{1}", Printer, Machine); if (Offsets.ContainsKey(OffsetKey)) // Use specific offset if it exists { Offset offset = Offsets[OffsetKey]; TopMargin += offset.TopMarginOffset; } else if (Offsets.ContainsKey("@")) //Use default offset if no specific one exists. { Offset offset = Offsets["@"]; TopMargin += offset.TopMarginOffset; } //if (TopMargin > PhysicalTopMargin) //{ TopMargin -= PhysicalTopMargin; //} //else //{ // TopMargin = new Tools.Length(0, new Tools.CoordinateSystem.Units(System.Drawing.GraphicsUnit.Millimeter)); //} return TopMargin; } public Tools.Length GetRightMargin() { return labelLayout.LeftMargin; //return new Tools.Length(0, new Tools.CoordinateSystem.Units(System.Drawing.GraphicsUnit.Millimeter)); } public Tools.Length GetBottomMargin() { return labelLayout.TopMargin; //return new Tools.Length(0, new Tools.CoordinateSystem.Units(System.Drawing.GraphicsUnit.Millimeter)); } public Tools.Length GetHorizontalInterlabelGap() { Tools.Length HorizontalInterlabelGap = labelLayout.HorizontalInterlabelGap; //String OffsetKey = string.Format("{0}@{1}", Printer, Machine); //if (Offsets.ContainsKey(OffsetKey)) //{ // Offset offset = Offsets[OffsetKey]; // HorizontalInterlabelGap += offset.HorizontalInterlabelGapOffset; //} return HorizontalInterlabelGap; } public Tools.Length GetVerticalInterlabelGap() { Tools.Length VerticalInterlabelGap = labelLayout.VerticalInterlabelGap; //String OffsetKey = string.Format("{0}@{1}", Printer, Machine); //if (Offsets.ContainsKey(OffsetKey)) //{ // Offset offset = Offsets[OffsetKey]; // VerticalInterlabelGap += offset.VerticalInterlabelGapOffset; //} return VerticalInterlabelGap; } public Tools.Size GetPrintablePageSize() { if (labelLayout == null) throw new ApplicationException("Please, parse a paper definition first"); Tools.Length NettoWidthPage = size.Width - (labelLayout.LeftMargin * 2); Tools.Length NettoHeightPage = size.Height - (labelLayout.TopMargin *2); /* //JBOS Tools.Length NettoWidthPage = size.Width - (GetLeftMargin()+ GetRightMargin()); Tools.Length NettoHeightPage = size.Height - (GetTopMargin()+GetBottomMargin()); */ //JBOS return new ACA.LabelX.Tools.Size(NettoWidthPage, NettoHeightPage); } public Tools.Size GetPhysicalLabelSize() { if (labelLayout == null) throw new ApplicationException("Please, parse a paper definition first"); Tools.Length NettoWidthPage = size.Width; Tools.Length NettoHeightPage = size.Height; return new ACA.LabelX.Tools.Size(NettoWidthPage, NettoHeightPage); } public Tools.Size GetLabelSize() { if (labelLayout == null) throw new ApplicationException("Please, parse a paper definition first"); Tools.Size NettoPageSize = GetPrintablePageSize(); Tools.Length TotalHorizontalInterlabelGap = GetHorizontalInterlabelGap() * (int)(labelLayout.HorizontalCount - 1); Tools.Length LabelWidth = (NettoPageSize.Width - TotalHorizontalInterlabelGap) / (int)labelLayout.HorizontalCount; Tools.Length TotalVerticalInterlabelGap = GetVerticalInterlabelGap() * (int)(labelLayout.VerticalCount - 1); Tools.Length LabelHeight = (NettoPageSize.Height - TotalVerticalInterlabelGap) / (int)labelLayout.VerticalCount; return new Tools.Size(LabelWidth, LabelHeight); } public Tools.Rectangle GetLabelRectangle(int HorizontalIndex, int VerticalIndex) { if (labelLayout == null) throw new ApplicationException("Please, parse a paper definition first"); Tools.Length Left = GetLeftMargin() + ((GetLabelSize().Width + GetHorizontalInterlabelGap()) * HorizontalIndex); Tools.Length Top = GetTopMargin() + ((GetLabelSize().Height + GetVerticalInterlabelGap()) * VerticalIndex); Tools.Rectangle rect = new Tools.Rectangle(Left, Top, GetLabelSize()); return rect; } public void Parse(string FilePath) { ID = ""; coordinateSystem = null; labelLayout = null; XmlDocument xDoc = new XmlDocument(); xDoc.Load(FilePath); XmlNodeList node = xDoc.GetElementsByTagName("paper"); foreach (XmlNode nodex in node) { foreach (XmlAttribute attrib in nodex.Attributes) { if (attrib.Name.Equals("type", StringComparison.OrdinalIgnoreCase)) { ID = attrib.Value; } } foreach (XmlNode nodexx in nodex.ChildNodes) { if (nodexx.Name.Equals("coordinates", StringComparison.OrdinalIgnoreCase)) { coordinateSystem = new Tools.CoordinateSystem(); coordinateSystem.Parse(nodexx); } else if (nodexx.Name.Equals("size", StringComparison.OrdinalIgnoreCase)) { size = new ACA.LabelX.Tools.Size(0, 0, coordinateSystem.units); size.Parse(nodexx); } else if (nodexx.Name.Equals("labelpos", StringComparison.OrdinalIgnoreCase)) { labelLayout = new LabelLayout(coordinateSystem.units); labelLayout.Parse(nodexx); } else if (nodexx.Name.Equals("offsets", StringComparison.OrdinalIgnoreCase)) { foreach (XmlNode nodexxx in nodexx) { if (nodexxx.Name.Equals("offset", StringComparison.OrdinalIgnoreCase)) { Offset offset = new Offset(coordinateSystem.units); offset.Parse(nodexxx); Offsets.Add(string.Format("{0}@{1}", offset.Printer, offset.Machine), offset); } } } } } } } } /* AcaLabelPrint Copyright (C) 2011 Retailium Software Development BV. This program comes with ABSOLUTELY NO WARRANTY; This is free Software, and you are welcome to redistribute it under certain conditions. See the License.txt file or GNU GPL 3.0 License at <http://www.gnu.org/licenses>*/
41.389175
138
0.584906
[ "Apache-2.0" ]
mvendert/LabelPrint
LabelXPrintEngine/Paper.cs
16,059
C#
using System; using System.Buffers; using System.Diagnostics; using System.Threading; namespace TiffLibrary.ImageDecoder { internal class TiffDelegatingImageDecoderContext : TiffImageDecoderContext { private readonly TiffImageDecoderContext _innerContext; protected TiffImageDecoderContext InnerContext => _innerContext; public TiffDelegatingImageDecoderContext(TiffImageDecoderContext innerContext) { Debug.Assert(innerContext != null); _innerContext = innerContext!; } public override MemoryPool<byte>? MemoryPool { get => _innerContext.MemoryPool; set => _innerContext.MemoryPool = value; } public override CancellationToken CancellationToken { get => _innerContext.CancellationToken; set => _innerContext.CancellationToken = value; } public override TiffOperationContext? OperationContext { get => _innerContext.OperationContext; set => _innerContext.OperationContext = value; } public override TiffFileContentReader? ContentReader { get => _innerContext.ContentReader; set => _innerContext.ContentReader = value; } public override TiffValueCollection<TiffStreamRegion> PlanarRegions { get => _innerContext.PlanarRegions; set => _innerContext.PlanarRegions = value; } public override Memory<byte> UncompressedData { get => _innerContext.UncompressedData; set => _innerContext.UncompressedData = value; } public override TiffSize SourceImageSize { get => _innerContext.SourceImageSize; set => _innerContext.SourceImageSize = value; } public override TiffPoint SourceReadOffset { get => _innerContext.SourceReadOffset; set => _innerContext.SourceReadOffset = value; } public override TiffSize ReadSize { get => _innerContext.ReadSize; set => _innerContext.ReadSize = value; } public override TiffPixelBufferWriter<TPixel> GetWriter<TPixel>() => _innerContext.GetWriter<TPixel>(); public override void RegisterService(Type serviceType, object? service) => _innerContext.RegisterService(serviceType, service); public override object? GetService(Type serviceType) => _innerContext.GetService(serviceType); } }
55.625
159
0.741124
[ "MIT" ]
machielvisser/TiffLibrary
src/TiffLibrary/ImageDecoder/TiffDelegatingImageDecoderContext.cs
2,227
C#
/* MIT License Copyright (c) 2020 Whitespace Software Limited 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 Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading.Tasks; using WSShared; namespace RiskPack { class Program { static void Main(string[] args) { RunAsync(args).GetAwaiter().GetResult(); } static async Task RunAsync( string [] args ) { if( args.Length < 2 ) { WSUtilities.PrintVersionMesssage("RiskPack", "1.0"); Console.WriteLine("riskpack.exe [settings file] [riskID]"); Console.WriteLine("riskpack.exe --example [settings file]"); return; } if( args[0].ToLower() == "--example") { Console.WriteLine(WSSettings.WriteExample(args[1])); return; } WSSettings settings; try { settings = WSSettings.Load(args[0]); } catch( Exception ex ) { Console.WriteLine("ERROR {0}", ex.Message); return; } string json = String.Empty, req = String.Empty; try { string folder = WSUtilities.MakeSafeFilename(args[1]) + DateTime.Now.ToString("_ddMMyy_HHmmss"); Directory.CreateDirectory(folder); WSAPIClient client = WSAPIClient.ForToken(settings); _ = await client.DoOIDC(settings); req = String.Format("/export/pdf/{0}", args[1]); client = WSAPIClient.ForPDF(settings); var bytes = await client.GetByteArrayAsync(req); WriteFile(folder, args[1] + ".pdf", bytes); client = WSAPIClient.ForJSON(settings); req = String.Format("/api/attachments/{0}", MakeATCH(args[1]) ); json = await client.GetStringAsync(req); Dictionary<String, WSAttachment> dict = JsonConvert.DeserializeObject<Dictionary<String, WSAttachment>>(json); foreach (string key in dict.Keys) { WSAttachment att = dict[key]; client = WSAPIClient.ForMIMEType(settings, att.content_type); req = string.Format("/api/attachments/{0}/{1}", MakeATCH(args[1]), key); bytes = await client.GetByteArrayAsync(req); WriteFile(folder, key, bytes); } } catch( Exception ex ) { Console.WriteLine(ex.Message); Console.WriteLine("Last URL was {0}", req); } } static void WriteFile( string folder, string filename, Byte[] bytes ) { string fullfilename = Path.Combine(folder, WSUtilities.MakeSafeFilename(filename)); using (var fs = new FileStream(fullfilename, FileMode.Create, FileAccess.Write)) { fs.Write(bytes, 0, bytes.Length); } Console.WriteLine("{0} written, {1} bytes", fullfilename, bytes.Length); } static string MakeATCH( string riskid ) { int pos = riskid.IndexOf("::"); if (pos > 0) return riskid.Substring(0, pos) + "::ATCH"; else return riskid + "::ATCH"; } } }
37.443548
127
0.566659
[ "MIT" ]
whitespace-software/CSharpUtils
RiskPack/Program.cs
4,645
C#
using System; using Cosmos; using Cosmos.UnionTypes; using Cosmos.UnionTypes.Internals; // ReSharper disable RedundantExtendsListEntry namespace Cosmos.UnionTypes; /// <summary> /// Union Of <br /> /// 联合类型 /// </summary> /// <typeparam name="T0"></typeparam> /// <typeparam name="T1"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> /// <typeparam name="T4"></typeparam> /// <typeparam name="T5"></typeparam> /// <typeparam name="T6"></typeparam> /// <typeparam name="T7"></typeparam> /// <typeparam name="T8"></typeparam> /// <typeparam name="T9"></typeparam> /// <typeparam name="T10"></typeparam> /// <typeparam name="T11"></typeparam> /// <typeparam name="T12"></typeparam> /// <typeparam name="T13"></typeparam> /// <typeparam name="T14"></typeparam> public class UnionOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> : IUnionType, IUnionType<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> { readonly T0 _v0; readonly T1 _v1; readonly T2 _v2; readonly T3 _v3; readonly T4 _v4; readonly T5 _v5; readonly T6 _v6; readonly T7 _v7; readonly T8 _v8; readonly T9 _v9; readonly T10 _v10; readonly T11 _v11; readonly T12 _v12; readonly T13 _v13; readonly T14 _v14; readonly int _ix; protected UnionOf(UnionType<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> input) { _ix = input.Index; switch (_ix) { case 0: _v0 = input.AsT0(); break; case 1: _v1 = input.AsT1(); break; case 2: _v2 = input.AsT2(); break; case 3: _v3 = input.AsT3(); break; case 4: _v4 = input.AsT4(); break; case 5: _v5 = input.AsT5(); break; case 6: _v6 = input.AsT6(); break; case 7: _v7 = input.AsT7(); break; case 8: _v8 = input.AsT8(); break; case 9: _v9 = input.AsT9(); break; case 10: _v10 = input.AsT10(); break; case 11: _v11 = input.AsT11(); break; case 12: _v12 = input.AsT12(); break; case 13: _v13 = input.AsT13(); break; case 14: _v14 = input.AsT14(); break; default: throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen."); } } /// <inheritdoc /> public object Value { get { return _ix switch { 0 => _v0, 1 => _v1, 2 => _v2, 3 => _v3, 4 => _v4, 5 => _v5, 6 => _v6, 7 => _v7, 8 => _v8, 9 => _v9, 10 => _v10, 11 => _v11, 12 => _v12, 13 => _v13, 14 => _v14, _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen.") }; } } /// <inheritdoc /> public int Index => _ix; /// <inheritdoc /> public bool IsT0() => _ix == 0; /// <inheritdoc /> public bool IsT1() => _ix == 1; /// <inheritdoc /> public bool IsT2() => _ix == 2; /// <inheritdoc /> public bool IsT3() => _ix == 3; /// <inheritdoc /> public bool IsT4() => _ix == 4; /// <inheritdoc /> public bool IsT5() => _ix == 5; /// <inheritdoc /> public bool IsT6() => _ix == 6; /// <inheritdoc /> public bool IsT7() => _ix == 7; /// <inheritdoc /> public bool IsT8() => _ix == 8; /// <inheritdoc /> public bool IsT9() => _ix == 9; /// <inheritdoc /> public bool IsT10() => _ix == 10; /// <inheritdoc /> public bool IsT11() => _ix == 11; /// <inheritdoc /> public bool IsT12() => _ix == 12; /// <inheritdoc /> public bool IsT13() => _ix == 13; /// <inheritdoc /> public bool IsT14() => _ix == 14; /// <inheritdoc /> public T0 AsT0() { return _ix == 0 ? _v0 : throw new InvalidOperationException($"Cannot return as T0 as result is T{_ix}"); } /// <inheritdoc /> public T1 AsT1() { return _ix == 1 ? _v1 : throw new InvalidOperationException($"Cannot return as T1 as result is T{_ix}"); } /// <inheritdoc /> public T2 AsT2() { return _ix == 2 ? _v2 : throw new InvalidOperationException($"Cannot return as T2 as result is T{_ix}"); } /// <inheritdoc /> public T3 AsT3() { return _ix == 3 ? _v3 : throw new InvalidOperationException($"Cannot return as T3 as result is T{_ix}"); } /// <inheritdoc /> public T4 AsT4() { return _ix == 4 ? _v4 : throw new InvalidOperationException($"Cannot return as T4 as result is T{_ix}"); } /// <inheritdoc /> public T5 AsT5() { return _ix == 5 ? _v5 : throw new InvalidOperationException($"Cannot return as T5 as result is T{_ix}"); } /// <inheritdoc /> public T6 AsT6() { return _ix == 6 ? _v6 : throw new InvalidOperationException($"Cannot return as T6 as result is T{_ix}"); } /// <inheritdoc /> public T7 AsT7() { return _ix == 7 ? _v7 : throw new InvalidOperationException($"Cannot return as T7 as result is T{_ix}"); } /// <inheritdoc /> public T8 AsT8() { return _ix == 8 ? _v8 : throw new InvalidOperationException($"Cannot return as T8 as result is T{_ix}"); } /// <inheritdoc /> public T9 AsT9() { return _ix == 9 ? _v9 : throw new InvalidOperationException($"Cannot return as T9 as result is T{_ix}"); } /// <inheritdoc /> public T10 AsT10() { return _ix == 10 ? _v10 : throw new InvalidOperationException($"Cannot return as T10 as result is T{_ix}"); } /// <inheritdoc /> public T11 AsT11() { return _ix == 11 ? _v11 : throw new InvalidOperationException($"Cannot return as T11 as result is T{_ix}"); } /// <inheritdoc /> public T12 AsT12() { return _ix == 12 ? _v12 : throw new InvalidOperationException($"Cannot return as T12 as result is T{_ix}"); } /// <inheritdoc /> public T13 AsT13() { return _ix == 13 ? _v13 : throw new InvalidOperationException($"Cannot return as T13 as result is T{_ix}"); } /// <inheritdoc /> public T14 AsT14() { return _ix == 14 ? _v14 : throw new InvalidOperationException($"Cannot return as T14 as result is T{_ix}"); } public void Switch(Action<T0> f0, Action<T1> f1, Action<T2> f2, Action<T3> f3, Action<T4> f4, Action<T5> f5, Action<T6> f6, Action<T7> f7, Action<T8> f8, Action<T9> f9, Action<T10> f10, Action<T11> f11, Action<T12> f12, Action<T13> f13, Action<T14> f14) { if (_ix is 0 && f0 is not null) { f0(_v0); return; } if (_ix is 1 && f1 is not null) { f1(_v1); return; } if (_ix is 2 && f2 is not null) { f2(_v2); return; } if (_ix is 3 && f3 is not null) { f3(_v3); return; } if (_ix is 4 && f4 is not null) { f4(_v4); return; } if (_ix is 5 && f5 is not null) { f5(_v5); return; } if (_ix is 6 && f6 is not null) { f6(_v6); return; } if (_ix is 7 && f7 is not null) { f7(_v7); return; } if (_ix is 8 && f8 is not null) { f8(_v8); return; } if (_ix is 9 && f9 is not null) { f9(_v9); return; } if (_ix is 10 && f10 is not null) { f10(_v10); return; } if (_ix is 11 && f11 is not null) { f11(_v11); return; } if (_ix is 12 && f12 is not null) { f12(_v12); return; } if (_ix is 13 && f13 is not null) { f13(_v13); return; } if (_ix is 14 && f14 is not null) { f14(_v14); return; } throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen."); } public TResult Match<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2, Func<T3, TResult> f3, Func<T4, TResult> f4, Func<T5, TResult> f5, Func<T6, TResult> f6, Func<T7, TResult> f7, Func<T8, TResult> f8, Func<T9, TResult> f9, Func<T10, TResult> f10, Func<T11, TResult> f11, Func<T12, TResult> f12, Func<T13, TResult> f13, Func<T14, TResult> f14) { if (_ix is 0 && f0 is not null) { return f0(_v0); } if (_ix is 1 && f1 is not null) { return f1(_v1); } if (_ix is 2 && f2 is not null) { return f2(_v2); } if (_ix is 3 && f3 is not null) { return f3(_v3); } if (_ix is 4 && f4 is not null) { return f4(_v4); } if (_ix is 5 && f5 is not null) { return f5(_v5); } if (_ix is 6 && f6 is not null) { return f6(_v6); } if (_ix is 7 && f7 is not null) { return f7(_v7); } if (_ix is 8 && f8 is not null) { return f8(_v8); } if (_ix is 9 && f9 is not null) { return f9(_v9); } if (_ix is 10 && f10 is not null) { return f10(_v10); } if (_ix is 11 && f11 is not null) { return f11(_v11); } if (_ix is 12 && f12 is not null) { return f12(_v12); } if (_ix is 13 && f13 is not null) { return f13(_v13); } if (_ix is 14 && f14 is not null) { return f14(_v14); } throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen."); } /// <summary> /// Try to get the value of the first type <br /> /// 尝试获取第 1 个类型的值 /// </summary> /// <param name="value"></param> /// <param name="remainder"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public bool TryPickT0(out T0 value, out UnionType<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> remainder) { value = IsT0() ? AsT0() : default; remainder = _ix switch { 0 => default, 1 => AsT1(), 2 => AsT2(), 3 => AsT3(), 4 => AsT4(), 5 => AsT5(), 6 => AsT6(), 7 => AsT7(), 8 => AsT8(), 9 => AsT9(), 10 => AsT10(), 11 => AsT11(), 12 => AsT12(), 13 => AsT13(), 14 => AsT14(), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen.") }; return IsT0(); } /// <summary> /// Try to get the value of the second type <br /> /// 尝试获取第 2 个类型的值 /// </summary> /// <param name="value"></param> /// <param name="remainder"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public bool TryPickT1(out T1 value, out UnionType<T0, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> remainder) { value = IsT1() ? AsT1() : default; remainder = _ix switch { 0 => AsT0(), 1 => default, 2 => AsT2(), 3 => AsT3(), 4 => AsT4(), 5 => AsT5(), 6 => AsT6(), 7 => AsT7(), 8 => AsT8(), 9 => AsT9(), 10 => AsT10(), 11 => AsT11(), 12 => AsT12(), 13 => AsT13(), 14 => AsT14(), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen.") }; return IsT1(); } /// <summary> /// Try to get the value of the third type <br /> /// 尝试获取第 3 个类型的值 /// </summary> /// <param name="value"></param> /// <param name="remainder"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public bool TryPickT2(out T2 value, out UnionType<T0, T1, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> remainder) { value = IsT2() ? AsT2() : default; remainder = _ix switch { 0 => AsT0(), 1 => AsT1(), 2 => default, 3 => AsT3(), 4 => AsT4(), 5 => AsT5(), 6 => AsT6(), 7 => AsT7(), 8 => AsT8(), 9 => AsT9(), 10 => AsT10(), 11 => AsT11(), 12 => AsT12(), 13 => AsT13(), 14 => AsT14(), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen.") }; return IsT2(); } /// <summary> /// Try to get the value of the forth type <br /> /// 尝试获取第 4 个类型的值 /// </summary> /// <param name="value"></param> /// <param name="remainder"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public bool TryPickT3(out T3 value, out UnionType<T0, T1, T2, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> remainder) { value = IsT3() ? AsT3() : default; remainder = _ix switch { 0 => AsT0(), 1 => AsT1(), 2 => AsT2(), 3 => default, 4 => AsT4(), 5 => AsT5(), 6 => AsT6(), 7 => AsT7(), 8 => AsT8(), 9 => AsT9(), 10 => AsT10(), 11 => AsT11(), 12 => AsT12(), 13 => AsT13(), 14 => AsT14(), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen.") }; return IsT3(); } /// <summary> /// Try to get the value of the fifth type <br /> /// 尝试获取第 5 个类型的值 /// </summary> /// <param name="value"></param> /// <param name="remainder"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public bool TryPickT4(out T4 value, out UnionType<T0, T1, T2, T3, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> remainder) { value = IsT4() ? AsT4() : default; remainder = _ix switch { 0 => AsT0(), 1 => AsT1(), 2 => AsT2(), 3 => AsT3(), 4 => default, 5 => AsT5(), 6 => AsT6(), 7 => AsT7(), 8 => AsT8(), 9 => AsT9(), 10 => AsT10(), 11 => AsT11(), 12 => AsT12(), 13 => AsT13(), 14 => AsT14(), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen.") }; return IsT4(); } /// <summary> /// Try to get the value of the sixth type <br /> /// 尝试获取第 6 个类型的值 /// </summary> /// <param name="value"></param> /// <param name="remainder"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public bool TryPickT5(out T5 value, out UnionType<T0, T1, T2, T3, T4, T6, T7, T8, T9, T10, T11, T12, T13, T14> remainder) { value = IsT5() ? AsT5() : default; remainder = _ix switch { 0 => AsT0(), 1 => AsT1(), 2 => AsT2(), 3 => AsT3(), 4 => AsT4(), 5 => default, 6 => AsT6(), 7 => AsT7(), 8 => AsT8(), 9 => AsT9(), 10 => AsT10(), 11 => AsT11(), 12 => AsT12(), 13 => AsT13(), 14 => AsT14(), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen.") }; return IsT5(); } /// <summary> /// Try to get the value of the seventh type <br /> /// 尝试获取第 7 个类型的值 /// </summary> /// <param name="value"></param> /// <param name="remainder"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public bool TryPickT6(out T6 value, out UnionType<T0, T1, T2, T3, T4, T5, T7, T8, T9, T10, T11, T12, T13, T14> remainder) { value = IsT6() ? AsT6() : default; remainder = _ix switch { 0 => AsT0(), 1 => AsT1(), 2 => AsT2(), 3 => AsT3(), 4 => AsT4(), 5 => AsT5(), 6 => default, 7 => AsT7(), 8 => AsT8(), 9 => AsT9(), 10 => AsT10(), 11 => AsT11(), 12 => AsT12(), 13 => AsT13(), 14 => AsT14(), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen.") }; return IsT6(); } /// <summary> /// Try to get the value of the eighth type <br /> /// 尝试获取第 8 个类型的值 /// </summary> /// <param name="value"></param> /// <param name="remainder"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public bool TryPickT7(out T7 value, out UnionType<T0, T1, T2, T3, T4, T5, T6, T8, T9, T10, T11, T12, T13, T14> remainder) { value = IsT7() ? AsT7() : default; remainder = _ix switch { 0 => AsT0(), 1 => AsT1(), 2 => AsT2(), 3 => AsT3(), 4 => AsT4(), 5 => AsT5(), 6 => AsT6(), 7 => default, 8 => AsT8(), 9 => AsT9(), 10 => AsT10(), 11 => AsT11(), 12 => AsT12(), 13 => AsT13(), 14 => AsT14(), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen.") }; return IsT7(); } /// <summary> /// Try to get the value of the ninth type <br /> /// 尝试获取第 9 个类型的值 /// </summary> /// <param name="value"></param> /// <param name="remainder"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public bool TryPickT8(out T8 value, out UnionType<T0, T1, T2, T3, T4, T5, T6, T7, T9, T10, T11, T12, T13, T14> remainder) { value = IsT8() ? AsT8() : default; remainder = _ix switch { 0 => AsT0(), 1 => AsT1(), 2 => AsT2(), 3 => AsT3(), 4 => AsT4(), 5 => AsT5(), 6 => AsT6(), 7 => AsT7(), 8 => default, 9 => AsT9(), 10 => AsT10(), 11 => AsT11(), 12 => AsT12(), 13 => AsT13(), 14 => AsT14(), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen.") }; return IsT8(); } /// <summary> /// Try to get the value of the tenth type <br /> /// 尝试获取第 10 个类型的值 /// </summary> /// <param name="value"></param> /// <param name="remainder"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public bool TryPickT9(out T9 value, out UnionType<T0, T1, T2, T3, T4, T5, T6, T7, T8, T10, T11, T12, T13, T14> remainder) { value = IsT9() ? AsT9() : default; remainder = _ix switch { 0 => AsT0(), 1 => AsT1(), 2 => AsT2(), 3 => AsT3(), 4 => AsT4(), 5 => AsT5(), 6 => AsT6(), 7 => AsT7(), 8 => AsT8(), 9 => default, 10 => AsT10(), 11 => AsT11(), 12 => AsT12(), 13 => AsT13(), 14 => AsT14(), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen.") }; return IsT9(); } /// <summary> /// Try to get the value of the eleventh type <br /> /// 尝试获取第 11 个类型的值 /// </summary> /// <param name="value"></param> /// <param name="remainder"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public bool TryPickT10(out T10 value, out UnionType<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T11, T12, T13, T14> remainder) { value = IsT10() ? AsT10() : default; remainder = _ix switch { 0 => AsT0(), 1 => AsT1(), 2 => AsT2(), 3 => AsT3(), 4 => AsT4(), 5 => AsT5(), 6 => AsT6(), 7 => AsT7(), 8 => AsT8(), 9 => AsT9(), 10 => default, 11 => AsT11(), 12 => AsT12(), 13 => AsT13(), 14 => AsT14(), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen.") }; return IsT10(); } /// <summary> /// Try to get the value of the twelfth type <br /> /// 尝试获取第 12 个类型的值 /// </summary> /// <param name="value"></param> /// <param name="remainder"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public bool TryPickT11(out T11 value, out UnionType<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T12, T13, T14> remainder) { value = IsT11() ? AsT11() : default; remainder = _ix switch { 0 => AsT0(), 1 => AsT1(), 2 => AsT2(), 3 => AsT3(), 4 => AsT4(), 5 => AsT5(), 6 => AsT6(), 7 => AsT7(), 8 => AsT8(), 9 => AsT9(), 10 => AsT10(), 11 => default, 12 => AsT12(), 13 => AsT13(), 14 => AsT14(), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen.") }; return IsT11(); } /// <summary> /// Try to get the value of the thirteenth type <br /> /// 尝试获取第 13 个类型的值 /// </summary> /// <param name="value"></param> /// <param name="remainder"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public bool TryPickT12(out T12 value, out UnionType<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T13, T14> remainder) { value = IsT12() ? AsT12() : default; remainder = _ix switch { 0 => AsT0(), 1 => AsT1(), 2 => AsT2(), 3 => AsT3(), 4 => AsT4(), 5 => AsT5(), 6 => AsT6(), 7 => AsT7(), 8 => AsT8(), 9 => AsT9(), 10 => AsT10(), 11 => AsT11(), 12 => default, 13 => AsT13(), 14 => AsT14(), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen.") }; return IsT12(); } /// <summary> /// Try to get the value of the fourteenth type <br /> /// 尝试获取第 14 个类型的值 /// </summary> /// <param name="value"></param> /// <param name="remainder"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public bool TryPickT13(out T13 value, out UnionType<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T14> remainder) { value = IsT13() ? AsT13() : default; remainder = _ix switch { 0 => AsT0(), 1 => AsT1(), 2 => AsT2(), 3 => AsT3(), 4 => AsT4(), 5 => AsT5(), 6 => AsT6(), 7 => AsT7(), 8 => AsT8(), 9 => AsT9(), 10 => AsT10(), 11 => AsT11(), 12 => AsT12(), 13 => default, 14 => AsT14(), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen.") }; return IsT13(); } /// <summary> /// Try to get the value of the fifteenth type <br /> /// 尝试获取第 15 个类型的值 /// </summary> /// <param name="value"></param> /// <param name="remainder"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public bool TryPickT14(out T14 value, out UnionType<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> remainder) { value = IsT14() ? AsT14() : default; remainder = _ix switch { 0 => AsT0(), 1 => AsT1(), 2 => AsT2(), 3 => AsT3(), 4 => AsT4(), 5 => AsT5(), 6 => AsT6(), 7 => AsT7(), 8 => AsT8(), 9 => AsT9(), 10 => AsT10(), 11 => AsT11(), 12 => AsT12(), 13 => AsT13(), 14 => default, _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen.") }; return IsT14(); } bool Equals(UnionOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> other) { return _ix == other._ix && _ix switch { 0 => Equals(_v0, other._v0), 1 => Equals(_v1, other._v1), 2 => Equals(_v2, other._v2), 3 => Equals(_v3, other._v3), 4 => Equals(_v4, other._v4), 5 => Equals(_v5, other._v5), 6 => Equals(_v6, other._v6), 7 => Equals(_v7, other._v7), 8 => Equals(_v8, other._v8), 9 => Equals(_v9, other._v9), 10 => Equals(_v10, other._v10), 11 => Equals(_v11, other._v11), 12 => Equals(_v12, other._v12), 13 => Equals(_v13, other._v13), 14 => Equals(_v14, other._v14), _ => false }; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj is UnionOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> o && Equals(o); } public override string ToString() { return _ix switch { 0 => FormatHelper.FormatValue(_v0), 1 => FormatHelper.FormatValue(_v1), 2 => FormatHelper.FormatValue(_v2), 3 => FormatHelper.FormatValue(_v3), 4 => FormatHelper.FormatValue(_v4), 5 => FormatHelper.FormatValue(_v5), 6 => FormatHelper.FormatValue(_v6), 7 => FormatHelper.FormatValue(_v7), 8 => FormatHelper.FormatValue(_v8), 9 => FormatHelper.FormatValue(_v9), 10 => FormatHelper.FormatValue(_v10), 11 => FormatHelper.FormatValue(_v11), 12 => FormatHelper.FormatValue(_v12), 13 => FormatHelper.FormatValue(_v13), 14 => FormatHelper.FormatValue(_v14), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the UnionOf codegen.") }; } public override int GetHashCode() { unchecked { int hashCode = _ix switch { 0 => _v0?.GetHashCode(), 1 => _v1?.GetHashCode(), 2 => _v2?.GetHashCode(), 3 => _v3?.GetHashCode(), 4 => _v4?.GetHashCode(), 5 => _v5?.GetHashCode(), 6 => _v6?.GetHashCode(), 7 => _v7?.GetHashCode(), 8 => _v8?.GetHashCode(), 9 => _v9?.GetHashCode(), 10 => _v10?.GetHashCode(), 11 => _v11?.GetHashCode(), 12 => _v12?.GetHashCode(), 13 => _v13?.GetHashCode(), 14 => _v14?.GetHashCode(), _ => 0 } ?? 0; return (hashCode * 397) ^ _ix; } } }
28.596774
231
0.450416
[ "Apache-2.0" ]
cosmos-loops/Cosmos.Standard
src/Cosmos.Extensions.Optionals/Cosmos/UnionTypes/UnionOf`14.cs
30,451
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.Maui.CustomAttributes; using System.Maui.Internals; #if UITEST using Xamarin.UITest; using NUnit.Framework; using System.Maui.Core.UITests; #endif namespace System.Maui.Controls.Issues { [Preserve(AllMembers = true)] [Issue(IssueTracker.Github, 4484, "[Android] ImageButton inside NavigationView.TitleView throw exception during device rotation", PlatformAffected.Android)] #if UITEST [NUnit.Framework.Category(UITestCategories.Image)] #endif public class Issue4484 : TestNavigationPage { protected override void Init() { ContentPage page = new ContentPage(); NavigationPage.SetTitleView(page, new StackLayout() { Orientation = StackOrientation.Horizontal, Children = { new Button(){ ImageSource = "bank.png", AutomationId="bank"}, new Image(){Source = "bank.png"}, new ImageButton{Source = "bank.png"} } }); page.Content = new StackLayout() { Children = { new Label() { Text = "You should see 3 images. Rotate device. If it doesn't crash then test has passed", AutomationId = "Instructions" } } }; PushAsync(page); } #if UITEST [Test] public void RotatingDeviceDoesntCrashTitleView() { RunningApp.WaitForElement("Instructions"); RunningApp.SetOrientationLandscape(); RunningApp.WaitForElement("Instructions"); RunningApp.SetOrientationPortrait(); RunningApp.WaitForElement("Instructions"); } #endif } }
22.797101
130
0.706929
[ "MIT" ]
AswinPG/maui
System.Maui.Controls.Issues/System.Maui.Controls.Issues.Shared/Issue4484.cs
1,573
C#
// 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 (c) 2004 Novell, Inc. // // Authors: // Peter Bartok pbartok@novell.com // using System.ComponentModel; namespace System.Windows.Forms { public class ApplicationContext : IDisposable { #region Local Variables Form main_form; object tag; bool thread_exit_raised; #endregion // Local Variables #region Public Constructors & Destructors public ApplicationContext() : this(null) { } public ApplicationContext(Form mainForm) { MainForm = mainForm; // Use property to get event handling setup } ~ApplicationContext() { this.Dispose(false); } #endregion // Public Constructors & Destructors #region Public Instance Properties public Form MainForm { get { return main_form; } set { if (main_form != value) { // Catch when the form is destroyed so we can fire OnMainFormClosed if (main_form != null) { main_form.HandleDestroyed -= new EventHandler(OnMainFormClosed); } main_form = value; if (main_form != null) { main_form.HandleDestroyed += new EventHandler(OnMainFormClosed); } } } } [BindableAttribute (true)] [DefaultValue (null)] [LocalizableAttribute (false)] [TypeConverterAttribute (typeof(StringConverter))] public Object Tag { get { return tag; } set { tag = value; } } #endregion // Public Instance Properties #region Public Instance Methods public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void ExitThread() { ExitThreadCore(); } #endregion // Public Instance Methods #region Protected Instance Methods protected virtual void Dispose(bool disposing) { MainForm = null; tag = null; } protected virtual void ExitThreadCore() { if (Application.MWFThread.Current.Context == this) XplatUI.PostQuitMessage(0); if (!thread_exit_raised && ThreadExit != null) { thread_exit_raised = true; ThreadExit(this, EventArgs.Empty); } } protected virtual void OnMainFormClosed(object sender, EventArgs e) { if (!MainForm.RecreatingHandle) ExitThreadCore(); } #endregion // Public Instance Methods #region Events public event EventHandler ThreadExit; #endregion // Events } }
27.756303
73
0.712988
[ "Apache-2.0" ]
121468615/mono
mcs/class/Managed.Windows.Forms/System.Windows.Forms/ApplicationContext.cs
3,303
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using System.Data; using System.Data.SqlClient; namespace TOS.DAL { public class MSSQL { /// <summary> /// 连接字符串 /// </summary> private static string conStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString; #region 查询 /// <summary> /// 查询 /// </summary> /// <param name="sql">查询SQL</param> /// <returns>DataTable</returns> public static DataTable query(string sql) { using (SqlConnection con = new SqlConnection(conStr)) { SqlDataAdapter sda = new SqlDataAdapter(sql, con); DataTable dt = new DataTable(); sda.Fill(dt); return dt; } } public static DataTable query(string sql, params SqlParameter[] pars) { using (SqlDataAdapter adapter = new SqlDataAdapter(sql, conStr)) { adapter.SelectCommand.CommandType = CommandType.Text; DataTable dt = new DataTable(); adapter.SelectCommand.CommandText = sql; if (pars != null) { adapter.SelectCommand.Parameters.AddRange(pars); } adapter.Fill(dt); return dt; } } #endregion #region 非查询 /// <summary> /// 非查询 /// </summary> /// <param name="sql">非查询SQL</param> /// <returns>受影响的条数</returns> public static int noQuery(string sql) { int result = -1; using (SqlConnection con = new SqlConnection(conStr)) { con.Open(); SqlCommand com = new SqlCommand(sql, con); result = com.ExecuteNonQuery(); return result; } } public static int noQuery(string sql, params SqlParameter[] pars) { int result = -1; using (SqlConnection con = new SqlConnection(conStr)) { con.Open(); SqlCommand com = new SqlCommand(sql, con); com.Parameters.AddRange(pars); result = com.ExecuteNonQuery(); return result; } } #endregion #region 执行存储过程-非查询 public static int ExecProcNonQuery(string procName, params SqlParameter[] pars) { using (SqlConnection conn = new SqlConnection(conStr)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = procName; cmd.Parameters.AddRange(pars); return cmd.ExecuteNonQuery(); } } #endregion } }
29.643564
105
0.506012
[ "MIT" ]
yiyungent/TOS
TOS.DAL/MSSQL.cs
3,066
C#
using CgbPostBuildHelper.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Text.RegularExpressions; using Diag = System.Diagnostics; using System.Security.Cryptography; using CgbPostBuildHelper.ViewModel; using Assimp; using System.Runtime.InteropServices; namespace CgbPostBuildHelper.Deployers { class CopyFileDeployment : DeploymentBase { public override void Deploy() { var outPath = new FileInfo(_outputFilePath); Directory.CreateDirectory(outPath.DirectoryName); var assetFileModel = PrepareNewAssetFile(null); assetFileModel.FileType = FileType.Generic; assetFileModel.OutputFilePath = outPath.FullName; // Now, are we going to copy or are we going to symlink? DeployFile(assetFileModel); FilesDeployed.Add(assetFileModel); } } }
23.184211
59
0.786606
[ "MIT" ]
johannesugb/CG-Base
visual_studio/tools/sources/cgb_post_build_helper/cgb_post_build_helper/Deployers/CopyFileDeployment.cs
883
C#
namespace usagi.Collection.Extension { /// <summary> /// IEnumerable, IDictionary など Collection 向けの Extension /// </summary> [System.Runtime.CompilerServices.CompilerGeneratedAttribute] internal class NamespaceDoc { } }
28.875
62
0.748918
[ "MIT" ]
usagi/usagi.cs
usagi/Collection/Extension/Extension.cs
243
C#
// Modified from http://mvccontrib.codeplex.com // Copyright 2007-2010 Eric Hexter, Jeffrey Palermo using System.Linq; using System.Reflection; using System.Web.Http; namespace WebApiContrib.Testing.Internal.Extensions { internal static class MethodInfoExtensions { /// <summary> /// Returns the name of the action specified in the ActionNameAttribute or the name of the method if no attribute is present. /// </summary> /// <param name="method"></param> public static string ActionName(this MethodInfo method) { if (method.HasAttribute<ActionNameAttribute>()) return method.GetAttribute<ActionNameAttribute>().First().Name; return method.Name; } } }
31.75
133
0.665354
[ "MIT" ]
Udit-Sharma/WebAPIContrib
src/WebApiContrib.Testing/Internal/Extensions/MethodInfoExtensions.cs
764
C#
using System.Collections.Generic; using Essensoft.Paylink.Alipay.Response; namespace Essensoft.Paylink.Alipay.Request { /// <summary> /// mybank.credit.guarantee.contract.sign /// </summary> public class MybankCreditGuaranteeContractSignRequest : IAlipayRequest<MybankCreditGuaranteeContractSignResponse> { /// <summary> /// 担保服务开通 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; private Dictionary<string, string> udfParams; //add user-defined text parameters public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "mybank.credit.guarantee.contract.sign"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public void PutOtherTextParam(string key, string value) { if (udfParams == null) { udfParams = new Dictionary<string, string>(); } udfParams.Add(key, value); } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; if (udfParams != null) { parameters.AddAll(udfParams); } return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.601449
117
0.540682
[ "MIT" ]
Frunck8206/payment
src/Essensoft.Paylink.Alipay/Request/MybankCreditGuaranteeContractSignRequest.cs
3,271
C#
using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace SigParser.Model { /// <summary> /// Details about a company based on the domain name. You should only map this to your CRM if your CRM only has one Account/Organization record per company. /// </summary> [DataContract] public class DragnetTechSharedIPAASModelsCompanyOutputModel { /// <summary> /// Valid, Other, Coworker, Private, Ignore. Other possible values may be added later. /// </summary> /// <value>Valid, Other, Coworker, Private, Ignore. Other possible values may be added later.</value> [DataMember(Name="status", EmitDefaultValue=false)] [JsonProperty(PropertyName = "status")] public string Status { get; set; } /// <summary> /// The best name SigParser has found or that has been set by a user. /// </summary> /// <value>The best name SigParser has found or that has been set by a user.</value> [DataMember(Name="name", EmitDefaultValue=false)] [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// Numeric value representing when this record was last modified. This has precision down to the millisecond so you shouldn't convert it to a date with less precision. /// </summary> /// <value>Numeric value representing when this record was last modified. This has precision down to the millisecond so you shouldn't convert it to a date with less precision.</value> [DataMember(Name="lastmodified", EmitDefaultValue=false)] [JsonProperty(PropertyName = "lastmodified")] public long? Lastmodified { get; set; } /// <summary> /// Number of Valid or Other contacts on this account. Coworker, Private and Ignore contacts are ignored when counting. /// </summary> /// <value>Number of Valid or Other contacts on this account. Coworker, Private and Ignore contacts are ignored when counting.</value> [DataMember(Name="contacts", EmitDefaultValue=false)] [JsonProperty(PropertyName = "contacts")] public int? Contacts { get; set; } /// <summary> /// Total emails from people at this company to your company. /// </summary> /// <value>Total emails from people at this company to your company.</value> [DataMember(Name="inbound_emails", EmitDefaultValue=false)] [JsonProperty(PropertyName = "inbound_emails")] public int? InboundEmails { get; set; } /// <summary> /// Total emails from your company to this company. /// </summary> /// <value>Total emails from your company to this company.</value> [DataMember(Name="outbound_emails", EmitDefaultValue=false)] [JsonProperty(PropertyName = "outbound_emails")] public int? OutboundEmails { get; set; } /// <summary> /// Meetings with this company's employees. /// </summary> /// <value>Meetings with this company's employees.</value> [DataMember(Name="meetings", EmitDefaultValue=false)] [JsonProperty(PropertyName = "meetings")] public int? Meetings { get; set; } /// <summary> /// Last time there was an email or a meeting with this company. /// </summary> /// <value>Last time there was an email or a meeting with this company.</value> [DataMember(Name="last_interaction", EmitDefaultValue=false)] [JsonProperty(PropertyName = "last_interaction")] public DateTime? LastInteraction { get; set; } /// <summary> /// The email domain name for this company. This is a primary key for the table so if the company has multiple domain names then there will be a Company record for each domain. /// </summary> /// <value>The email domain name for this company. This is a primary key for the table so if the company has multiple domain names then there will be a Company record for each domain.</value> [DataMember(Name="domain", EmitDefaultValue=false)] [JsonProperty(PropertyName = "domain")] public string Domain { get; set; } /// <summary> /// Email address of someone in your company with the best relationsip with this account. /// </summary> /// <value>Email address of someone in your company with the best relationsip with this account.</value> [DataMember(Name="closest_internal_contact", EmitDefaultValue=false)] [JsonProperty(PropertyName = "closest_internal_contact")] public string ClosestInternalContact { get; set; } /// <summary> /// The internal contact who has the most active relationship with this company. /// </summary> /// <value>The internal contact who has the most active relationship with this company.</value> [DataMember(Name="internal_contact_most_active", EmitDefaultValue=false)] [JsonProperty(PropertyName = "internal_contact_most_active")] public string InternalContactMostActive { get; set; } /// <summary> /// The internal contact who has most recently interacted with this company. /// </summary> /// <value>The internal contact who has most recently interacted with this company.</value> [DataMember(Name="internal_contact_latest", EmitDefaultValue=false)] [JsonProperty(PropertyName = "internal_contact_latest")] public string InternalContactLatest { get; set; } /// <summary> /// The date of the latest communication with this company. /// </summary> /// <value>The date of the latest communication with this company.</value> [DataMember(Name="internal_contact_latest_date", EmitDefaultValue=false)] [JsonProperty(PropertyName = "internal_contact_latest_date")] public DateTime? InternalContactLatestDate { get; set; } /// <summary> /// The internal contact who first established communications with this company. /// </summary> /// <value>The internal contact who first established communications with this company.</value> [DataMember(Name="internal_contact_first", EmitDefaultValue=false)] [JsonProperty(PropertyName = "internal_contact_first")] public string InternalContactFirst { get; set; } /// <summary> /// The date of first established communication with this company. /// </summary> /// <value>The date of first established communication with this company.</value> [DataMember(Name="internal_contact_first_date", EmitDefaultValue=false)] [JsonProperty(PropertyName = "internal_contact_first_date")] public DateTime? InternalContactFirstDate { get; set; } /// <summary> /// The number of internal contacts who have an established relationship with a contact at this company. /// </summary> /// <value>The number of internal contacts who have an established relationship with a contact at this company.</value> [DataMember(Name="relationships_coworker", EmitDefaultValue=false)] [JsonProperty(PropertyName = "relationships_coworker")] public int? RelationshipsCoworker { get; set; } /// <summary> /// A count of relationships with this company that are not internal contacts and not within the same company. /// </summary> /// <value>A count of relationships with this company that are not internal contacts and not within the same company.</value> [DataMember(Name="relationships_other", EmitDefaultValue=false)] [JsonProperty(PropertyName = "relationships_other")] public int? RelationshipsOther { get; set; } /// <summary> /// Email addresses of the top 5 Coworkers (internal) to your company who know this contact the best based on interactions. /// </summary> /// <value>Email addresses of the top 5 Coworkers (internal) to your company who know this contact the best based on interactions.</value> [DataMember(Name="coworker_relationships_emailaddresses", EmitDefaultValue=false)] [JsonProperty(PropertyName = "coworker_relationships_emailaddresses")] public List<string> CoworkerRelationshipsEmailaddresses { get; set; } /// <summary> /// Email addresses of the top 5 contacts who work at the same company who have been on emails and meetings. /// </summary> /// <value>Email addresses of the top 5 contacts who work at the same company who have been on emails and meetings.</value> [DataMember(Name="company_relationships_emailaddresses", EmitDefaultValue=false)] [JsonProperty(PropertyName = "company_relationships_emailaddresses")] public List<string> CompanyRelationshipsEmailaddresses { get; set; } /// <summary> /// Email addresses of the top 5 people who have been on emails with this contact from other companies. /// </summary> /// <value>Email addresses of the top 5 people who have been on emails with this contact from other companies.</value> [DataMember(Name="other_relationships_emailaddresses", EmitDefaultValue=false)] [JsonProperty(PropertyName = "other_relationships_emailaddresses")] public List<string> OtherRelationshipsEmailaddresses { get; set; } /// <summary> /// Gets or Sets Tags /// </summary> [DataMember(Name="tags", EmitDefaultValue=false)] [JsonProperty(PropertyName = "tags")] public List<DragnetTechSharedIPAASModelsTag> Tags { get; set; } /// <summary> /// Get the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DragnetTechSharedIPAASModelsCompanyOutputModel {\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Lastmodified: ").Append(Lastmodified).Append("\n"); sb.Append(" Contacts: ").Append(Contacts).Append("\n"); sb.Append(" InboundEmails: ").Append(InboundEmails).Append("\n"); sb.Append(" OutboundEmails: ").Append(OutboundEmails).Append("\n"); sb.Append(" Meetings: ").Append(Meetings).Append("\n"); sb.Append(" LastInteraction: ").Append(LastInteraction).Append("\n"); sb.Append(" Domain: ").Append(Domain).Append("\n"); sb.Append(" ClosestInternalContact: ").Append(ClosestInternalContact).Append("\n"); sb.Append(" InternalContactMostActive: ").Append(InternalContactMostActive).Append("\n"); sb.Append(" InternalContactLatest: ").Append(InternalContactLatest).Append("\n"); sb.Append(" InternalContactLatestDate: ").Append(InternalContactLatestDate).Append("\n"); sb.Append(" InternalContactFirst: ").Append(InternalContactFirst).Append("\n"); sb.Append(" InternalContactFirstDate: ").Append(InternalContactFirstDate).Append("\n"); sb.Append(" RelationshipsCoworker: ").Append(RelationshipsCoworker).Append("\n"); sb.Append(" RelationshipsOther: ").Append(RelationshipsOther).Append("\n"); sb.Append(" CoworkerRelationshipsEmailaddresses: ").Append(CoworkerRelationshipsEmailaddresses).Append("\n"); sb.Append(" CompanyRelationshipsEmailaddresses: ").Append(CompanyRelationshipsEmailaddresses).Append("\n"); sb.Append(" OtherRelationshipsEmailaddresses: ").Append(OtherRelationshipsEmailaddresses).Append("\n"); sb.Append(" Tags: ").Append(Tags).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Get the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } }
51.346667
197
0.703367
[ "MIT" ]
DragnetTech/SigParserDotNetApis
src/main/CsharpDotNet2/SigParser/Model/DragnetTechSharedIPAASModelsCompanyOutputModel.cs
11,553
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Tanneryd.BulkOperations.EF6.NET47.ModelFirst.Tests.Models.EF { using System; using System.Collections.Generic; public partial class BatchInvoiceItem { public System.Guid Id { get; set; } public System.Guid BatchInvoiceId { get; set; } public System.Guid InvoiceId { get; set; } public virtual BatchInvoice BatchInvoice { get; set; } public virtual Invoice Invoice { get; set; } } }
35.44
85
0.553047
[ "Apache-2.0" ]
360imprimir/ef6-bulk-operations
Tanneryd.BulkOperations.EF6/Tanneryd.BulkOperations.EF6.NET47.ModelFirst.Tests/Models/EF/BatchInvoiceItem.cs
886
C#
namespace FlatFile.Delimited { using FlatFile.Core; public interface IDelimitedLineBuilderFactory : ILineBuilderFactory<IDelimitedLineBuilder, IDelimitedLayoutDescriptor, IDelimitedFieldSettingsContainer> { } }
26.111111
112
0.782979
[ "MIT" ]
Peter-LaComb/FlatFile
FlatFile.Delimited/IDelimitedLineBuilderFactory.cs
235
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; using WooCommerceNET.Base; namespace WooCommerceNET.WooCommerce.v2 { public class CustomerBatch : BatchObject<Customer> { } [DataContract] public class Customer : JsonObject { public static string Endpoint { get { return "customers"; } } /// <summary> /// Unique identifier for the resource. /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public long? id { get; set; } /// <summary> /// The date the customer was created, in the site’s timezone. /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public DateTime? date_created { get; set; } /// <summary> /// The date the order was created, as GMT. /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public DateTime? date_created_gmt { get; set; } /// <summary> /// The date the customer was last modified, in the site’s timezone. /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public DateTime? date_modified { get; set; } /// <summary> /// The date the customer was last modified, as GMT. /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public DateTime? date_modified_gmt { get; set; } /// <summary> /// The email address for the customer. /// mandatory /// </summary> [DataMember(EmitDefaultValue = false)] public string email { get; set; } /// <summary> /// Customer first name. /// </summary> [DataMember(EmitDefaultValue = false)] public string first_name { get; set; } /// <summary> /// Customer last name. /// </summary> [DataMember(EmitDefaultValue = false)] public string last_name { get; set; } /// <summary> /// Customer role. /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public string role { get; set; } /// <summary> /// Customer login name. /// </summary> [DataMember(EmitDefaultValue = false)] public string username { get; set; } /// <summary> /// Customer password. /// write-only /// </summary> [DataMember(EmitDefaultValue = false)] public string password { get; set; } /// <summary> /// List of billing address data. See Customer - Billing properties /// </summary> [DataMember(EmitDefaultValue = false)] public CustomerBilling billing { get; set; } /// <summary> /// List of shipping address data. See Customer - Shipping properties /// </summary> [DataMember(EmitDefaultValue = false)] public CustomerShipping shipping { get; set; } /// <summary> /// Is the customer a paying customer? /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public bool? is_paying_customer { get; set; } /// <summary> /// Quantity of orders made by the customer. /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public int? orders_count { get; set; } [DataMember(EmitDefaultValue = false, Name = "total_spent")] protected object total_spentValue { get; set; } /// <summary> /// Total amount spent. /// read-only /// </summary> public decimal? total_spent { get; set; } /// <summary> /// Avatar URL. /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public string avatar_url { get; set; } /// <summary> /// Meta data. See Customer - Meta data properties /// </summary> [DataMember(EmitDefaultValue = false)] public List<CustomerMeta> meta_data { get; set; } } [DataContract] public class CustomerBilling { /// <summary> /// First name. /// </summary> [DataMember(EmitDefaultValue = false)] public string first_name { get; set; } /// <summary> /// Last name. /// </summary> [DataMember(EmitDefaultValue = false)] public string last_name { get; set; } /// <summary> /// Company name. /// </summary> [DataMember(EmitDefaultValue = false)] public string company { get; set; } /// <summary> /// Address line 1 /// </summary> [DataMember(EmitDefaultValue = false)] public string address_1 { get; set; } /// <summary> /// Address line 2 /// </summary> [DataMember(EmitDefaultValue = false)] public string address_2 { get; set; } /// <summary> /// City name. /// </summary> [DataMember(EmitDefaultValue = false)] public string city { get; set; } /// <summary> /// ISO code or name of the state, province or district. /// </summary> [DataMember(EmitDefaultValue = false)] public string state { get; set; } /// <summary> /// Postal code. /// </summary> [DataMember(EmitDefaultValue = false)] public string postcode { get; set; } /// <summary> /// ISO code of the country. /// </summary> [DataMember(EmitDefaultValue = false)] public string country { get; set; } /// <summary> /// Email address. /// </summary> [DataMember(EmitDefaultValue = false)] public string email { get; set; } /// <summary> /// Phone number. /// </summary> [DataMember(EmitDefaultValue = false)] public string phone { get; set; } } [DataContract] public class CustomerShipping { /// <summary> /// First name. /// </summary> [DataMember(EmitDefaultValue = false)] public string first_name { get; set; } /// <summary> /// Last name. /// </summary> [DataMember(EmitDefaultValue = false)] public string last_name { get; set; } /// <summary> /// Company name. /// </summary> [DataMember(EmitDefaultValue = false)] public string company { get; set; } /// <summary> /// Address line 1 /// </summary> [DataMember(EmitDefaultValue = false)] public string address_1 { get; set; } /// <summary> /// Address line 2 /// </summary> [DataMember(EmitDefaultValue = false)] public string address_2 { get; set; } /// <summary> /// City name. /// </summary> [DataMember(EmitDefaultValue = false)] public string city { get; set; } /// <summary> /// ISO code or name of the state, province or district. /// </summary> [DataMember(EmitDefaultValue = false)] public string state { get; set; } /// <summary> /// Postal code. /// </summary> [DataMember(EmitDefaultValue = false)] public string postcode { get; set; } /// <summary> /// ISO code of the country. /// </summary> [DataMember(EmitDefaultValue = false)] public string country { get; set; } } [DataContract] public class CustomerMeta : WCObject.MetaData { } [DataContract] public class CustomerDownloads { /// <summary> /// Download ID (MD5). /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public string download_id { get; set; } /// <summary> /// Download file URL. /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public string download_url { get; set; } /// <summary> /// Downloadable product ID. /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public uint? product_id { get; set; } /// <summary> /// Product name. /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public string product_name { get; set; } /// <summary> /// Downloadable file name. /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public string download_name { get; set; } /// <summary> /// Order ID. /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public uint? order_id { get; set; } /// <summary> /// Order key. /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public string order_key { get; set; } /// <summary> /// Number of downloads remaining. /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public string downloads_remaining { get; set; } /// <summary> /// The date when download access expires, in the site’s timezone. /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public string access_expires { get; set; } /// <summary> /// The date when download access expires, as GMT. /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public string access_expires_gmt { get; set; } /// <summary> /// File details. /// read-only /// </summary> [DataMember(EmitDefaultValue = false)] public CustomerDownloadFile file { get; set; } } [DataContract] public class CustomerDownloadFile { /// <summary> /// File name /// </summary> [DataMember(EmitDefaultValue = false)] public string name { get; set; } /// <summary> /// File URL /// </summary> [DataMember(EmitDefaultValue = false)] public string file { get; set; } } }
28.037736
77
0.526053
[ "MIT" ]
HenkoR/WooCommerce.NET
WooCommerce/v2/Customer.cs
10,410
C#
using EngineeringUnits.Units; using System.Collections.Generic; using System.Text; namespace EngineeringUnits { public partial class BitRate { /// <summary> /// Get BitRate in BitsPerSecond. /// </summary> public double BitsPerSecond => As(BitRateUnit.BitPerSecond); /// <summary> /// Get BitRate in SI Unit (BitsPerSecond). /// </summary> public double SI => As(BitRateUnit.SI); /// <summary> /// Get BitRate in BytesPerSecond. /// </summary> public double BytesPerSecond => As(BitRateUnit.BytePerSecond); /// <summary> /// Get BitRate in ExabitsPerSecond. /// </summary> public double ExabitsPerSecond => As(BitRateUnit.ExabitPerSecond); /// <summary> /// Get BitRate in ExabytesPerSecond. /// </summary> public double ExabytesPerSecond => As(BitRateUnit.ExabytePerSecond); /// <summary> /// Get BitRate in ExbibitsPerSecond. /// </summary> public double ExbibitsPerSecond => As(BitRateUnit.ExbibitPerSecond); /// <summary> /// Get BitRate in ExbibytesPerSecond. /// </summary> public double ExbibytesPerSecond => As(BitRateUnit.ExbibytePerSecond); /// <summary> /// Get BitRate in GibibitsPerSecond. /// </summary> public double GibibitsPerSecond => As(BitRateUnit.GibibitPerSecond); /// <summary> /// Get BitRate in GibibytesPerSecond. /// </summary> public double GibibytesPerSecond => As(BitRateUnit.GibibytePerSecond); /// <summary> /// Get BitRate in GigabitsPerSecond. /// </summary> public double GigabitsPerSecond => As(BitRateUnit.GigabitPerSecond); /// <summary> /// Get BitRate in GigabytesPerSecond. /// </summary> public double GigabytesPerSecond => As(BitRateUnit.GigabytePerSecond); /// <summary> /// Get BitRate in KibibitsPerSecond. /// </summary> public double KibibitsPerSecond => As(BitRateUnit.KibibitPerSecond); /// <summary> /// Get BitRate in KibibytesPerSecond. /// </summary> public double KibibytesPerSecond => As(BitRateUnit.KibibytePerSecond); /// <summary> /// Get BitRate in KilobitsPerSecond. /// </summary> public double KilobitsPerSecond => As(BitRateUnit.KilobitPerSecond); /// <summary> /// Get BitRate in KilobytesPerSecond. /// </summary> public double KilobytesPerSecond => As(BitRateUnit.KilobytePerSecond); /// <summary> /// Get BitRate in MebibitsPerSecond. /// </summary> public double MebibitsPerSecond => As(BitRateUnit.MebibitPerSecond); /// <summary> /// Get BitRate in MebibytesPerSecond. /// </summary> public double MebibytesPerSecond => As(BitRateUnit.MebibytePerSecond); /// <summary> /// Get BitRate in MegabitsPerSecond. /// </summary> public double MegabitsPerSecond => As(BitRateUnit.MegabitPerSecond); /// <summary> /// Get BitRate in MegabytesPerSecond. /// </summary> public double MegabytesPerSecond => As(BitRateUnit.MegabytePerSecond); /// <summary> /// Get BitRate in PebibitsPerSecond. /// </summary> public double PebibitsPerSecond => As(BitRateUnit.PebibitPerSecond); /// <summary> /// Get BitRate in PebibytesPerSecond. /// </summary> public double PebibytesPerSecond => As(BitRateUnit.PebibytePerSecond); /// <summary> /// Get BitRate in PetabitsPerSecond. /// </summary> public double PetabitsPerSecond => As(BitRateUnit.PetabitPerSecond); /// <summary> /// Get BitRate in PetabytesPerSecond. /// </summary> public double PetabytesPerSecond => As(BitRateUnit.PetabytePerSecond); /// <summary> /// Get BitRate in TebibitsPerSecond. /// </summary> public double TebibitsPerSecond => As(BitRateUnit.TebibitPerSecond); /// <summary> /// Get BitRate in TebibytesPerSecond. /// </summary> public double TebibytesPerSecond => As(BitRateUnit.TebibytePerSecond); /// <summary> /// Get BitRate in TerabitsPerSecond. /// </summary> public double TerabitsPerSecond => As(BitRateUnit.TerabitPerSecond); /// <summary> /// Get BitRate in TerabytesPerSecond. /// </summary> public double TerabytesPerSecond => As(BitRateUnit.TerabytePerSecond); } }
33
78
0.587173
[ "MIT" ]
MadsKirkFoged/EngineeringUnits
EngineeringUnits/CombinedUnits/BitRate/BitRateGet.cs
4,820
C#
using Google.GData.Client; using NUnit.Framework; using Google.GData.Client.UnitTests; namespace Google.GData.Client.UnitTests.Core { /// <summary> ///This is a test class for AtomLogoTest and is intended ///to contain all AtomLogoTest Unit Tests ///</summary> [TestFixture][Category("CoreClient")] public class AtomLogoTest { private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region Additional test attributes // //You can use the following additional attributes as you write your tests: // //Use ClassInitialize to run code before running the first test in the class //[ClassInitialize()] //public static void MyClassInitialize(TestContext testContext) //{ //} // //Use ClassCleanup to run code after all tests in a class have run //[ClassCleanup()] //public static void MyClassCleanup() //{ //} // //Use TestInitialize to run code before running each test //[TestInitialize()] //public void MyTestInitialize() //{ //} // //Use TestCleanup to run code after each test has run //[TestCleanup()] //public void MyTestCleanup() //{ //} // #endregion /// <summary> ///A test for XmlName ///</summary> [Test] public void XmlNameTest() { AtomLogo target = new AtomLogo(); Assert.AreEqual(target.XmlName, AtomParserNameTable.XmlLogoElement); } } }
25.707317
85
0.523719
[ "Apache-2.0" ]
michael-jia-sage/libgoogle
src/unittests/core/AtomLogoTest.cs
2,110
C#
// // Unit tests for HKCdaDocumentSample // // Authors: // Sebastien Pouliot <sebastien@xamarin.com> // // Copyright 2016 Xamarin Inc. All rights reserved. // #if HAS_HEALTHKIT using System; using Foundation; using HealthKit; using UIKit; using NUnit.Framework; namespace MonoTouchFixtures.HealthKit { [TestFixture] [Preserve (AllMembers = true)] public class CdaDocumentSampleTest { [Test] public void Error () { TestRuntime.AssertXcodeVersion (8, 0); NSError error; using (var d = new NSData ()) { TestDelegate action = () => { using (var s = HKCdaDocumentSample.Create (d, NSDate.DistantPast, NSDate.DistantFuture, (NSDictionary)null, out error)) { Assert.NotNull (error, "error"); var details = new HKDetailedCdaErrors (error.UserInfo); Assert.That (details.ValidationError.Length, Is.EqualTo ((nint) 0), "Length"); } }; #if __MACCATALYST__ var throwsException = false; #else var throwsException = TestRuntime.CheckXcodeVersion (11, 0); #endif if (throwsException) { var ex = Assert.Throws<MonoTouchException> (action, "Exception"); Assert.That (ex.Message, Does.Match ("startDate.*and endDate.*exceed the maximum allowed duration for this sample type"), "Exception Message"); } else { action (); } } } } } #endif // HAS_HEALTHKIT
23.910714
148
0.68708
[ "BSD-3-Clause" ]
ScriptBox99/xamarin-macios
tests/monotouch-test/HealthKit/CdaDocumentSampleTest.cs
1,339
C#
/* The MIT License (MIT) Copyright (c) 2007 - 2021 Microting A/S 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. */ namespace Microting.InsightDashboardBase.Infrastructure.Data { using eFormApi.BasePn.Abstractions; using eFormApi.BasePn.Infrastructure.Database.Entities; using Entities; using Microsoft.EntityFrameworkCore; public class InsightDashboardPnDbContext : DbContext, IPluginDbContext { public InsightDashboardPnDbContext() { } public InsightDashboardPnDbContext(DbContextOptions<InsightDashboardPnDbContext> options) : base(options) { } public DbSet<Dashboard> Dashboards { get; set; } public DbSet<DashboardVersion> DashboardVersions { get; set; } public DbSet<DashboardItem> DashboardItems { get; set; } public DbSet<DashboardItemVersion> DashboardItemVersions { get; set; } public DbSet<DashboardItemCompare> DashboardItemCompares { get; set; } public DbSet<DashboardItemCompareVersion> DashboardItemCompareVersions { get; set; } public DbSet<DashboardItemIgnoredAnswer> DashboardItemIgnoredAnswers { get; set; } public DbSet<DashboardItemIgnoredAnswerVersion> DashboardItemIgnoredAnswerVersions { get; set; } // default tables public DbSet<PluginConfigurationValue> PluginConfigurationValues { get; set; } public DbSet<PluginConfigurationValueVersion> PluginConfigurationValueVersions { get; set; } public DbSet<PluginPermission> PluginPermissions { get; set; } public DbSet<PluginGroupPermission> PluginGroupPermissions { get; set; } public DbSet<PluginGroupPermissionVersion> PluginGroupPermissionVersions { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Dashboard>() .HasIndex(x => x.SurveyId); modelBuilder.Entity<Dashboard>() .HasIndex(x => x.LocationId); modelBuilder.Entity<Dashboard>() .HasIndex(x => x.TagId); modelBuilder.Entity<Dashboard>() .HasIndex(x => x.Name); modelBuilder.Entity<DashboardItem>() .HasIndex(x => x.FirstQuestionId); modelBuilder.Entity<DashboardItem>() .HasIndex(x => x.FilterQuestionId); modelBuilder.Entity<DashboardItem>() .HasIndex(x => x.FilterAnswerId); modelBuilder.Entity<DashboardItemCompare>() .HasIndex(x => x.LocationId); modelBuilder.Entity<DashboardItemCompare>() .HasIndex(x => x.TagId); modelBuilder.Entity<DashboardItemIgnoredAnswer>() .HasIndex(x => x.AnswerId); } } }
41.802198
113
0.700578
[ "MIT" ]
Gid733/eform-insight-dashboard-base
Microting.InsightDashboardBase/Infrastructure/Data/InsightDashboardPnDbContext.cs
3,804
C#
using Blockcore.Consensus.ScriptInfo; using Blockcore.Networks; using NBitcoin; namespace Blockcore.Indexer.Crypto { public class ScriptToAddressParser { public static string GetSignerAddress(Network network, Script script) { BitcoinAddress address = script.GetSignerAddress(network); if (address == null) { return null; } return script.GetSignerAddress(network).ToString(); } public static string[] GetAddress(Network network, Script script) { ScriptTemplate template = StandardScripts.GetTemplateFromScriptPubKey(script); if (template == null) return null; if (template.Type == TxOutType.TX_NONSTANDARD) return null; if (template.Type == TxOutType.TX_NULL_DATA) return null; if (template.Type == TxOutType.TX_PUBKEY) { PubKey[] pubkeys = script.GetDestinationPublicKeys(network); return new[] { pubkeys[0].GetAddress(network).ToString() }; } if (template.Type == TxOutType.TX_PUBKEYHASH || template.Type == TxOutType.TX_SCRIPTHASH || template.Type == TxOutType.TX_SEGWIT) { BitcoinAddress bitcoinAddress = script.GetDestinationAddress(network); if (bitcoinAddress != null) { return new[] { bitcoinAddress.ToString() }; } } if (template.Type == TxOutType.TX_MULTISIG) { // TODO; return null; } if (template.Type == TxOutType.TX_COLDSTAKE) { if (ColdStakingScriptTemplate.Instance.ExtractScriptPubKeyParameters(script, out KeyId hotPubKeyHash, out KeyId coldPubKeyHash)) { // We want to index based on both the cold and hot key return new[] { hotPubKeyHash.GetAddress(network).ToString(), coldPubKeyHash.GetAddress(network).ToString(), }; } return null; } return null; } } }
28.285714
140
0.562902
[ "MIT" ]
block-core/blockcore-indexer
src/Blockcore.Indexer/Crypto/ScriptToAddressParser.cs
2,178
C#
using FakeNews.Transfer.Jwt; using FakeNews.Transfer.Users; using System.Threading.Tasks; namespace FakeNews.Bll.Users { public interface IUserService { Task<TokenDto> LogUserInAsync(LoginDto loginDto); Task RegisterUserAsync(RegisterUserDto registerUserDto); } }
22.615385
64
0.748299
[ "MIT" ]
TomSoldier/fakenews
src/Backend/FakeNews/FakeNews.Bll/Users/IUserService.cs
296
C#
using System; namespace _03.ExactProductOfRealNumbers { public class ExactProductOfRealNumbers { public static void Main() { int n = int.Parse(Console.ReadLine()); decimal product = 1M; for (int i = 0; i < n; i++) { double number = double.Parse(Console.ReadLine()); product = product * (decimal)number; } Console.WriteLine(product); } } }
22.857143
65
0.5125
[ "MIT" ]
vasilivanov93/SOFTUNI
C#/02. Programming Fundamentals C# - Extended/Programming Fundamentals - Project/01. Data types - Lab/03. ExactProductOfRealNumbers/ExactProductOfRealNumbers.cs
482
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore; using Microsoft.Extensions.Configuration; using Microsoft.AspNetCore.Http.Features; using System; using System.Runtime.Serialization; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using Newtonsoft.Json; namespace Features.Session { [Serializable] public class Person { public string FirstName { get; set; } public string LastName {get; set;} } public class Startup { IConfiguration Configuration {get;set;} public Startup(IConfiguration configuration) { Configuration = configuration; } public void ConfigureServices(IServiceCollection services) { //This is the only service available at ConfigureServices services.AddStackExchangeRedisCache(options => { options.Configuration = Configuration["redisConnectionString"]; }); services.AddSession(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger) { app.UseSession(); app.Use(async (context, next)=> { var person = new Person { FirstName = "Anne", LastName = "M" }; var session = context.Features.Get<ISessionFeature>(); try { session.Session.SetString("Message", "Buon giorno cuore"); session.Session.SetInt32("Year", DateTime.Now.Year); session.Session.SetString("Amore", JsonConvert.SerializeObject(person)); } catch(Exception ex) { await context.Response.WriteAsync($"{ex.Message}"); } await next.Invoke(); }); app.Run(async context => { var session = context.Features.Get<ISessionFeature>(); try { string msg = session.Session.GetString("Message"); int? year = session.Session.GetInt32("Year"); var amore = JsonConvert.DeserializeObject<Person>(session.Session.GetString("Amore")); await context.Response.WriteAsync($"{amore.FirstName}, {msg} {year}"); } catch(Exception ex) { await context.Response.WriteAsync($"{ex.Message}"); } }); } } public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseEnvironment("Development"); } }
31.752475
106
0.549111
[ "MIT" ]
BionStt/practical-aspnetcore
projects/2-2/new-redis-caching-package/src/Program.cs
3,207
C#
using System; using System.Collections.Generic; namespace SonarAnalyzer.Experiments.CSharp { public class DontSortUncomparebleLists { public DontSortUncomparebleLists() { var objects = new List<object>(); objects.Sort(); // noncompliant. object does not implement IComparable<T> objects.Sort(Comparer<object>.Default); // compliant. The comparer should no what to do. var ints = new List<int>(); ints.Sort(); // compliant. int implements IComparable<int> } public static void Sort<T>(List<T> list) { list.Sort(); // noncompliant. object might not implement IComarable<T> } public static void Sort2<T>(List<T> list) where T : IComparable<T> { list.Sort(); // compliant. T implements IComparable<T> } } }
29.6
100
0.594595
[ "MIT" ]
Corniel/SonarAnalyzer.Experiments
src/SonarAnalyzer.Experiments.CSharp/DontSortUncomparebleLists.cs
890
C#
using UnityEngine; using UnityEditor; using System.Reflection; using System.Linq; namespace KrColorPalette { public abstract class ColorInitializeInspectorBase : Editor { protected PropertyInfo[] properties = null; // Palette色のクラスのプロパティ配列 protected string[] propertyNames = null; // プルダウンに表示するプロパティ名配列 protected SerializedProperty color = null; private SerializedProperty selectPropertyName = null; private int selectIndex = -1; // 選択しているプロパティ配列のindex(-1の場合は選択対象のプロパティが存在しない) protected virtual void OnEnable() { selectPropertyName = serializedObject.FindProperty("selectPropertyName"); color = serializedObject.FindProperty("color"); System.Type type = typeof(Palette); properties = type.GetProperties(); propertyNames = properties.Select(property => property.Name).ToArray(); for(int i = 0; i < properties.Length; i ++) { if(selectPropertyName.stringValue == properties[i].Name) { selectIndex = i; } } if(selectIndex <= -1 && !string.IsNullOrEmpty(selectPropertyName.stringValue)) { // すでに設定していたプロパティがなくなった場合はエラーログを表示 Debug.LogError($"[{target.GetType().Name}]指定されている{selectPropertyName.stringValue}は定義されていません : {target.name}"); } } public override void OnInspectorGUI() { selectIndex = EditorGUILayout.Popup("Color", selectIndex, propertyNames); // -1の場合は色を反映できないのでリターンする if(selectIndex <= -1) { return; } if(propertyNames[selectIndex] != selectPropertyName.stringValue) { selectPropertyName.stringValue = propertyNames[selectIndex]; color.colorValue = (Color)properties[selectIndex].GetValue(null); } } } }
35.20339
126
0.573423
[ "MIT" ]
kirierurein/KrColorPalette
Assets/Kirierurein/ColorPalette/Editor/Scripts/ColorInitializeInspectorBase.cs
2,345
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace RainbowCommand { class Explosion { private PointF _position; private float _width; private float _height; private const float MaxExplosion = 100f; private const float ExplosionIncrease = 10f; public Explosion(PointF position) { _position = position; _width = 0f; _height = 0f; } public PointF Position { get { return _position; } } public float Radius { get { return _width; } } public bool Update() { // Grow explosion by ExplosionIncrease _width = _width + ExplosionIncrease; _height = _height + ExplosionIncrease; if (_width < MaxExplosion) { return false; // Continue explosion } return true; // Done clear explosion } public void Draw(Graphics g) { g.FillEllipse(Brushes.Red, _position.X - _width / 2f, _position.Y - _height / 2f, _width, _height); } } }
20.936508
111
0.504928
[ "MIT" ]
rfoligno/game-rainbow-command
RainbowCommand/Explosion.cs
1,321
C#
using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; using SuperSocket.SocketBase; namespace SuperSocket.SocketEngine { /// <summary> /// This class is designed for use as the object to be assigned to the SocketAsyncEventArgs.UserToken property. /// </summary> class AsyncUserToken { Socket m_socket; public AsyncUserToken() : this(null) { } public AsyncUserToken(Socket socket) { m_socket = socket; } public Socket Socket { get { return m_socket; } set { m_socket = value; } } public IAsyncSocketSession SocketSession { get; set; } } }
22.666667
117
0.588235
[ "BSD-3-Clause" ]
3rdandUrban-dev/Nuxleus
src/external/SuperSocket/v1.4/SocketEngine/AsyncSocket/AsyncUserToken.cs
748
C#
using System.Diagnostics; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Shapes; using JetBrains.Annotations; namespace essentialMix.Core.WPF.Controls; public enum TransitionQuality { None, Low = 72, Medium = 96, High = 120 } public enum TransitionDirection { Default, Left, Right } public interface ITransitionSlide { TransitionDirection Direction { get; set; } bool TransitionEnabled { get; set; } int Order { get; set; } bool WideScreen { get; } bool FullScreen { get; } } public class SlideTransition : Freezable { private static readonly DependencyPropertyKey __enabledPropertyKey = DependencyProperty.RegisterReadOnly(nameof(Enabled), typeof(bool), typeof(SlideTransition), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.None)); public static readonly DependencyProperty DurationProperty = DependencyProperty.Register(nameof(Duration), typeof(Duration), typeof(SlideTransition), new FrameworkPropertyMetadata(new Duration(TimeSpan.FromMilliseconds(300)), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnEnabledDependenciesChanged), OnValidateDuration); public static readonly DependencyProperty QualityProperty = DependencyProperty.Register(nameof(Quality), typeof(TransitionQuality), typeof(SlideTransition), new FrameworkPropertyMetadata(TransitionQuality.Medium, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnEnabledDependenciesChanged), OnValidateQuality); public static readonly DependencyProperty EnabledProperty = __enabledPropertyKey.DependencyProperty; /// <inheritdoc /> public SlideTransition() { } public Duration Duration { get => (Duration)GetValue(DurationProperty); set => SetValue(DurationProperty, value); } public TransitionQuality Quality { get => (TransitionQuality)GetValue(QualityProperty); set => SetValue(QualityProperty, value); } public bool Enabled => (bool)GetValue(EnabledProperty); /// <inheritdoc /> protected override Freezable CreateInstanceCore() { return new SlideTransition(); } private static bool OnValidateDuration(object value) { return value is Duration d && (d.HasTimeSpan || d == Duration.Automatic); } private static bool OnValidateQuality(object value) { return value is TransitionQuality tq && Enum.IsDefined(typeof(TransitionQuality), tq); } private static void OnEnabledDependenciesChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { SlideTransition transition = (SlideTransition)sender; bool enabled = transition.Quality > TransitionQuality.None && (transition.Duration == Duration.Automatic || transition.Duration.HasTimeSpan && transition.Duration.TimeSpan > TimeSpan.Zero); transition.SetValue(__enabledPropertyKey, enabled); } } /// <inheritdoc /> [TemplatePart(Name = "PART_PaintArea", Type = typeof(Shape))] [TemplatePart(Name = "PART_Content", Type = typeof(ContentPresenter))] public class SlidingContent : ContentControl { public static readonly DependencyProperty TransitionProperty = DependencyProperty.Register(nameof(Transition), typeof(SlideTransition), typeof(SlidingContent), new FrameworkPropertyMetadata(new SlideTransition(), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); private Storyboard _slidingInAnimation; private Storyboard _slidingOutAnimation; // represents the old content private Shape _paintArea; private ContentPresenter _content; static SlidingContent() { DefaultStyleKeyProperty.OverrideMetadata(typeof(SlidingContent), new FrameworkPropertyMetadata(typeof(SlidingContent))); } /// <inheritdoc /> public SlidingContent() { } [NotNull] public SlideTransition Transition { get => (SlideTransition)GetValue(TransitionProperty); set => SetValue(TransitionProperty, value); } /// <inheritdoc /> public override void OnApplyTemplate() { _paintArea = Template.FindName("PART_PaintArea", this) as Shape; _content = Template.FindName("PART_Content", this) as ContentPresenter; base.OnApplyTemplate(); } /// <inheritdoc /> protected override void OnContentChanged(object oldContent, object newContent) { if (_paintArea == null || _content == null || !Transition.Enabled) { base.OnContentChanged(oldContent, newContent); return; } ITransitionSlide oldSlide = oldContent as ITransitionSlide; ITransitionSlide newSlide = newContent as ITransitionSlide; if (oldSlide == null && newSlide == null || oldSlide is { WideScreen: false } || newSlide is { WideScreen: false } || oldSlide is { TransitionEnabled: false } && newSlide is { TransitionEnabled: false }) { base.OnContentChanged(oldContent, newContent); return; } TransitionDirection direction; // if we are here, then at least one of the contents has transition enabled if (newSlide is { TransitionEnabled: true }) { if (newSlide.Direction == TransitionDirection.Default) { if (oldSlide != null) { // check the new slide order relative to the old slide int diff = oldSlide.Order - newSlide.Order; direction = diff <= 0 ? TransitionDirection.Left : TransitionDirection.Right; } else { direction = TransitionDirection.Left; } } else { direction = newSlide.Direction; } } else if (oldSlide is { TransitionEnabled: true }) { // old slide transition direction will be reversed if (oldSlide.Direction == TransitionDirection.Default) { if (newSlide != null) { // check the new slide order relative to the old slide int diff = oldSlide.Order - newSlide.Order; direction = diff > 0 ? TransitionDirection.Right : TransitionDirection.Left; } else { direction = TransitionDirection.Right; } } else { direction = oldSlide.Direction == TransitionDirection.Left ? TransitionDirection.Right : TransitionDirection.Left; } } else { base.OnContentChanged(oldContent, newContent); return; } _paintArea.Fill = CreateBrushFromVisual(_content); BeginAnimateContentReplacement(direction); base.OnContentChanged(oldContent, newContent); } /// <summary> /// Creates a snapshot image from current content /// </summary> [NotNull] private Brush CreateBrushFromVisual([NotNull] Visual element) { int quality = (int)Transition.Quality; Debug.Assert(quality > 0); RenderTargetBitmap target = new RenderTargetBitmap((int)ActualWidth, (int)ActualHeight, quality, quality, PixelFormats.Pbgra32); target.Render(element); Brush brush = new ImageBrush(target); brush.Freeze(); return brush; } private void BeginAnimateContentReplacement(TransitionDirection direction) { if (_paintArea == null || _content == null) return; Duration duration = Transition.Duration; double offset = ActualWidth + Math.Max(Padding.Left, Padding.Right); if (direction == TransitionDirection.Right) offset *= -1; _paintArea.RenderTransform = new TranslateTransform(-offset, 0); _content.RenderTransform = new TranslateTransform(offset, 0); _paintArea.Visibility = Visibility.Visible; _slidingOutAnimation ??= CreateOutAnimation(() => _paintArea.Visibility = Visibility.Hidden); _slidingInAnimation ??= CreateInAnimation(); foreach (DoubleAnimation animation in _slidingOutAnimation.Children.Cast<DoubleAnimation>()) { animation.Duration = duration; Storyboard.SetTarget(animation, _paintArea); } foreach (DoubleAnimation animation in _slidingInAnimation.Children.Cast<DoubleAnimation>()) { animation.Duration = duration; Storyboard.SetTarget(animation, _content); } _slidingOutAnimation.Begin(); _slidingInAnimation.Begin(); static Storyboard CreateOutAnimation(Action onCompleted) { Storyboard storyboard = new Storyboard { Children = { new DoubleAnimation { From = 0d, EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut } }, new DoubleAnimation { From = 1d, To = 0d, EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut } } } }; Storyboard.SetTargetProperty(storyboard.Children[0], new PropertyPath("RenderTransform.(TranslateTransform.X)")); Storyboard.SetTargetProperty(storyboard.Children[1], new PropertyPath(OpacityProperty)); storyboard.Completed += (_, _) => onCompleted(); return storyboard; } static Storyboard CreateInAnimation() { Storyboard storyboard = new Storyboard { Children = { new DoubleAnimation { To = 0d, EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut } }, new DoubleAnimation { From = 0d, To = 1d, EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut } } } }; Storyboard.SetTargetProperty(storyboard.Children[0], new PropertyPath("RenderTransform.(TranslateTransform.X)")); Storyboard.SetTargetProperty(storyboard.Children[1], new PropertyPath(OpacityProperty)); return storyboard; } } }
29.699029
333
0.733246
[ "MIT" ]
asm2025/essentailMix.Core
essentialMix.Core.WPF/Controls/SlidingContent.cs
9,179
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using StarkPlatform.CodeAnalysis.Common; namespace StarkPlatform.CodeAnalysis.Editor { /// <summary> /// Returns Roslyn todo list from the workspace. /// </summary> internal interface ITodoListProvider { /// <summary> /// An event that is raised when the todo list has changed. /// /// When an event handler is newly added, this event will fire for the currently available todo items and then /// afterward for any changes since. /// </summary> event EventHandler<TodoItemsUpdatedArgs> TodoListUpdated; ImmutableArray<TodoItem> GetTodoItems(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken); /// <summary> /// Get current UpdatedEventArgs stored in ITodoListProvider /// </summary> IEnumerable<UpdatedEventArgs> GetTodoItemsUpdatedEventArgs(Workspace workspace, CancellationToken cancellationToken); } }
38.5
161
0.712662
[ "Apache-2.0" ]
stark-lang/stark-roslyn
src/EditorFeatures/Core/Implementation/TodoComment/ITodoListProvider.cs
1,234
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("ImplementLinkedList.cs")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ImplementLinkedList.cs")] [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("ac18fea4-a59f-40ee-ab8b-2f4021cba35f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.162162
84
0.75
[ "MIT" ]
simeonovanton/TelerikALPHA_nov2017
05.DSA/LinearDataStructures/LinearStructures/ImplementLinkedList.cs/Properties/AssemblyInfo.cs
1,415
C#
//----------------------------------------------------- // <copyright file="PageModelOther.cs" company="Cognizant"> // Copyright 2022 Cognizant, All rights Reserved // </copyright> // <summary>Another test Playwright page object model</summary> //----------------------------------------------------- using CognizantSoftvision.Maqs.BasePlaywrightTest; using Microsoft.Playwright; using System.Diagnostics.CodeAnalysis; namespace PlaywrightTests { /// <summary> /// Playwright page model class for testing /// </summary> [ExcludeFromCodeCoverage] public class PageModelIFrame : BasePlaywrightPageModel { /// <summary> /// Initializes a new instance of the <see cref="PageModel"/> class /// </summary> /// <param name="testObject">The base Playwright test object</param> /// <param name="otherDriver">Page driver to use instead of the default</param> public PageModelIFrame(IPlaywrightTestObject testObject) : base(testObject) { } /// <summary> /// Get page url /// </summary> public static string Url { get { return PlaywrightConfig.WebBase() + "iFrame.html"; } } /// <summary> /// Test frame /// </summary> private IFrameLocator Frame { get { return this.PageDriver.AsyncPage.FrameLocator("#frame"); } } /// <summary> /// Get loaded label /// </summary> public PlaywrightSyncElement ShowDialog { get { return new PlaywrightSyncElement(Frame, "#showDialog1"); } } /// <summary> /// Get loaded label /// </summary> public PlaywrightSyncElement CloseDialog { get { return new PlaywrightSyncElement(Frame, "#CloseButtonShowDialog"); } } /// <summary> /// Open the page /// </summary> public void OpenPage() { this.PageDriver.Goto(Url); } /// <summary> /// Check if the page has been loaded /// </summary> /// <returns>True if the page was loaded</returns> public override bool IsPageLoaded() { return ShowDialog.IsEventualyVisible(); } } }
28.62963
87
0.542475
[ "MIT" ]
CognizantOpenSource/maqs-dotnet
Framework/PlaywrightTests/PageModelIFrame.cs
2,321
C#
//------------------------------------------------------------------------------ // <auto-generated> // Этот код был создан программным средством. // // Изменения в этом файле могут привести к неправильному поведению и будут утрачены, если // код создается повторно. // </auto-generated> //------------------------------------------------------------------------------ namespace WebApplication5 { public partial class SiteMaster { /// <summary> /// Элемент управления HeadContent. /// </summary> /// <remarks> /// Автоматически созданное поле. /// Для изменения переместите объявление поля из файла конструктора в файл кода программной части. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder HeadContent; /// <summary> /// Элемент управления FeaturedContent. /// </summary> /// <remarks> /// Автоматически созданное поле. /// Для изменения переместите объявление поля из файла конструктора в файл кода программной части. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder FeaturedContent; /// <summary> /// Элемент управления MainContent. /// </summary> /// <remarks> /// Автоматически созданное поле. /// Для изменения переместите объявление поля из файла конструктора в файл кода программной части. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder MainContent; } }
35.022222
106
0.572335
[ "Apache-2.0" ]
MiracleSirius1/Projects
WebApplication5/WebApplication5/Site.Master.designer.cs
2,079
C#
using Neo.Persistence; namespace Neo.Network.P2P.Payloads { public interface IInventory : IVerifiable { UInt256 Hash { get; } InventoryType InventoryType { get; } bool Verify(DataCache snapshot); } }
17.071429
45
0.648536
[ "MIT" ]
belane/neo
src/neo/Network/P2P/Payloads/IInventory.cs
239
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. /*============================================================ ** ** Purpose: Unsafe code that uses pointers should use ** SafePointer to fix subtle lifetime problems with the ** underlying resource. ** ===========================================================*/ // Design points: // *) Avoid handle-recycling problems (including ones triggered via // resurrection attacks) for all accesses via pointers. This requires tying // together the lifetime of the unmanaged resource with the code that reads // from that resource, in a package that uses synchronization to enforce // the correct semantics during finalization. We're using SafeHandle's // ref count as a gate on whether the pointer can be dereferenced because that // controls the lifetime of the resource. // // *) Keep the penalties for using this class small, both in terms of space // and time. Having multiple threads reading from a memory mapped file // will already require 2 additional interlocked operations. If we add in // a "current position" concept, that requires additional space in memory and // synchronization. Since the position in memory is often (but not always) // something that can be stored on the stack, we can save some memory by // excluding it from this object. However, avoiding the need for // synchronization is a more significant win. This design allows multiple // threads to read and write memory simultaneously without locks (as long as // you don't write to a region of memory that overlaps with what another // thread is accessing). // // *) Space-wise, we use the following memory, including SafeHandle's fields: // Object Header MT* handle int bool bool <2 pad bytes> length // On 32 bit platforms: 24 bytes. On 64 bit platforms: 40 bytes. // (We can safe 4 bytes on x86 only by shrinking SafeHandle) // // *) Wrapping a SafeHandle would have been a nice solution, but without an // ordering between critical finalizable objects, it would have required // changes to each SafeHandle subclass to opt in to being usable from a // SafeBuffer (or some clever exposure of SafeHandle's state fields and a // way of forcing ReleaseHandle to run even after the SafeHandle has been // finalized with a ref count > 1). We can use less memory and create fewer // objects by simply inserting a SafeBuffer into the class hierarchy. // // *) In an ideal world, we could get marshaling support for SafeBuffer that // would allow us to annotate a P/Invoke declaration, saying this parameter // specifies the length of the buffer, and the units of that length are X. // P/Invoke would then pass that size parameter to SafeBuffer. // [DllImport(...)] // static extern SafeMemoryHandle AllocCharBuffer(int numChars); // If we could put an attribute on the SafeMemoryHandle saying numChars is // the element length, and it must be multiplied by 2 to get to the byte // length, we can simplify the usage model for SafeBuffer. // // *) This class could benefit from a constraint saying T is a value type // containing no GC references. // Implementation notes: // *) The Initialize method must be called before you use any instance of // a SafeBuffer. To avoid races when storing SafeBuffers in statics, // you either need to take a lock when publishing the SafeBuffer, or you // need to create a local, initialize the SafeBuffer, then assign to the // static variable (perhaps using Interlocked.CompareExchange). Of course, // assignments in a static class constructor are under a lock implicitly. using System; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.Versioning; namespace System.Runtime.InteropServices { public abstract unsafe class SafeBuffer : SafeHandle { // Steal UIntPtr.MaxValue as our uninitialized value. private static readonly UIntPtr Uninitialized = (UIntPtr.Size == 4) ? ((UIntPtr)UInt32.MaxValue) : ((UIntPtr)UInt64.MaxValue); private UIntPtr _numBytes; protected SafeBuffer(bool ownsHandle) : base(IntPtr.Zero, ownsHandle) { _numBytes = Uninitialized; } // On the desktop CLR, SafeBuffer has access to the internal handle field since they're both in // mscorlib. For this refactoring, we'll keep the name the same to minimize deltas, but shim // through to DangerousGetHandle private new IntPtr handle { get { return DangerousGetHandle(); } } public override bool IsInvalid { get { return DangerousGetHandle() == IntPtr.Zero || DangerousGetHandle() == new IntPtr(-1); } } /// <summary> /// Specifies the size of the region of memory, in bytes. Must be /// called before using the SafeBuffer. /// </summary> /// <param name="numBytes">Number of valid bytes in memory.</param> [CLSCompliant(false)] public void Initialize(ulong numBytes) { if (numBytes < 0) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_NeedNonNegNum); if (IntPtr.Size == 4 && numBytes > UInt32.MaxValue) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_AddressSpace); Contract.EndContractBlock(); if (numBytes >= (ulong)Uninitialized) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_UIntPtrMaxMinusOne); _numBytes = (UIntPtr)numBytes; } /// <summary> /// Specifies the the size of the region in memory, as the number of /// elements in an array. Must be called before using the SafeBuffer. /// </summary> [CLSCompliant(false)] public void Initialize(uint numElements, uint sizeOfEachElement) { if (numElements < 0) throw new ArgumentOutOfRangeException(nameof(numElements), SR.ArgumentOutOfRange_NeedNonNegNum); if (sizeOfEachElement < 0) throw new ArgumentOutOfRangeException(nameof(sizeOfEachElement), SR.ArgumentOutOfRange_NeedNonNegNum); if (IntPtr.Size == 4 && numElements * sizeOfEachElement > UInt32.MaxValue) throw new ArgumentOutOfRangeException("numBytes", SR.ArgumentOutOfRange_AddressSpace); Contract.EndContractBlock(); if (numElements * sizeOfEachElement >= (ulong)Uninitialized) throw new ArgumentOutOfRangeException(nameof(numElements), SR.ArgumentOutOfRange_UIntPtrMaxMinusOne); _numBytes = checked((UIntPtr)(numElements * sizeOfEachElement)); } /// <summary> /// Specifies the the size of the region in memory, as the number of /// elements in an array. Must be called before using the SafeBuffer. /// </summary> [CLSCompliant(false)] public void Initialize<T>(uint numElements) where T : struct { Initialize(numElements, AlignedSizeOf<T>()); } // Callers should ensure that they check whether the pointer ref param // is null when AcquirePointer returns. If it is not null, they must // call ReleasePointer in a CER. This method calls DangerousAddRef // & exposes the pointer. Unlike Read, it does not alter the "current // position" of the pointer. Here's how to use it: // // byte* pointer = null; // RuntimeHelpers.PrepareConstrainedRegions(); // try { // safeBuffer.AcquirePointer(ref pointer); // // Use pointer here, with your own bounds checking // } // finally { // if (pointer != null) // safeBuffer.ReleasePointer(); // } // // Note: If you cast this byte* to a T*, you have to worry about // whether your pointer is aligned. Additionally, you must take // responsibility for all bounds checking with this pointer. /// <summary> /// Obtain the pointer from a SafeBuffer for a block of code, /// with the express responsibility for bounds checking and calling /// ReleasePointer later within a CER to ensure the pointer can be /// freed later. This method either completes successfully or /// throws an exception and returns with pointer set to null. /// </summary> /// <param name="pointer">A byte*, passed by reference, to receive /// the pointer from within the SafeBuffer. You must set /// pointer to null before calling this method.</param> [CLSCompliant(false)] public void AcquirePointer(ref byte* pointer) { if (_numBytes == Uninitialized) throw NotInitialized(); pointer = null; try { } finally { bool junk = false; DangerousAddRef(ref junk); pointer = (byte*)handle; } } public void ReleasePointer() { if (_numBytes == Uninitialized) throw NotInitialized(); DangerousRelease(); } /// <summary> /// Read a value type from memory at the given offset. This is /// equivalent to: return *(T*)(bytePtr + byteOffset); /// </summary> /// <typeparam name="T">The value type to read</typeparam> /// <param name="byteOffset">Where to start reading from memory. You /// may have to consider alignment.</param> /// <returns>An instance of T read from memory.</returns> [CLSCompliant(false)] public T Read<T>(ulong byteOffset) where T : struct { if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = SizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, sizeofT); // return *(T*) (_ptr + byteOffset); T value = default(T); bool mustCallRelease = false; try { DangerousAddRef(ref mustCallRelease); fixed (byte* pStructure = &Unsafe.As<T, byte>(ref value)) Buffer.Memmove(pStructure, ptr, sizeofT); } finally { if (mustCallRelease) DangerousRelease(); } return value; } [CLSCompliant(false)] public void ReadArray<T>(ulong byteOffset, T[] array, int index, int count) where T : struct { if (array == null) throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = SizeOf<T>(); uint alignedSizeofT = AlignedSizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count))); bool mustCallRelease = false; try { DangerousAddRef(ref mustCallRelease); if (count > 0) { unsafe { fixed (byte* pStructure = &Unsafe.As<T, byte>(ref array[index])) { for (int i = 0; i < count; i++) Buffer.Memmove(pStructure + sizeofT * i, ptr + alignedSizeofT * i, sizeofT); } } } } finally { if (mustCallRelease) DangerousRelease(); } } /// <summary> /// Write a value type to memory at the given offset. This is /// equivalent to: *(T*)(bytePtr + byteOffset) = value; /// </summary> /// <typeparam name="T">The type of the value type to write to memory.</typeparam> /// <param name="byteOffset">The location in memory to write to. You /// may have to consider alignment.</param> /// <param name="value">The value type to write to memory.</param> [CLSCompliant(false)] public void Write<T>(ulong byteOffset, T value) where T : struct { if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = SizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, sizeofT); // *((T*) (_ptr + byteOffset)) = value; bool mustCallRelease = false; try { DangerousAddRef(ref mustCallRelease); fixed (byte* pStructure = &Unsafe.As<T, byte>(ref value)) Buffer.Memmove(ptr, pStructure, sizeofT); } finally { if (mustCallRelease) DangerousRelease(); } } [CLSCompliant(false)] public void WriteArray<T>(ulong byteOffset, T[] array, int index, int count) where T : struct { if (array == null) throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); if (_numBytes == Uninitialized) throw NotInitialized(); uint sizeofT = SizeOf<T>(); uint alignedSizeofT = AlignedSizeOf<T>(); byte* ptr = (byte*)handle + byteOffset; SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count))); bool mustCallRelease = false; try { DangerousAddRef(ref mustCallRelease); if (count > 0) { unsafe { fixed (byte* pStructure = &Unsafe.As<T, byte>(ref array[index])) { for (int i = 0; i < count; i++) Buffer.Memmove(ptr + alignedSizeofT * i, pStructure + sizeofT * i, sizeofT); } } } } finally { if (mustCallRelease) DangerousRelease(); } } /// <summary> /// Returns the number of bytes in the memory region. /// </summary> [CLSCompliant(false)] public ulong ByteLength { get { if (_numBytes == Uninitialized) throw NotInitialized(); return (ulong)_numBytes; } } /* No indexer. The perf would be misleadingly bad. People should use * AcquirePointer and ReleasePointer instead. */ private void SpaceCheck(byte* ptr, ulong sizeInBytes) { if ((ulong)_numBytes < sizeInBytes) NotEnoughRoom(); if ((ulong)(ptr - (byte*)handle) > ((ulong)_numBytes) - sizeInBytes) NotEnoughRoom(); } private static void NotEnoughRoom() { throw new ArgumentException(SR.Arg_BufferTooSmall); } private static InvalidOperationException NotInitialized() { Debug.Assert(false, "Uninitialized SafeBuffer! Someone needs to call Initialize before using this instance!"); return new InvalidOperationException(SR.InvalidOperation_MustCallInitialize); } #region "SizeOf Helpers" /// <summary> /// Returns the aligned size of an instance of a value type. /// </summary> internal static uint AlignedSizeOf<T>() where T : struct { uint size = SizeOf<T>(); if (size == 1 || size == 2) { return size; } if (IntPtr.Size == 8 && size == 4) { return size; } return (uint)(((size + 3) & (~3))); } private static uint SizeOf<T>() where T : struct { RuntimeTypeHandle structureTypeHandle = typeof(T).TypeHandle; if (!structureTypeHandle.IsBlittable()) throw new ArgumentException(SR.Argument_NeedStructWithNoRefs); return (uint)Unsafe.SizeOf<T>(); } #endregion } }
39.931818
123
0.584121
[ "MIT" ]
hoyMS/corert
src/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeBuffer.cs
17,570
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using Microsoft.AspNetCore.HttpSys.Internal; namespace Microsoft.AspNetCore.Server.HttpSys; // See the native HTTP_TIMEOUT_LIMIT_INFO structure documentation for additional information. // http://msdn.microsoft.com/en-us/library/aa364661.aspx /// <summary> /// Exposes the Http.Sys timeout configurations. These may also be configured in the registry. /// These settings do not apply when attaching to an existing queue. /// </summary> public sealed class TimeoutManager { private static readonly int TimeoutLimitSize = Marshal.SizeOf<HttpApiTypes.HTTP_TIMEOUT_LIMIT_INFO>(); private UrlGroup? _urlGroup; private readonly int[] _timeouts; private uint _minSendBytesPerSecond; internal TimeoutManager() { // We have to maintain local state since we allow applications to set individual timeouts. Native Http // API for setting timeouts expects all timeout values in every call so we have remember timeout values // to fill in the blanks. Except MinSendBytesPerSecond, local state for remaining five timeouts is // maintained in timeouts array. // // No initialization is required because a value of zero indicates that system defaults should be used. _timeouts = new int[5]; } #region Properties /// <summary> /// The time, in seconds, allowed for the request entity body to arrive. The default timer is 2 minutes. /// /// The HTTP Server API turns on this timer when the request has an entity body. The timer expiration is /// initially set to the configured value. When the HTTP Server API receives additional data indications on the /// request, it resets the timer to give the connection another interval. /// /// Use TimeSpan.Zero to indicate that system defaults should be used. /// </summary> public TimeSpan EntityBody { get { return GetTimeSpanTimeout(HttpApiTypes.HTTP_TIMEOUT_TYPE.EntityBody); } set { SetTimeSpanTimeout(HttpApiTypes.HTTP_TIMEOUT_TYPE.EntityBody, value); } } /// <summary> /// The time, in seconds, allowed for the HTTP Server API to drain the entity body on a Keep-Alive connection. /// The default timer is 2 minutes. /// /// On a Keep-Alive connection, after the application has sent a response for a request and before the request /// entity body has completely arrived, the HTTP Server API starts draining the remainder of the entity body to /// reach another potentially pipelined request from the client. If the time to drain the remaining entity body /// exceeds the allowed period the connection is timed out. /// /// Use TimeSpan.Zero to indicate that system defaults should be used. /// </summary> public TimeSpan DrainEntityBody { get { return GetTimeSpanTimeout(HttpApiTypes.HTTP_TIMEOUT_TYPE.DrainEntityBody); } set { SetTimeSpanTimeout(HttpApiTypes.HTTP_TIMEOUT_TYPE.DrainEntityBody, value); } } /// <summary> /// The time, in seconds, allowed for the request to remain in the request queue before the application picks /// it up. The default timer is 2 minutes. /// /// Use TimeSpan.Zero to indicate that system defaults should be used. /// </summary> public TimeSpan RequestQueue { get { return GetTimeSpanTimeout(HttpApiTypes.HTTP_TIMEOUT_TYPE.RequestQueue); } set { SetTimeSpanTimeout(HttpApiTypes.HTTP_TIMEOUT_TYPE.RequestQueue, value); } } /// <summary> /// The time, in seconds, allowed for an idle connection. The default timer is 2 minutes. /// /// This timeout is only enforced after the first request on the connection is routed to the application. /// /// Use TimeSpan.Zero to indicate that system defaults should be used. /// </summary> public TimeSpan IdleConnection { get { return GetTimeSpanTimeout(HttpApiTypes.HTTP_TIMEOUT_TYPE.IdleConnection); } set { SetTimeSpanTimeout(HttpApiTypes.HTTP_TIMEOUT_TYPE.IdleConnection, value); } } /// <summary> /// The time, in seconds, allowed for the HTTP Server API to parse the request header. The default timer is /// 2 minutes. /// /// This timeout is only enforced after the first request on the connection is routed to the application. /// /// Use TimeSpan.Zero to indicate that system defaults should be used. /// </summary> public TimeSpan HeaderWait { get { return GetTimeSpanTimeout(HttpApiTypes.HTTP_TIMEOUT_TYPE.HeaderWait); } set { SetTimeSpanTimeout(HttpApiTypes.HTTP_TIMEOUT_TYPE.HeaderWait, value); } } /// <summary> /// The minimum send rate, in bytes-per-second, for the response. The default response send rate is 150 /// bytes-per-second. /// /// Use 0 to indicate that system defaults should be used. /// /// To disable this timer set it to UInt32.MaxValue /// </summary> public long MinSendBytesPerSecond { get { // Since we maintain local state, GET is local. return _minSendBytesPerSecond; } set { // MinSendRate value is ULONG in native layer. if (value < 0 || value > uint.MaxValue) { throw new ArgumentOutOfRangeException(nameof(value)); } SetUrlGroupTimeouts(_timeouts, (uint)value); _minSendBytesPerSecond = (uint)value; } } #endregion Properties #region Helpers private TimeSpan GetTimeSpanTimeout(HttpApiTypes.HTTP_TIMEOUT_TYPE type) { // Since we maintain local state, GET is local. return new TimeSpan(0, 0, (int)_timeouts[(int)type]); } private void SetTimeSpanTimeout(HttpApiTypes.HTTP_TIMEOUT_TYPE type, TimeSpan value) { // All timeouts are defined as USHORT in native layer (except MinSendRate, which is ULONG). Make sure that // timeout value is within range. var timeoutValue = Convert.ToInt64(value.TotalSeconds); if (timeoutValue < 0 || timeoutValue > ushort.MaxValue) { throw new ArgumentOutOfRangeException(nameof(value)); } // Use local state to get values for other timeouts. Call into the native layer and if that // call succeeds, update local state. var newTimeouts = (int[])_timeouts.Clone(); newTimeouts[(int)type] = (int)timeoutValue; SetUrlGroupTimeouts(newTimeouts, _minSendBytesPerSecond); _timeouts[(int)type] = (int)timeoutValue; } internal void SetUrlGroupTimeouts(UrlGroup urlGroup) { _urlGroup = urlGroup; SetUrlGroupTimeouts(_timeouts, _minSendBytesPerSecond); } private unsafe void SetUrlGroupTimeouts(int[] timeouts, uint minSendBytesPerSecond) { if (_urlGroup == null) { // Not started yet return; } var timeoutinfo = new HttpApiTypes.HTTP_TIMEOUT_LIMIT_INFO(); timeoutinfo.Flags = HttpApiTypes.HTTP_FLAGS.HTTP_PROPERTY_FLAG_PRESENT; timeoutinfo.DrainEntityBody = (ushort)timeouts[(int)HttpApiTypes.HTTP_TIMEOUT_TYPE.DrainEntityBody]; timeoutinfo.EntityBody = (ushort)timeouts[(int)HttpApiTypes.HTTP_TIMEOUT_TYPE.EntityBody]; timeoutinfo.RequestQueue = (ushort)timeouts[(int)HttpApiTypes.HTTP_TIMEOUT_TYPE.RequestQueue]; timeoutinfo.IdleConnection = (ushort)timeouts[(int)HttpApiTypes.HTTP_TIMEOUT_TYPE.IdleConnection]; timeoutinfo.HeaderWait = (ushort)timeouts[(int)HttpApiTypes.HTTP_TIMEOUT_TYPE.HeaderWait]; timeoutinfo.MinSendRate = minSendBytesPerSecond; var infoptr = new IntPtr(&timeoutinfo); _urlGroup.SetProperty( HttpApiTypes.HTTP_SERVER_PROPERTY.HttpServerTimeoutsProperty, infoptr, (uint)TimeoutLimitSize); } #endregion Helpers }
35.677966
115
0.660808
[ "MIT" ]
AndrewTriesToCode/aspnetcore
src/Servers/HttpSys/src/TimeoutManager.cs
8,420
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics; using Microsoft.TestPlatform.TestUtilities; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestTools.UnitTesting; #nullable disable namespace Microsoft.TestPlatform.ObjectModel.PlatformTests; [TestClass] public class DiaSessionTests : IntegrationTestBase { private const string NET451 = "net451"; private const string NETCOREAPP21 = "netcoreapp2.1"; public static string GetAndSetTargetFrameWork(IntegrationTestEnvironment testEnvironment) { var currentTargetFrameWork = testEnvironment.TargetFramework; testEnvironment.TargetFramework = #if NETFRAMEWORK NET451; #else NETCOREAPP21; #endif return currentTargetFrameWork; } [TestMethod] public void GetNavigationDataShouldReturnCorrectFileNameAndLineNumber() { var currentTargetFrameWork = GetAndSetTargetFrameWork(_testEnvironment); var assemblyPath = GetAssetFullPath("SimpleClassLibrary.dll"); var diaSession = new DiaSession(assemblyPath); DiaNavigationData diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.Class1", "PassingTest"); Assert.IsNotNull(diaNavigationData, "Failed to get navigation data"); StringAssert.EndsWith(diaNavigationData.FileName, @"\SimpleClassLibrary\Class1.cs"); ValidateMinLineNumber(11, diaNavigationData.MinLineNumber); Assert.AreEqual(13, diaNavigationData.MaxLineNumber, "Incorrect max line number"); _testEnvironment.TargetFramework = currentTargetFrameWork; } [TestMethod] public void GetNavigationDataShouldReturnCorrectDataForAsyncMethod() { var currentTargetFrameWork = GetAndSetTargetFrameWork(_testEnvironment); var assemblyPath = GetAssetFullPath("SimpleClassLibrary.dll"); var diaSession = new DiaSession(assemblyPath); DiaNavigationData diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.Class1+<AsyncTestMethod>d__1", "MoveNext"); Assert.IsNotNull(diaNavigationData, "Failed to get navigation data"); StringAssert.EndsWith(diaNavigationData.FileName, @"\SimpleClassLibrary\Class1.cs"); ValidateMinLineNumber(16, diaNavigationData.MinLineNumber); Assert.AreEqual(18, diaNavigationData.MaxLineNumber, "Incorrect max line number"); _testEnvironment.TargetFramework = currentTargetFrameWork; } [TestMethod] public void GetNavigationDataShouldReturnCorrectDataForOverLoadedMethod() { var currentTargetFrameWork = GetAndSetTargetFrameWork(_testEnvironment); var assemblyPath = GetAssetFullPath("SimpleClassLibrary.dll"); var diaSession = new DiaSession(assemblyPath); DiaNavigationData diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.Class1", "OverLoadedMethod"); Assert.IsNotNull(diaNavigationData, "Failed to get navigation data"); StringAssert.EndsWith(diaNavigationData.FileName, @"\SimpleClassLibrary\Class1.cs"); // Weird why DiaSession is now returning the first overloaded method // as compared to before when it used to return second method ValidateLineNumbers(diaNavigationData.MinLineNumber, diaNavigationData.MaxLineNumber); _testEnvironment.TargetFramework = currentTargetFrameWork; } [TestMethod] public void GetNavigationDataShouldReturnNullForNotExistMethodNameOrNotExistTypeName() { var currentTargetFrameWork = GetAndSetTargetFrameWork(_testEnvironment); var assemblyPath = GetAssetFullPath("SimpleClassLibrary.dll"); var diaSession = new DiaSession(assemblyPath); // Not exist method name DiaNavigationData diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.Class1", "NotExistMethod"); Assert.IsNull(diaNavigationData); // Not Exist Type name diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.NotExistType", "PassingTest"); Assert.IsNull(diaNavigationData); _testEnvironment.TargetFramework = currentTargetFrameWork; } [TestMethod] public void DiaSessionPerfTest() { var currentTargetFrameWork = GetAndSetTargetFrameWork(_testEnvironment); var assemblyPath = GetAssetFullPath("SimpleClassLibrary.dll"); var watch = Stopwatch.StartNew(); var diaSession = new DiaSession(assemblyPath); DiaNavigationData diaNavigationData = diaSession.GetNavigationData("SimpleClassLibrary.HugeMethodSet", "MSTest_D1_01"); watch.Stop(); Assert.IsNotNull(diaNavigationData, "Failed to get navigation data"); StringAssert.EndsWith(diaNavigationData.FileName, @"\SimpleClassLibrary\HugeMethodSet.cs"); ValidateMinLineNumber(9, diaNavigationData.MinLineNumber); Assert.AreEqual(10, diaNavigationData.MaxLineNumber); var expectedTime = 150; Assert.IsTrue(watch.Elapsed.Milliseconds < expectedTime, string.Format("DiaSession Perf test Actual time:{0} ms Expected time:{1} ms", watch.Elapsed.Milliseconds, expectedTime)); _testEnvironment.TargetFramework = currentTargetFrameWork; } private void ValidateLineNumbers(int min, int max) { // Release builds optimize code, hence min line numbers are different. if (IntegrationTestEnvironment.BuildConfiguration.StartsWith("release", StringComparison.OrdinalIgnoreCase)) { Assert.AreEqual(min, max, "Incorrect min line number"); } else { if (max == 23) { Assert.AreEqual(min + 1, max, "Incorrect min line number"); } else if (max == 27) { Assert.AreEqual(min + 1, max, "Incorrect min line number"); } else { Assert.Fail("Incorrect min/max line number"); } } } private void ValidateMinLineNumber(int expected, int actual) { // Release builds optimize code, hence min line numbers are different. if (IntegrationTestEnvironment.BuildConfiguration.StartsWith("release", StringComparison.OrdinalIgnoreCase)) { Assert.AreEqual(expected + 1, actual, "Incorrect min line number"); } else { Assert.AreEqual(expected, actual, "Incorrect min line number"); } } }
40.181818
186
0.715535
[ "MIT" ]
Evangelink/vstest
test/Microsoft.TestPlatform.ObjectModel.PlatformTests/DiaSessionTests.cs
6,632
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using Spark.Compiler; using Spark.Parser.Markup; using SparkLanguage.VsAdapters; using SparkLanguagePackageLib; using Spark.Parser; using Spark; namespace SparkLanguage { public class SourceSupervisor : ISourceSupervisor { readonly SparkViewEngine _engine; readonly MarkupGrammar _grammar; readonly ISparkSource _source; readonly string _path; uint _dwLastCookie; readonly IDictionary<uint, ISourceSupervisorEvents> _events = new Dictionary<uint, ISourceSupervisorEvents>(); static SourceSupervisor() { // To enable Visual Studio to correlate errors, the location of the // error must be allowed to come from the natural location // in the generated file. This setting is changed for the entire // AppDomain running inside the devenv process. SourceBuilder.AdjustDebugSymbolsDefault = false; } public SourceSupervisor(ISparkSource source) { _source = source; IVsHierarchy hierarchy; uint itemid; IVsTextLines buffer; _source.GetDocument(out hierarchy, out itemid, out buffer); _path = GetDocumentPath(hierarchy, itemid); //Spark.Web.Mvc.SparkView //MyBaseView var settings = new VsProjectSparkSettings(hierarchy) { PageBaseType = source.GetDefaultPageBaseType() }; var viewFolder = new VsProjectViewFolder(_source, hierarchy); _engine = new SparkViewEngine(settings) { ViewFolder = viewFolder }; _grammar = new MarkupGrammar(settings); } private static string GetDocumentPath(IVsHierarchy hierarchy, uint itemid) { var rootid = -2; var rootItem = new HierarchyItem(hierarchy, (uint)rootid); var viewItem = rootItem.FirstOrDefault(child => child.Name == "Views"); var docItem = new HierarchyItem(hierarchy, itemid); var path = docItem.Name; while (!Equals(docItem.Parent, viewItem) && !Equals(docItem.Parent, rootItem)) { docItem = docItem.Parent; path = docItem.Name + "\\" + path; } if (Equals(docItem.Parent, rootItem)) path = "$\\" + path; return path; } public void Advise(ISourceSupervisorEvents pEvents, out uint pdwCookie) { pdwCookie = ++_dwLastCookie; _events[_dwLastCookie] = pEvents; } public void Unadvise(uint dwCookie) { if (_events.ContainsKey(dwCookie)) _events.Remove(dwCookie); } class PaintInfo { public int Count { get; set; } public _SOURCEPAINTING[] Paint { get; set; } public Exception ParseError { get; set; } } class MappingInfo { public string GeneratedCode { get; set; } public int Count { get; set; } public _SOURCEMAPPING[] Mapping { get; set; } public Exception GenerationError { get; set; } } public void PrimaryTextChanged(int processImmediately) { var primaryText = _source.GetPrimaryText(); var paintInfo = GetPaintInfo(primaryText); var mappingInfo = GetMappingInfo(); foreach (var events in _events.Values) { events.OnGenerated( primaryText, mappingInfo.GeneratedCode, mappingInfo.Count, ref mappingInfo.Mapping[0], paintInfo.Count, ref paintInfo.Paint[0]); } } private PaintInfo GetPaintInfo(string primaryText) { var paintInfo = new PaintInfo(); try { var sourceContext = new SourceContext(primaryText, 0, _path); var result = _grammar.Nodes(new Position(sourceContext)); paintInfo.Paint = result.Rest.GetPaint() .OfType<Paint<SparkTokenType>>() .Where(p => string.Equals(p.Begin.SourceContext.FileName, _path, StringComparison.InvariantCultureIgnoreCase)) .Select(p => new _SOURCEPAINTING { start = p.Begin.Offset, end = p.End.Offset, color = (int)p.Value }) .ToArray(); paintInfo.Count = paintInfo.Paint.Length; } catch (Exception ex) { paintInfo.ParseError = ex; } if (paintInfo.Count == 0) paintInfo.Paint = new _SOURCEPAINTING[1]; return paintInfo; } private MappingInfo GetMappingInfo() { var mappingInfo = new MappingInfo(); try { var descriptor = new SparkViewDescriptor() .AddTemplate(_path); var entry = _engine.CreateEntryInternal(descriptor, false); mappingInfo.GeneratedCode = entry.SourceCode; mappingInfo.Mapping = entry.SourceMappings .Where(m => string.Equals(m.Source.Begin.SourceContext.FileName, _path, StringComparison.InvariantCultureIgnoreCase)) .Select(m => new _SOURCEMAPPING { start1 = m.Source.Begin.Offset, end1 = m.Source.End.Offset, start2 = m.OutputBegin, end2 = m.OutputEnd }) .ToArray(); mappingInfo.Count = mappingInfo.Mapping.Length; } catch (Exception ex) { mappingInfo.GenerationError = ex; } if (mappingInfo.Count == 0) mappingInfo.Mapping = new _SOURCEMAPPING[1]; return mappingInfo; } public void OnTypeChar(IVsTextView pView, string ch) { if (ch == "{") { // add a closing "}" if it makes a complete expression or condition where one doesn't exist otherwise _TextSpan selection; pView.GetSelectionSpan(out selection); IVsTextLines buffer; pView.GetBuffer(out buffer); string before; buffer.GetLineText(0, 0, selection.iStartLine, selection.iStartIndex, out before); int iLastLine, iLastColumn; buffer.GetLastLineIndex(out iLastLine, out iLastColumn); string after; buffer.GetLineText(selection.iEndLine, selection.iEndIndex, iLastLine, iLastColumn, out after); var existingResult = _grammar.Nodes(new Position(new SourceContext(before + ch + after))); var expressionHits = existingResult.Rest.GetPaint() .OfType<Paint<Node>>() .Where(p => p.Begin.Offset <= before.Length && before.Length <= p.End.Offset && (p.Value is ExpressionNode || p.Value is ConditionNode)); // if a node exists normally, do nothing if (expressionHits.Count() != 0) return; var withCloseResult = _grammar.Nodes(new Position(new SourceContext(before + ch + "}" + after))); var withCloseHits = withCloseResult.Rest.GetPaint() .OfType<Paint<Node>>() .Where(p => p.Begin.Offset <= before.Length && before.Length <= p.End.Offset && (p.Value is ExpressionNode || p.Value is ConditionNode)); // if a close brace doesn't cause a node to exist, do nothing if (withCloseHits.Count() == 0) return; // add a closing } after the selection, then set the selection back to what it was int iAnchorLine, iAnchorCol, iEndLine, iEndCol; pView.GetSelection(out iAnchorLine, out iAnchorCol, out iEndLine, out iEndCol); _TextSpan inserted; buffer.ReplaceLines(selection.iEndLine, selection.iEndIndex, selection.iEndLine, selection.iEndIndex, "}", 1, out inserted); pView.SetSelection(iAnchorLine, iAnchorCol, iEndLine, iEndCol); } } } }
35.892857
157
0.530017
[ "Apache-2.0" ]
jayharris/spark
src/Tools/SparkLanguage/SourceSupervisor.cs
9,045
C#
/* * Copyright (c) 2012-2019 Snowflake Computing Inc. All rights reserved. */ namespace Snowflake.Data.Tests { using NUnit.Framework; using System.IO; using System.Text; using Snowflake.Data.Core; using Snowflake.Data.Client; using System.Threading.Tasks; [TestFixture] class SFReusableChunkTest { [Test] public async Task TestSimpleChunk() { string data = "[ [\"1\", \"1.234\", \"abcde\"], [\"2\", \"5.678\", \"fghi\"] ]"; byte[] bytes = Encoding.UTF8.GetBytes(data); Stream stream = new MemoryStream(bytes); IChunkParser parser = new ReusableChunkParser(stream); ExecResponseChunk chunkInfo = new ExecResponseChunk() { url = "fake", uncompressedSize = 100, rowCount = 2 }; SFReusableChunk chunk = new SFReusableChunk(3); chunk.Reset(chunkInfo, 0); await parser.ParseChunk(chunk); Assert.AreEqual("1", chunk.ExtractCell(0, 0).SafeToString()); Assert.AreEqual("1.234", chunk.ExtractCell(0, 1).SafeToString()); Assert.AreEqual("abcde", chunk.ExtractCell(0, 2).SafeToString()); Assert.AreEqual("2", chunk.ExtractCell(1, 0).SafeToString()); Assert.AreEqual("5.678", chunk.ExtractCell(1, 1).SafeToString()); Assert.AreEqual("fghi", chunk.ExtractCell(1, 2).SafeToString()); } [Test] public async Task TestChunkWithNull() { string data = "[ [null, \"1.234\", null], [\"2\", null, \"fghi\"] ]"; byte[] bytes = Encoding.UTF8.GetBytes(data); Stream stream = new MemoryStream(bytes); IChunkParser parser = new ReusableChunkParser(stream); ExecResponseChunk chunkInfo = new ExecResponseChunk() { url = "fake", uncompressedSize = 100, rowCount = 2 }; SFReusableChunk chunk = new SFReusableChunk(3); chunk.Reset(chunkInfo, 0); await parser.ParseChunk(chunk); Assert.AreEqual(null, chunk.ExtractCell(0, 0).SafeToString()); Assert.AreEqual("1.234", chunk.ExtractCell(0, 1).SafeToString()); Assert.AreEqual(null, chunk.ExtractCell(0, 2).SafeToString()); Assert.AreEqual("2", chunk.ExtractCell(1, 0).SafeToString()); Assert.AreEqual(null, chunk.ExtractCell(1, 1).SafeToString()); Assert.AreEqual("fghi", chunk.ExtractCell(1, 2).SafeToString()); } [Test] public async Task TestChunkWithDate() { string data = "[ [null, \"2019-08-21T11:58:00\", null], [\"2\", null, \"fghi\"] ]"; byte[] bytes = Encoding.UTF8.GetBytes(data); Stream stream = new MemoryStream(bytes); IChunkParser parser = new ReusableChunkParser(stream); ExecResponseChunk chunkInfo = new ExecResponseChunk() { url = "fake", uncompressedSize = 100, rowCount = 2 }; SFReusableChunk chunk = new SFReusableChunk(3); chunk.Reset(chunkInfo, 0); await parser.ParseChunk(chunk); Assert.AreEqual(null, chunk.ExtractCell(0, 0).SafeToString()); Assert.AreEqual("2019-08-21T11:58:00", chunk.ExtractCell(0, 1).SafeToString()); Assert.AreEqual(null, chunk.ExtractCell(0, 2).SafeToString()); Assert.AreEqual("2", chunk.ExtractCell(1, 0).SafeToString()); Assert.AreEqual(null, chunk.ExtractCell(1, 1).SafeToString()); Assert.AreEqual("fghi", chunk.ExtractCell(1, 2).SafeToString()); } [Test] public async Task TestChunkWithEscape() { string data = "[ [\"\\\\åäö\\nÅÄÖ\\r\", \"1.234\", null], [\"2\", null, \"fghi\"] ]"; byte[] bytes = Encoding.UTF8.GetBytes(data); Stream stream = new MemoryStream(bytes); IChunkParser parser = new ReusableChunkParser(stream); ExecResponseChunk chunkInfo = new ExecResponseChunk() { url = "fake", uncompressedSize = bytes.Length, rowCount = 2 }; SFReusableChunk chunk = new SFReusableChunk(3); chunk.Reset(chunkInfo, 0); await parser.ParseChunk(chunk); Assert.AreEqual("\\åäö\nÅÄÖ\r", chunk.ExtractCell(0, 0).SafeToString()); Assert.AreEqual("1.234", chunk.ExtractCell(0, 1).SafeToString()); Assert.AreEqual(null, chunk.ExtractCell(0, 2).SafeToString()); Assert.AreEqual("2", chunk.ExtractCell(1, 0).SafeToString()); Assert.AreEqual(null, chunk.ExtractCell(1, 1).SafeToString()); Assert.AreEqual("fghi", chunk.ExtractCell(1, 2).SafeToString()); } [Test] public async Task TestChunkWithLongString() { string longstring = new string('å', 10 * 1000 * 1000); string data = "[ [\"åäö\\nÅÄÖ\\r\", \"1.234\", null], [\"2\", null, \"" + longstring + "\"] ]"; byte[] bytes = Encoding.UTF8.GetBytes(data); Stream stream = new MemoryStream(bytes); IChunkParser parser = new ReusableChunkParser(stream); ExecResponseChunk chunkInfo = new ExecResponseChunk() { url = "fake", uncompressedSize = bytes.Length, rowCount = 2 }; SFReusableChunk chunk = new SFReusableChunk(3); chunk.Reset(chunkInfo, 0); await parser.ParseChunk(chunk); Assert.AreEqual("åäö\nÅÄÖ\r", chunk.ExtractCell(0, 0).SafeToString()); Assert.AreEqual("1.234", chunk.ExtractCell(0, 1).SafeToString()); Assert.AreEqual(null, chunk.ExtractCell(0, 2).SafeToString()); Assert.AreEqual("2", chunk.ExtractCell(1, 0).SafeToString()); Assert.AreEqual(null, chunk.ExtractCell(1, 1).SafeToString()); Assert.AreEqual(longstring, chunk.ExtractCell(1, 2).SafeToString()); } [Test] public async Task TestParserError1() { // Unterminated escape sequence string data = "[ [\"åäö\\"; byte[] bytes = Encoding.UTF8.GetBytes(data); Stream stream = new MemoryStream(bytes); IChunkParser parser = new ReusableChunkParser(stream); ExecResponseChunk chunkInfo = new ExecResponseChunk() { url = "fake", uncompressedSize = bytes.Length, rowCount = 1 }; SFReusableChunk chunk = new SFReusableChunk(1); chunk.Reset(chunkInfo, 0); try { await parser.ParseChunk(chunk); Assert.Fail(); } catch (SnowflakeDbException e) { Assert.AreEqual(SFError.INTERNAL_ERROR.GetAttribute<SFErrorAttr>().errorCode, e.ErrorCode); } } [Test] public async Task TestParserError2() { // Unterminated string string data = "[ [\"åäö"; byte[] bytes = Encoding.UTF8.GetBytes(data); Stream stream = new MemoryStream(bytes); IChunkParser parser = new ReusableChunkParser(stream); ExecResponseChunk chunkInfo = new ExecResponseChunk() { url = "fake", uncompressedSize = bytes.Length, rowCount = 1 }; SFReusableChunk chunk = new SFReusableChunk(1); chunk.Reset(chunkInfo, 0); try { await parser.ParseChunk(chunk); Assert.Fail(); } catch (SnowflakeDbException e) { Assert.AreEqual(SFError.INTERNAL_ERROR.GetAttribute<SFErrorAttr>().errorCode, e.ErrorCode); } } [Test] public async Task TestParserWithTab() { // Unterminated string string data = "[[\"abc\t\"]]"; byte[] bytes = Encoding.UTF8.GetBytes(data); Stream stream = new MemoryStream(bytes); IChunkParser parser = new ReusableChunkParser(stream); ExecResponseChunk chunkInfo = new ExecResponseChunk() { url = "fake", uncompressedSize = bytes.Length, rowCount = 1 }; SFReusableChunk chunk = new SFReusableChunk(1); chunk.Reset(chunkInfo, 0); await parser.ParseChunk(chunk); string val = chunk.ExtractCell(0, 0).SafeToString(); Assert.AreEqual("abc\t", chunk.ExtractCell(0, 0).SafeToString()); } } }
37.8107
109
0.529713
[ "Apache-2.0" ]
Christian-Oleson/snowflake-connector-net
Snowflake.Data.Tests/SFReusableChunkTest.cs
9,221
C#
using System; using System.Collections.Generic; using System.Reflection; using Microsoft.AspNetCore.Components; namespace Snijderman.Common.Blazor.Internal.Parameters; internal interface IParameterResolver { IEnumerable<PropertyInfo> ResolveParameters(Type memberType); } internal class ParameterResolver : IParameterResolver { public IEnumerable<PropertyInfo> ResolveParameters(Type memberType) { if (memberType == null) { throw new ArgumentNullException(nameof(memberType)); } var componentProperties = memberType.GetProperties(); var resolvedComponentProperties = new List<PropertyInfo>(); foreach (var componentProperty in componentProperties) { // Skip if property has no public setter if (componentProperty.GetSetMethod() is null) { continue; } // If the property is marked as a parameter add it to the list var parameterAttribute = componentProperty.GetCustomAttribute<ParameterAttribute>(); if (parameterAttribute != null) { resolvedComponentProperties.Add(componentProperty); } } return resolvedComponentProperties; } }
27.636364
93
0.694901
[ "Apache-2.0" ]
Snijderman/Snijderman
src/Snijderman.Common.Blazor/Internal/Parameters/ParameterResolver.cs
1,216
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IEntityCollectionPage.cs.tt namespace Microsoft.Graph { using System; using System.Text.Json.Serialization; /// <summary> /// The interface IDeviceManagementDeviceManagementScriptsCollectionPage. /// </summary> [InterfaceConverter(typeof(InterfaceConverter<DeviceManagementDeviceManagementScriptsCollectionPage>))] public interface IDeviceManagementDeviceManagementScriptsCollectionPage : ICollectionPage<DeviceManagementScript> { /// <summary> /// Gets the next page <see cref="IDeviceManagementDeviceManagementScriptsCollectionRequest"/> instance. /// </summary> IDeviceManagementDeviceManagementScriptsCollectionRequest NextPageRequest { get; } /// <summary> /// Initializes the NextPageRequest property. /// </summary> void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString); } }
42.28125
153
0.648189
[ "MIT" ]
ScriptBox99/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IDeviceManagementDeviceManagementScriptsCollectionPage.cs
1,353
C#
namespace Core.Utilities.Results { public class SuccessResult : Result { public SuccessResult(string message) : base(true, message) { } public SuccessResult() : base(true) { } } }
18.538462
66
0.551867
[ "MIT" ]
Tengilimm/ReCapProject-master
Core/Utilities/Results/SuccessResult.cs
243
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace ServerLocal { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
24.28
76
0.693575
[ "MIT" ]
DarkArkantos/Parking
Server/CloudServer/ServerLocal/Program.cs
609
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using Microsoft.Maui.Controls; using Microsoft.Maui.Controls.Core.UnitTests; using Mono.Cecil; using Mono.Cecil.Cil; using NUnit.Framework; namespace Microsoft.Maui.Controls.Xaml.UnitTests { public partial class DefinitionCollectionTests : ContentPage { public DefinitionCollectionTests() => InitializeComponent(); public DefinitionCollectionTests(bool useCompiledXaml) { //this stub will be replaced at compile time } [TestFixture] class Tests { [Test] public void DefinitionCollectionsParsedFromMarkup([Values(false, true)] bool useCompiledXaml) { var layout = new DefinitionCollectionTests(useCompiledXaml); var coldef = layout.grid.ColumnDefinitions; var rowdef = layout.grid.RowDefinitions; Assert.That(coldef.Count, Is.EqualTo(5)); Assert.That(coldef[0].Width, Is.EqualTo(new GridLength(1, GridUnitType.Star))); Assert.That(coldef[1].Width, Is.EqualTo(new GridLength(2, GridUnitType.Star))); Assert.That(coldef[2].Width, Is.EqualTo(new GridLength(1, GridUnitType.Auto))); Assert.That(coldef[3].Width, Is.EqualTo(new GridLength(1, GridUnitType.Star))); Assert.That(coldef[4].Width, Is.EqualTo(new GridLength(300, GridUnitType.Absolute))); Assert.That(rowdef.Count, Is.EqualTo(5)); Assert.That(rowdef[0].Height, Is.EqualTo(new GridLength(1, GridUnitType.Star))); Assert.That(rowdef[1].Height, Is.EqualTo(new GridLength(1, GridUnitType.Auto))); Assert.That(rowdef[2].Height, Is.EqualTo(new GridLength(25, GridUnitType.Absolute))); Assert.That(rowdef[3].Height, Is.EqualTo(new GridLength(14, GridUnitType.Absolute))); Assert.That(rowdef[4].Height, Is.EqualTo(new GridLength(20, GridUnitType.Absolute))); } [Test] public void DefinitionCollectionsReplacedAtCompilation() { MockCompiler.Compile(typeof(DefinitionCollectionTests), out var methodDef); Assert.That(!methodDef.Body.Instructions.Any(instr => InstructionIsDefColConvCtor(methodDef, instr)), "This Xaml still generates [Row|Col]DefinitionCollectionTypeConverter ctor"); } bool InstructionIsDefColConvCtor(MethodDefinition methodDef, Mono.Cecil.Cil.Instruction instruction) { if (instruction.OpCode != OpCodes.Newobj) return false; if (!(instruction.Operand is MethodReference methodRef)) return false; if (Build.Tasks.TypeRefComparer.Default.Equals(methodRef.DeclaringType, methodDef.Module.ImportReference(typeof(Microsoft.Maui.Controls.RowDefinitionCollectionTypeConverter)))) return true; if (Build.Tasks.TypeRefComparer.Default.Equals(methodRef.DeclaringType, methodDef.Module.ImportReference(typeof(Microsoft.Maui.Controls.ColumnDefinitionCollectionTypeConverter)))) return true; return false; } } } }
40.56338
183
0.759375
[ "MIT" ]
10088/maui
src/Controls/tests/Xaml.UnitTests/DefinitionCollectionTests.xaml.cs
2,880
C#
namespace CodeChange.Toolkit.Azure.Events { using CodeChange.Toolkit.Domain.Events; using Microsoft.ApplicationInsights; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// An Azure ApplicationInsights implementation of a domain event logger /// </summary> public sealed class DomainEventLogger : IDomainEventLogger { private readonly TelemetryClient _telemetry; public DomainEventLogger() { _telemetry = new TelemetryClient(); } /// <summary> /// Logs the domain event specified /// </summary> /// <param name="event">The domain event</param> public void LogEvent ( IDomainEvent @event ) { var properties = CompileEventProperties(@event); _telemetry.TrackEvent ( @event.ToString(), properties ); } /// <summary> /// Logs the domain event specified /// </summary> /// <param name="aggregateKey">The aggregate key</param> /// <param name="aggregateType">The aggregate type</param> /// <param name="event">The domain event</param> public void LogEvent ( string aggregateKey, Type aggregateType, IDomainEvent @event ) { Validate.IsNotEmpty(aggregateKey); Validate.IsNotNull(aggregateType); var properties = CompileEventProperties(@event); properties.Add("AggregateKey", aggregateKey); properties.Add("AggregateType", aggregateType.Name); _telemetry.TrackEvent ( @event.ToString(), properties ); } /// <summary> /// Compiles the domain event properties onto a dictionary /// </summary> /// <param name="event">The domain event</param> /// <returns>The event details as a dictionary</returns> private Dictionary<string, string> CompileEventProperties ( IDomainEvent @event ) { Validate.IsNotNull(@event); var properties = new Dictionary<string, string>() { { "EventTypeName", @event.GetType().Name }, { "EventDescription", @event.ToString() } }; var eventLog = DomainEventLog.CreateLog ( @event ); foreach (var detail in eventLog.Details) { AppendDetail ( ref properties, detail ); } return properties; } /// <summary> /// Appends the event log detail to a details dictionary /// </summary> /// <param name="properties">The event properties</param> /// <param name="detail">The event log detail to append</param> private void AppendDetail ( ref Dictionary<string, string> properties, DomainEventLogDetail detail ) { var path = String.Empty; var parentDetail = detail.Parent; while (parentDetail != null) { path = $"{parentDetail.PropertyName}.{path}"; parentDetail = parentDetail.Parent; } var key = $"{path}{detail.PropertyName}"; var value = detail.PropertyStringValue; var usedCount = properties.Count ( pair => pair.Key == key || (pair.Key.StartsWith(key) && pair.Key.EndsWith("]")) ); if (usedCount > 0) { if (usedCount == 1) { var tempValue = properties[key]; properties.Remove(key); properties.Add($"{key}[0]", tempValue); } properties.Add ( $"{key}[{usedCount}]", value ); } else { properties.Add(key, value); } foreach (var nestedDetail in detail.NestedDetails) { AppendDetail ( ref properties, nestedDetail ); } } } }
28.233129
76
0.474359
[ "MIT" ]
JTOne123/Toolkit.NET
src/CodeChange.Toolkit.Azure/Events/DomainEventLogger.cs
4,604
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using JsonApiDotNetCore.Queries; using JsonApiDotNetCore.Queries.Expressions; using JsonApiDotNetCore.Resources; namespace JsonApiDotNetCore.Repositories { /// <summary> /// Retrieves an <see cref="IResourceRepository{TResource,TId}" /> instance from the D/I container and invokes a method on it. /// </summary> public interface IResourceRepositoryAccessor { /// <summary> /// Invokes <see cref="IResourceReadRepository{TResource,TId}.GetAsync" />. /// </summary> Task<IReadOnlyCollection<TResource>> GetAsync<TResource>(QueryLayer layer, CancellationToken cancellationToken) where TResource : class, IIdentifiable; /// <summary> /// Invokes <see cref="IResourceReadRepository{TResource,TId}.GetAsync" /> for the specified resource type. /// </summary> Task<IReadOnlyCollection<IIdentifiable>> GetAsync(Type resourceType, QueryLayer layer, CancellationToken cancellationToken); /// <summary> /// Invokes <see cref="IResourceReadRepository{TResource,TId}.CountAsync" /> for the specified resource type. /// </summary> Task<int> CountAsync<TResource>(FilterExpression topFilter, CancellationToken cancellationToken) where TResource : class, IIdentifiable; /// <summary> /// Invokes <see cref="IResourceWriteRepository{TResource,TId}.GetForCreateAsync" />. /// </summary> Task<TResource> GetForCreateAsync<TResource, TId>(TId id, CancellationToken cancellationToken) where TResource : class, IIdentifiable<TId>; /// <summary> /// Invokes <see cref="IResourceWriteRepository{TResource,TId}.CreateAsync" />. /// </summary> Task CreateAsync<TResource>(TResource resourceFromRequest, TResource resourceForDatabase, CancellationToken cancellationToken) where TResource : class, IIdentifiable; /// <summary> /// Invokes <see cref="IResourceWriteRepository{TResource,TId}.GetForUpdateAsync" />. /// </summary> Task<TResource> GetForUpdateAsync<TResource>(QueryLayer queryLayer, CancellationToken cancellationToken) where TResource : class, IIdentifiable; /// <summary> /// Invokes <see cref="IResourceWriteRepository{TResource,TId}.UpdateAsync" />. /// </summary> Task UpdateAsync<TResource>(TResource resourceFromRequest, TResource resourceFromDatabase, CancellationToken cancellationToken) where TResource : class, IIdentifiable; /// <summary> /// Invokes <see cref="IResourceWriteRepository{TResource,TId}.DeleteAsync" /> for the specified resource type. /// </summary> Task DeleteAsync<TResource, TId>(TId id, CancellationToken cancellationToken) where TResource : class, IIdentifiable<TId>; /// <summary> /// Invokes <see cref="IResourceWriteRepository{TResource,TId}.SetRelationshipAsync" />. /// </summary> Task SetRelationshipAsync<TResource>(TResource leftResource, object rightValue, CancellationToken cancellationToken) where TResource : class, IIdentifiable; /// <summary> /// Invokes <see cref="IResourceWriteRepository{TResource,TId}.AddToToManyRelationshipAsync" /> for the specified resource type. /// </summary> Task AddToToManyRelationshipAsync<TResource, TId>(TId leftId, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) where TResource : class, IIdentifiable<TId>; /// <summary> /// Invokes <see cref="IResourceWriteRepository{TResource,TId}.RemoveFromToManyRelationshipAsync" />. /// </summary> Task RemoveFromToManyRelationshipAsync<TResource>(TResource leftResource, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) where TResource : class, IIdentifiable; } }
49.195122
156
0.695588
[ "MIT" ]
json-api-dotnet/JsonApiDotNetCore
src/JsonApiDotNetCore/Repositories/IResourceRepositoryAccessor.cs
4,034
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VisitorPattern.Items { public class Book : Item { public Book(float weight,string title) : base(weight) { this.Title = title; } public string Title { get; set; } } }
18.15
46
0.608815
[ "MIT" ]
GoranGit/High-Quality-Code
Homework/18.BehavioralPattern/VisitorPattern/Items/Book.cs
365
C#
// OData .NET Libraries ver. 5.6.3 // Copyright (c) Microsoft Corporation // All rights reserved. // MIT License // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the // Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. namespace Microsoft.Data.OData.Atom { #region Namespaces using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Xml; using Microsoft.Data.Edm; using Microsoft.Data.Edm.Library; using Microsoft.Data.OData.Metadata; using ODataErrorStrings = Microsoft.Data.OData.Strings; #endregion Namespaces /// <summary> /// OData ATOM deserializer for properties and value types. /// </summary> internal class ODataAtomPropertyAndValueDeserializer : ODataAtomDeserializer { #region Atomized strings /// <summary>The empty namespace used for attributes in no namespace.</summary> protected readonly string EmptyNamespace; /// <summary>OData attribute which indicates the null value for the element.</summary> protected readonly string ODataNullAttributeName; /// <summary>Element name for the items in a Collection.</summary> protected readonly string ODataCollectionItemElementName; /// <summary>XML element name to mark type attribute in Atom.</summary> protected readonly string AtomTypeAttributeName; #endregion /// <summary>The Edm.String type from the core model.</summary> private static readonly IEdmType edmStringType = EdmCoreModel.Instance.GetPrimitiveType(EdmPrimitiveTypeKind.String); /// <summary>The current recursion depth of values read by this deserializer, measured by the number of complex and collection values read so far.</summary> private int recursionDepth; /// <summary> /// Constructor. /// </summary> /// <param name="atomInputContext">The ATOM input context to read from.</param> internal ODataAtomPropertyAndValueDeserializer(ODataAtomInputContext atomInputContext) : base(atomInputContext) { DebugUtils.CheckNoExternalCallers(); XmlNameTable nameTable = this.XmlReader.NameTable; this.EmptyNamespace = nameTable.Add(string.Empty); this.ODataNullAttributeName = nameTable.Add(AtomConstants.ODataNullAttributeName); this.ODataCollectionItemElementName = nameTable.Add(AtomConstants.ODataCollectionItemElementName); this.AtomTypeAttributeName = nameTable.Add(AtomConstants.AtomTypeAttributeName); } /// <summary> /// This method creates and reads the property from the input and /// returns an <see cref="ODataProperty"/> representing the read property. /// </summary> /// <param name="expectedProperty">The <see cref="IEdmProperty"/> producing the property to be read.</param> /// <param name="expectedPropertyTypeReference">The expected type of the property to read.</param> /// <returns>An <see cref="ODataProperty"/> representing the read property.</returns> internal ODataProperty ReadTopLevelProperty(IEdmStructuralProperty expectedProperty, IEdmTypeReference expectedPropertyTypeReference) { DebugUtils.CheckNoExternalCallers(); Debug.Assert( expectedPropertyTypeReference == null || !expectedPropertyTypeReference.IsODataEntityTypeKind(), "If the expected type is specified it must not be an entity type."); Debug.Assert(this.XmlReader != null, "this.xmlReader != null"); this.ReadPayloadStart(); Debug.Assert(this.XmlReader.NodeType == XmlNodeType.Element, "The XML reader must be positioned on an Element."); // For compatibility with WCF DS Server we need to be able to read the property element in any namespace, not just the OData namespace. if (!this.UseServerFormatBehavior && !this.XmlReader.NamespaceEquals(this.XmlReader.ODataNamespace)) { throw new ODataException(ODataErrorStrings.ODataAtomPropertyAndValueDeserializer_TopLevelPropertyElementWrongNamespace(this.XmlReader.NamespaceURI, this.XmlReader.ODataNamespace)); } // this is a top level property so EPM does not apply hence it is safe to say that EPM is not present this.AssertRecursionDepthIsZero(); string expectedPropertyName = ReaderUtils.GetExpectedPropertyName(expectedProperty); ODataProperty property = this.ReadProperty( expectedPropertyName, expectedPropertyTypeReference, /*nullValueReadBehaviorKind*/ ODataNullValueBehaviorKind.Default, /* epmPresent */false); this.AssertRecursionDepthIsZero(); Debug.Assert(property != null, "If we don't ignore null values the property must not be null."); this.ReadPayloadEnd(); return property; } /// <summary> /// Reads the primitive, complex or collection value. /// </summary> /// <param name="expectedValueTypeReference">The expected type reference of the value.</param> /// <param name="duplicatePropertyNamesChecker">The duplicate property names checker to use (cached), or null if new one should be created.</param> /// <param name="collectionValidator">The collection validator instance if no expected item type has been specified; otherwise null.</param> /// <param name="validateNullValue">true to validate a null value (i.e., throw if a null value is being written for a non-nullable property); otherwise false.</param> /// <param name="epmPresent">Whether any EPM mappings exist.</param> /// <returns>The value read (null, primitive CLR value, ODataComplexValue or ODataCollectionValue).</returns> /// <remarks> /// Pre-Condition: XmlNodeType.Element - The XML element containing the value to read (also the attributes will be read from it) /// Post-Condition: XmlNodeType.EndElement - The end tag of the element. /// XmlNodeType.Element - The empty element node. /// </remarks> internal object ReadNonEntityValue( IEdmTypeReference expectedValueTypeReference, DuplicatePropertyNamesChecker duplicatePropertyNamesChecker, CollectionWithoutExpectedTypeValidator collectionValidator, bool validateNullValue, bool epmPresent) { DebugUtils.CheckNoExternalCallers(); this.AssertRecursionDepthIsZero(); object nonEntityValue = this.ReadNonEntityValueImplementation( expectedValueTypeReference, duplicatePropertyNamesChecker, collectionValidator, validateNullValue, epmPresent, /*propertyName*/ null); this.AssertRecursionDepthIsZero(); return nonEntityValue; } /// <summary> /// Determines the kind of value to read based on the payload shape. /// </summary> /// <returns>The kind of type of the value to read.</returns> /// <remarks> /// Pre-Condition: XmlNodeType.Element - The XML element containing the value to get the kind for. /// Post-Condition: XmlNodeType.Element - The XML element containing the value to get the kind for. /// </remarks> protected EdmTypeKind GetNonEntityValueKind() { this.AssertXmlCondition(XmlNodeType.Element); this.XmlReader.AssertNotBuffering(); if (this.XmlReader.IsEmptyElement) { // Empty element is considered to be a primitive value (which means Edm.String since we don't have a payload type) return EdmTypeKind.Primitive; } this.XmlReader.StartBuffering(); try { // Move to the first node of the content of the value element. this.XmlReader.Read(); bool foundCollectionItem = false; do { switch (this.XmlReader.NodeType) { case XmlNodeType.Element: if (this.XmlReader.NamespaceEquals(this.XmlReader.ODataNamespace)) { if (this.XmlReader.LocalNameEquals(this.ODataCollectionItemElementName) && this.Version >= ODataVersion.V3) { // Note that even if we've already seen another d:element element // it can still be a complex value since in some cases we allow duplicate properties // in complex values, and thus we have to keep looking and only if we se just d:element // ones then we can assume it's a collection. foundCollectionItem = true; } else { // Element in the "d" namespace but not called "element" -> must be a complex value return EdmTypeKind.Complex; } } this.XmlReader.Skip(); break; case XmlNodeType.EndElement: break; default: this.XmlReader.Skip(); break; } } while (this.XmlReader.NodeType != XmlNodeType.EndElement); // If we've found at least one d:element and no other elements in the "d" namespace then it's a collection. // If we didn't find any elements in the "d" namespace then we treat this as a string value -> primitive. return foundCollectionItem ? EdmTypeKind.Collection : EdmTypeKind.Primitive; } finally { this.XmlReader.StopBuffering(); } } /// <summary> /// Reads the 'type' and 'isNull' attributes of a value. /// </summary> /// <param name="typeName">The value of the 'type' attribute or null if no 'type' attribute exists.</param> /// <param name="isNull">The value of the 'isNull' attribute or null if no 'isNull' attribute exists.</param> /// <remarks> /// Pre-Condition: XmlNodeType.Element - The element to read attributes from. /// Post-Condition: XmlNodeType.Element - The element to read attributes from. /// </remarks> protected void ReadNonEntityValueAttributes(out string typeName, out bool isNull) { this.AssertXmlCondition(XmlNodeType.Element); this.XmlReader.AssertNotBuffering(); typeName = null; isNull = false; while (this.XmlReader.MoveToNextAttribute()) { if (this.XmlReader.NamespaceEquals(this.XmlReader.ODataMetadataNamespace)) { if (this.XmlReader.LocalNameEquals(this.AtomTypeAttributeName)) { // m:type typeName = this.XmlReader.Value; } else if (this.XmlReader.LocalNameEquals(this.ODataNullAttributeName)) { // m:null isNull = ODataAtomReaderUtils.ReadMetadataNullAttributeValue(this.XmlReader.Value); // Once we find m:null we stop reading further since m:null trumps any other // content (attributes or elements) break; } //// Ignore all other attributes in the metadata namespace } else if (this.UseClientFormatBehavior && this.XmlReader.NamespaceEquals(this.EmptyNamespace)) { if (this.XmlReader.LocalNameEquals(this.AtomTypeAttributeName)) { // type typeName = typeName ?? this.XmlReader.Value; } //// Ignore all other attributes in the empty namespace } //// Ignore all other attributes in all other namespaces } this.XmlReader.MoveToElement(); this.AssertXmlCondition(XmlNodeType.Element); this.XmlReader.AssertNotBuffering(); } /// <summary> /// Reads the content of a properties in an element (complex value, m:properties, ...) /// </summary> /// <param name="structuredType">The type which should declare the properties to be read. Optional.</param> /// <param name="properties">The list of properties to add properties to.</param> /// <param name="duplicatePropertyNamesChecker">The duplicate property names checker to use.</param> /// <param name="epmPresent">Whether any EPM mappings exist.</param> /// <remarks> /// Pre-Condition: XmlNodeType.Element - The element to read properties from. /// Post-Condition: XmlNodeType.Element - The element to read properties from if it is an empty element. /// XmlNodeType.EndElement - The end element of the element to read properties from. /// </remarks> protected void ReadProperties(IEdmStructuredType structuredType, ReadOnlyEnumerable<ODataProperty> properties, DuplicatePropertyNamesChecker duplicatePropertyNamesChecker, bool epmPresent) { this.AssertRecursionDepthIsZero(); this.ReadPropertiesImplementation( structuredType, properties, duplicatePropertyNamesChecker, epmPresent); this.AssertRecursionDepthIsZero(); } /// <summary> /// Reads the primitive, complex or collection value. /// </summary> /// <param name="expectedTypeReference">The expected type reference of the value.</param> /// <param name="duplicatePropertyNamesChecker">The duplicate property names checker to use (cached), or null if new one should be created.</param> /// <param name="collectionValidator">The collection validator instance if no expected item type has been specified; otherwise null.</param> /// <param name="validateNullValue">true to validate a null value (i.e., throw if a null value is being written for a non-nullable property); otherwise false.</param> /// <param name="epmPresent">Whether any EPM mappings exist.</param> /// <param name="propertyName">The name of the property whose value is being read, if applicable (used for error reporting).</param> /// <returns>The value read (null, primitive CLR value, ODataComplexValue or ODataCollectionValue).</returns> /// <remarks> /// Pre-Condition: XmlNodeType.Element - The XML element containing the value to read (also the attributes will be read from it) /// Post-Condition: XmlNodeType.EndElement - The end tag of the element. /// XmlNodeType.Element - The empty element node. /// </remarks> private object ReadNonEntityValueImplementation(IEdmTypeReference expectedTypeReference, DuplicatePropertyNamesChecker duplicatePropertyNamesChecker, CollectionWithoutExpectedTypeValidator collectionValidator, bool validateNullValue, bool epmPresent, string propertyName) { this.AssertXmlCondition(XmlNodeType.Element); Debug.Assert( expectedTypeReference == null || !expectedTypeReference.IsODataEntityTypeKind(), "Only primitive, complex or collection types can be read by this method."); Debug.Assert( expectedTypeReference == null || collectionValidator == null, "If an expected value type reference is specified, no collection validator must be provided."); this.XmlReader.AssertNotBuffering(); // Read the attributes looking for m:type and m:null string payloadTypeName; bool isNull; this.ReadNonEntityValueAttributes(out payloadTypeName, out isNull); object result; if (isNull) { result = this.ReadNullValue(expectedTypeReference, validateNullValue, propertyName); } else { // If we could derive the item type name from the collection's type name and no type name was specified in the payload // fill it in now. EdmTypeKind payloadTypeKind; bool derivedItemTypeNameFromCollectionTypeName = false; if (collectionValidator != null && payloadTypeName == null) { payloadTypeName = collectionValidator.ItemTypeNameFromCollection; payloadTypeKind = collectionValidator.ItemTypeKindFromCollection; derivedItemTypeNameFromCollectionTypeName = payloadTypeKind != EdmTypeKind.None; } // Resolve the payload type name and compute the target type kind and target type reference. SerializationTypeNameAnnotation serializationTypeNameAnnotation; EdmTypeKind targetTypeKind; IEdmTypeReference targetTypeReference = ReaderValidationUtils.ResolvePayloadTypeNameAndComputeTargetType( EdmTypeKind.None, /*defaultPrimitivePayloadType*/ edmStringType, expectedTypeReference, payloadTypeName, this.Model, this.MessageReaderSettings, this.Version, this.GetNonEntityValueKind, out targetTypeKind, out serializationTypeNameAnnotation); if (derivedItemTypeNameFromCollectionTypeName) { Debug.Assert( serializationTypeNameAnnotation == null, "If we derived the item type name from the collection type name we must not have created a serialization type name annotation."); serializationTypeNameAnnotation = new SerializationTypeNameAnnotation { TypeName = null }; } // If we have no expected type make sure the collection items are of the same kind and specify the same name. if (collectionValidator != null) { Debug.Assert(expectedTypeReference == null, "If a collection validator is specified there must not be an expected value type reference."); collectionValidator.ValidateCollectionItem(payloadTypeName, targetTypeKind); } switch (targetTypeKind) { case EdmTypeKind.Primitive: Debug.Assert(targetTypeReference != null && targetTypeReference.IsODataPrimitiveTypeKind(), "Expected an OData primitive type."); result = this.ReadPrimitiveValue(targetTypeReference.AsPrimitive()); break; case EdmTypeKind.Complex: Debug.Assert(targetTypeReference == null || targetTypeReference.IsComplex(), "Expected a complex type."); result = this.ReadComplexValue( targetTypeReference == null ? null : targetTypeReference.AsComplex(), payloadTypeName, serializationTypeNameAnnotation, duplicatePropertyNamesChecker, epmPresent); break; case EdmTypeKind.Collection: IEdmCollectionTypeReference collectionTypeReference = ValidationUtils.ValidateCollectionType(targetTypeReference); result = this.ReadCollectionValue( collectionTypeReference, payloadTypeName, serializationTypeNameAnnotation); break; default: throw new ODataException(ODataErrorStrings.General_InternalError(InternalErrorCodes.ODataAtomPropertyAndValueDeserializer_ReadNonEntityValue)); } } this.AssertXmlCondition(true, XmlNodeType.EndElement); this.XmlReader.AssertNotBuffering(); return result; } /// <summary> /// Read a null value from the payload. /// </summary> /// <param name="expectedTypeReference">The expected type reference (for validation purposes).</param> /// <param name="validateNullValue">true to validate the value against the <paramref name="expectedTypeReference"/>.</param> /// <param name="propertyName">The name of the property whose value is being read, if applicable (used for error reporting).</param> /// <returns>The null value.</returns> private object ReadNullValue(IEdmTypeReference expectedTypeReference, bool validateNullValue, string propertyName) { // The m:null attribute has a precedence over the content of the element, thus if we find m:null='true' we ignore the content of the element. this.XmlReader.SkipElementContent(); // NOTE: when reading a null value we will never ask the type resolver (if present) to resolve the // type; we always fall back to the expected type. ReaderValidationUtils.ValidateNullValue(this.Model, expectedTypeReference, this.MessageReaderSettings, validateNullValue, this.Version, propertyName); return null; } /// <summary> /// Reads the content of a properties in an element (complex value, m:properties, ...) /// </summary> /// <param name="structuredType">The type which should declare the properties to be read. Optional.</param> /// <param name="properties">The list of properties to add properties to.</param> /// <param name="duplicatePropertyNamesChecker">The duplicate property names checker to use.</param> /// <param name="epmPresent">Whether any EPM mappings exist.</param> /// <remarks> /// Pre-Condition: XmlNodeType.Element - The element to read properties from. /// Post-Condition: XmlNodeType.Element - The element to read properties from if it is an empty element. /// XmlNodeType.EndElement - The end element of the element to read properties from. /// </remarks> private void ReadPropertiesImplementation(IEdmStructuredType structuredType, ReadOnlyEnumerable<ODataProperty> properties, DuplicatePropertyNamesChecker duplicatePropertyNamesChecker, bool epmPresent) { Debug.Assert(properties != null, "properties != null"); Debug.Assert(duplicatePropertyNamesChecker != null, "duplicatePropertyNamesChecker != null"); this.AssertXmlCondition(XmlNodeType.Element); // Empty values are valid - they have no properties if (!this.XmlReader.IsEmptyElement) { // Read over the complex value element to its first child node (or end-element) this.XmlReader.ReadStartElement(); do { switch (this.XmlReader.NodeType) { case XmlNodeType.Element: if (this.XmlReader.NamespaceEquals(this.XmlReader.ODataNamespace)) { // Found a property IEdmProperty edmProperty = null; bool isOpen = false; bool ignoreProperty = false; if (structuredType != null) { // Lookup the property in metadata edmProperty = ReaderValidationUtils.ValidateValuePropertyDefined(this.XmlReader.LocalName, structuredType, this.MessageReaderSettings, out ignoreProperty); if (edmProperty != null && edmProperty.PropertyKind == EdmPropertyKind.Navigation) { throw new ODataException(ODataErrorStrings.ODataAtomPropertyAndValueDeserializer_NavigationPropertyInProperties(edmProperty.Name, structuredType)); } // If the property was not declared, it must be open. isOpen = edmProperty == null; } if (ignoreProperty) { this.XmlReader.Skip(); } else { ODataNullValueBehaviorKind nullValueReadBehaviorKind = this.ReadingResponse || edmProperty == null ? ODataNullValueBehaviorKind.Default : this.Model.NullValueReadBehaviorKind(edmProperty); ODataProperty property = this.ReadProperty( edmProperty == null ? null : edmProperty.Name, edmProperty == null ? null : edmProperty.Type, nullValueReadBehaviorKind, epmPresent); Debug.Assert( property != null || nullValueReadBehaviorKind == ODataNullValueBehaviorKind.IgnoreValue, "If we don't ignore null values the property must not be null."); if (property != null) { if (isOpen) { ValidationUtils.ValidateOpenPropertyValue(property.Name, property.Value, this.MessageReaderSettings.UndeclaredPropertyBehaviorKinds); } duplicatePropertyNamesChecker.CheckForDuplicatePropertyNames(property); properties.AddToSourceList(property); } } } else { this.XmlReader.Skip(); } break; case XmlNodeType.EndElement: // End of the complex value. break; default: // Non-element so for example a text node, just ignore this.XmlReader.Skip(); break; } } while (this.XmlReader.NodeType != XmlNodeType.EndElement); } } /// <summary> /// Reads a property. /// </summary> /// <param name="expectedPropertyName">The expected property name to be read from the payload (or null if no expected property name was specified).</param> /// <param name="expectedPropertyTypeReference">The expected type reference of the property value.</param> /// <param name="nullValueReadBehaviorKind">Behavior to use when reading null value for the property.</param> /// <param name="epmPresent">Whether any EPM mappings exist.</param> /// <returns>The ODataProperty representing the property in question; if null is returned from this method it means that the property is to be ignored.</returns> /// <remarks> /// Pre-Condition: XmlNodeType.Element - The XML element representing the property to read. /// Note that the method does NOT check for the property name neither it resolves the property against metadata. /// Post-Condition: Any - The node after the property. /// </remarks> private ODataProperty ReadProperty( string expectedPropertyName, IEdmTypeReference expectedPropertyTypeReference, ODataNullValueBehaviorKind nullValueReadBehaviorKind, bool epmPresent) { Debug.Assert( expectedPropertyTypeReference == null || expectedPropertyTypeReference.IsODataPrimitiveTypeKind() || expectedPropertyTypeReference.IsODataComplexTypeKind() || expectedPropertyTypeReference.IsNonEntityCollectionType(), "Only primitive, complex and collection types can be read by this method."); this.AssertXmlCondition(XmlNodeType.Element); Debug.Assert(this.UseServerFormatBehavior || this.XmlReader.NamespaceEquals(this.XmlReader.ODataNamespace), "Property elements must be in the OData namespace (unless we are running in WCF DS server format mode)."); this.XmlReader.AssertNotBuffering(); ODataProperty property = new ODataProperty(); string propertyName = this.XmlReader.LocalName; ValidationUtils.ValidatePropertyName(propertyName); ReaderValidationUtils.ValidateExpectedPropertyName(expectedPropertyName, propertyName); property.Name = propertyName; object propertyValue = this.ReadNonEntityValueImplementation( expectedPropertyTypeReference, /*duplicatePropertyNamesChecker*/ null, /*collectionValidator*/ null, nullValueReadBehaviorKind == ODataNullValueBehaviorKind.Default, epmPresent, propertyName); if (nullValueReadBehaviorKind == ODataNullValueBehaviorKind.IgnoreValue && propertyValue == null) { property = null; } else { property.Value = propertyValue; } // Read past the end tag of the property or the start tag if the element is empty. this.XmlReader.Read(); this.XmlReader.AssertNotBuffering(); return property; } /// <summary> /// Read a primitive value from the reader. /// </summary> /// <param name="actualValueTypeReference">The type of the value to read.</param> /// <returns>The value read from the payload and converted as appropriate to the target type.</returns> /// <remarks> /// Pre-Condition: XmlNodeType.Element - the element to read the value for. /// XmlNodeType.Attribute - an attribute on the element to read the value for. /// Post-Condition: XmlNodeType.Element - the element was empty. /// XmlNodeType.EndElement - the element had some value. /// /// Note that this method will not read null values, those should be handled by the caller already. /// </remarks> private object ReadPrimitiveValue(IEdmPrimitiveTypeReference actualValueTypeReference) { Debug.Assert(actualValueTypeReference != null, "actualValueTypeReference != null"); Debug.Assert(actualValueTypeReference.TypeKind() == EdmTypeKind.Primitive, "Only primitive values can be read by this method."); this.AssertXmlCondition(XmlNodeType.Element, XmlNodeType.Attribute); object result = AtomValueUtils.ReadPrimitiveValue(this.XmlReader, actualValueTypeReference); this.AssertXmlCondition(true, XmlNodeType.EndElement); Debug.Assert(result != null, "The method should never return null since it doesn't handle null values."); return result; } /// <summary> /// Read a complex value from the reader. /// </summary> /// <param name="complexTypeReference">The type reference of the value to read (or null if no type is available).</param> /// <param name="payloadTypeName">The name of the type specified in the payload.</param> /// <param name="serializationTypeNameAnnotation">The serialization type name for the complex value (possibly null).</param> /// <param name="duplicatePropertyNamesChecker">The duplicate property names checker to use (cached), or null if new one should be created.</param> /// <param name="epmPresent">Whether any EPM mappings exist.</param> /// <returns>The value read from the payload.</returns> /// <remarks> /// Pre-Condition: XmlNodeType.Element - the element to read the value for. /// XmlNodeType.Attribute - an attribute on the element to read the value for. /// Post-Condition: XmlNodeType.EndElement - the element has been read. /// /// Note that this method will not read null values, those should be handled by the caller already. /// </remarks> private ODataComplexValue ReadComplexValue( IEdmComplexTypeReference complexTypeReference, string payloadTypeName, SerializationTypeNameAnnotation serializationTypeNameAnnotation, DuplicatePropertyNamesChecker duplicatePropertyNamesChecker, bool epmPresent) { this.AssertXmlCondition(XmlNodeType.Element, XmlNodeType.Attribute); this.IncreaseRecursionDepth(); ODataComplexValue complexValue = new ODataComplexValue(); IEdmComplexType complexType = complexTypeReference == null ? null : (IEdmComplexType)complexTypeReference.Definition; // If we have a metadata type for the complex value, use that type name // otherwise use the type name from the payload (if there was any). complexValue.TypeName = complexType == null ? payloadTypeName : complexType.ODataFullName(); if (serializationTypeNameAnnotation != null) { complexValue.SetAnnotation(serializationTypeNameAnnotation); } // Move to the element (so that if we were on an attribute we can test the element for being empty) this.XmlReader.MoveToElement(); if (duplicatePropertyNamesChecker == null) { duplicatePropertyNamesChecker = this.CreateDuplicatePropertyNamesChecker(); } else { duplicatePropertyNamesChecker.Clear(); } ReadOnlyEnumerable<ODataProperty> properties = new ReadOnlyEnumerable<ODataProperty>(); this.ReadPropertiesImplementation(complexType, properties, duplicatePropertyNamesChecker, epmPresent); complexValue.Properties = properties; this.AssertXmlCondition(true, XmlNodeType.EndElement); Debug.Assert(complexValue != null, "The method should never return null since it doesn't handle null values."); this.DecreaseRecursionDepth(); return complexValue; } /// <summary> /// Read a collection from the reader. /// </summary> /// <param name="collectionTypeReference">The type of the collection to read (or null if no type is available).</param> /// <param name="payloadTypeName">The name of the collection type specified in the payload.</param> /// <param name="serializationTypeNameAnnotation">The serialization type name for the collection value (possibly null).</param> /// <returns>The value read from the payload.</returns> /// <remarks> /// Pre-Condition: XmlNodeType.Element - the element to read the value for. /// XmlNodeType.Attribute - an attribute on the element to read the value for. /// Post-Condition: XmlNodeType.Element - the element was empty. /// XmlNodeType.EndElement - the element had some value. /// /// Note that this method will not read null values, those should be handled by the caller already. /// </remarks> private ODataCollectionValue ReadCollectionValue( IEdmCollectionTypeReference collectionTypeReference, string payloadTypeName, SerializationTypeNameAnnotation serializationTypeNameAnnotation) { this.AssertXmlCondition(XmlNodeType.Element, XmlNodeType.Attribute); Debug.Assert( collectionTypeReference == null || collectionTypeReference.IsNonEntityCollectionType(), "If the metadata is specified it must denote a collection for this method to work."); this.IncreaseRecursionDepth(); ODataCollectionValue collectionValue = new ODataCollectionValue(); // If we have a metadata type for the collection, use that type name // otherwise use the type name from the payload (if there was any). collectionValue.TypeName = collectionTypeReference == null ? payloadTypeName : collectionTypeReference.ODataFullName(); if (serializationTypeNameAnnotation != null) { collectionValue.SetAnnotation(serializationTypeNameAnnotation); } // Move to the element (so that if we were on an attribute we can test the element for being empty) this.XmlReader.MoveToElement(); List<object> items = new List<object>(); // Empty collections are valid - they have no items if (!this.XmlReader.IsEmptyElement) { // Read over the collection element to its first child node (or end-element) this.XmlReader.ReadStartElement(); IEdmTypeReference itemTypeReference = collectionTypeReference == null ? null : collectionTypeReference.ElementType(); DuplicatePropertyNamesChecker duplicatePropertyNamesChecker = this.CreateDuplicatePropertyNamesChecker(); CollectionWithoutExpectedTypeValidator collectionValidator = null; if (collectionTypeReference == null) { // Parse the type name from the payload (if any), extract the item type name and construct a collection validator string itemTypeName = payloadTypeName == null ? null : EdmLibraryExtensions.GetCollectionItemTypeName(payloadTypeName); collectionValidator = new CollectionWithoutExpectedTypeValidator(itemTypeName); } do { switch (this.XmlReader.NodeType) { case XmlNodeType.Element: if (this.XmlReader.NamespaceEquals(this.XmlReader.ODataNamespace)) { if (!this.XmlReader.LocalNameEquals(this.ODataCollectionItemElementName)) { throw new ODataException(ODataErrorStrings.ODataAtomPropertyAndValueDeserializer_InvalidCollectionElement(this.XmlReader.LocalName, this.XmlReader.ODataNamespace)); } // We don't support EPM for collections so it is fine to say that EPM is not present object itemValue = this.ReadNonEntityValueImplementation( itemTypeReference, duplicatePropertyNamesChecker, collectionValidator, /*validateNullValue*/ true, /*epmPresent*/ false, /*propertyName*/ null); // read over the end tag of the element or the start tag if the element was empty. this.XmlReader.Read(); // Validate the item (for example that it's not null) ValidationUtils.ValidateCollectionItem(itemValue, false /* isStreamable */); // Note that the ReadNonEntityValue already validated that the actual type of the value matches // the expected type (the itemType). items.Add(itemValue); } else { this.XmlReader.Skip(); } break; case XmlNodeType.EndElement: // End of the collection. break; default: // Non-element so for example a text node, just ignore this.XmlReader.Skip(); break; } } while (this.XmlReader.NodeType != XmlNodeType.EndElement); } collectionValue.Items = new ReadOnlyEnumerable(items); this.AssertXmlCondition(true, XmlNodeType.EndElement); Debug.Assert(collectionValue != null, "The method should never return null since it doesn't handle null values."); this.DecreaseRecursionDepth(); return collectionValue; } /// <summary> /// Increases the recursion depth of values by 1. This will throw if the recursion depth exceeds the current limit. /// </summary> private void IncreaseRecursionDepth() { ValidationUtils.IncreaseAndValidateRecursionDepth(ref this.recursionDepth, this.MessageReaderSettings.MessageQuotas.MaxNestingDepth); } /// <summary> /// Decreases the recursion depth of values by 1. /// </summary> private void DecreaseRecursionDepth() { Debug.Assert(this.recursionDepth > 0, "Can't decrease recursion depth below 0."); this.recursionDepth--; } /// <summary> /// Asserts that the current recursion depth of values is zero. This should be true on all calls into this class from outside of this class. /// </summary> [Conditional("DEBUG")] [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "The this is needed in DEBUG build.")] private void AssertRecursionDepthIsZero() { Debug.Assert(this.recursionDepth == 0, "The current recursion depth must be 0."); } } }
54.645858
280
0.581459
[ "Apache-2.0" ]
tapika/choco
lib/Microsoft.Data.Services.Client/ODataLib/OData/Desktop/.Net4.0/Microsoft/Data/OData/Atom/ODataAtomPropertyAndValueDeserializer.cs
45,520
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using System.Threading.Tasks; using CrypticPay.Areas.Identity.Data; using CrypticPay.Data; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace CrypticPay.Areas.Community.Pages.Content { public class UploadModel : PageModel { private readonly UserManager<CrypticPayUser> _userManager; private readonly CrypticPayContext _context; private Services.DecentralizedStorage _dstorage { get; set; } [TempData] public string StatusMessage { get; set; } [BindProperty] public InputModel Input { get; set; } public class InputModel { [Required] [Display(Name = "New File")] public IFormFile NewFile { get; set; } public string Description { get; set; } public string Name { get; set; } } public UploadModel(UserManager<CrypticPayUser> userManager, Services.DecentralizedStorage dstorage, CrypticPayContext context) { _userManager = userManager; _dstorage = dstorage; _context = context; } public void OnGet() { } // upload file input to decentralized storage system // ONLY SUPPORTS IMAGES RIGHT NOW TO MINIMZE STORAGE COST // ADD MESSAGES THAT REFLECT STATUS TO CLIENT public async Task<IActionResult> OnPostUploadAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } // verify file is valid if (Input.NewFile == null || !Utils.IsValidPhoto(Input.NewFile.FileName)) return RedirectToPage(); // upload file Data.Responses.ResponseUpload response = await _dstorage.UploadFile(Input.NewFile.FileName, Input.NewFile); if(response.Status == Globals.Status.Success) { // save upload to local DB var upload = new FileUpload() { CID = response.CID, CreationTime = DateTime.Now, OwnerId = user.Id, Description = Input.Description, Name = Input.Name }; _context.Uploads.Add(upload); _context.SaveChanges(); } return RedirectToPage(); } } }
33.8875
134
0.596459
[ "Apache-2.0" ]
jettblu/Kryptik
CrypticPay/Areas/Community/Pages/Content/Upload.cshtml.cs
2,711
C#
// <copyright file="Login.cshtml.cs" company="Kiip Pazardzhik"> // Copyright (c) Kiip Pazardzhik. All rights reserved. // </copyright> namespace KiipPazardzhik.Areas.Identity.Pages.Account { using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using KiipPazardzhik.Models.Users; using KiipPazardzhik.ViewModels.User.InputModels; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; [AllowAnonymous] public class LoginModel : PageModel { private readonly UserManager<ApplicationUser> userManager; private readonly SignInManager<ApplicationUser> signInManager; private readonly ILogger<LoginModel> logger; public LoginModel( SignInManager<ApplicationUser> signInManager, ILogger<LoginModel> logger, UserManager<ApplicationUser> userManager) { this.userManager = userManager; this.signInManager = signInManager; this.logger = logger; } [BindProperty] public LoginUserInputModel Input { get; set; } public IList<AuthenticationScheme> ExternalLogins { get; set; } public string ReturnUrl { get; set; } [TempData] public string ErrorMessage { get; set; } public async Task OnGetAsync(string returnUrl = null) { if (!string.IsNullOrEmpty(this.ErrorMessage)) { this.ModelState.AddModelError(string.Empty, this.ErrorMessage); } returnUrl ??= this.Url.Content("~/"); // Clear the existing external cookie to ensure a clean login process await this.HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); this.ExternalLogins = (await this.signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); this.ReturnUrl = returnUrl; } public async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl ??= this.Url.Content("~/"); if (this.ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await this.signInManager.PasswordSignInAsync(this.Input.UserName, this.Input.Password, this.Input.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { this.logger.LogInformation("User logged in."); return this.LocalRedirect(returnUrl); } if (result.RequiresTwoFactor) { return this.RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = this.Input.RememberMe }); } if (result.IsLockedOut) { this.logger.LogWarning("User account locked out."); return this.RedirectToPage("./Lockout"); } else { this.ModelState.AddModelError(string.Empty, "Invalid login attempt."); return this.Page(); } } // If we got this far, something failed, redisplay form return this.Page(); } } }
35.60396
164
0.605951
[ "MIT" ]
indieza/Kiip-Pazardzhik
KiipPazardzhik/KiipPazardzhik/Areas/Identity/Pages/Account/Login.cshtml.cs
3,598
C#
//----------------------------------------------------------------------- // <copyright file="ProductFacetsViewModel.cs" company="Sitecore Corporation"> // Copyright (c) Sitecore Corporation 1999-2015 // </copyright> // <summary>Defines the ProductFacetsViewModel class.</summary> //----------------------------------------------------------------------- // Copyright 2015 Sitecore Corporation A/S // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // ------------------------------------------------------------------------------------------- namespace Sitecore.Commerce.Storefront.Models.Storefront { using Sitecore.Commerce.Connect.CommerceServer.Search.Models; using Sitecore.Mvc.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Used to represent a product facet list /// </summary> public class ProductFacetsViewModel : Sitecore.Mvc.Presentation.RenderingModel { /// <summary> /// Initializes a new instance of the <see cref="ProductFacetsViewModel"/> class. /// </summary> public ProductFacetsViewModel() { this.ChildProductFacets = new List<CommerceQueryFacet>(); this.ActiveFacets = new List<CommerceQueryFacet>(); } /// <summary> /// Gets or sets the list of product facets /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "This is the desired behavior")] public IEnumerable<CommerceQueryFacet> ChildProductFacets { get; protected set; } /// <summary> /// Gets or sets the list of active facets /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "This is the desired behavior")] public IEnumerable<CommerceQueryFacet> ActiveFacets { get; protected set; } /// <summary> /// Initializes the view model /// </summary> /// <param name="rendering">The rendering</param> /// <param name="products">The list of child products</param> /// <param name="searchOptions">Any search options used to find products in this category</param> public void Initialize(Rendering rendering, ProductSearchResults products, CommerceSearchOptions searchOptions) { base.Initialize(rendering); if (products != null) this.ChildProductFacets = products.Facets; this.ActiveFacets = searchOptions.FacetFields; } } }
42.467532
171
0.617431
[ "Apache-2.0" ]
Sitecore/Reference-Storefront-SCpbMD
Storefront/CSF/Models/Storefront/ProductFacetsViewModel.cs
3,272
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace RegaloParaTiAPI { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25.814815
70
0.647059
[ "MIT" ]
jdjinete/regaloparatiapistore
RegaloParaTiAPI/Program.cs
697
C#
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; namespace UnityStandardAssets.Vehicles.Car { [RequireComponent(typeof (CarController))] public class CarUserControl : MonoBehaviour { private CarController m_Car; // the car controller we want to use public bool isPlayerOne=true; public String horizontal = "Horizontal"; private String vertical= "Vertical"; private String jump ="Jump"; float h = 0; float v = 0; private void Awake() { // get the car controller m_Car = GetComponent<CarController>(); if (!isPlayerOne) { horizontal = "Horizontal_Two"; vertical= "Vertical_Two"; jump ="Jump_Two"; } else { horizontal = "Horizontal"; vertical= "Vertical"; jump ="Jump"; } } private void FixedUpdate() { if (isPlayerOne) { Debug.Log("Player 1"); h = CrossPlatformInputManager.GetAxis("Horizontal"); v = CrossPlatformInputManager.GetAxis("Vertical"); } else if(!isPlayerOne) { Debug.Log("Player 2"); h = CrossPlatformInputManager.GetAxis("Horizontal_Two"); v = CrossPlatformInputManager.GetAxis("Vertical_Two"); } /*float h = CrossPlatformInputManager.GetAxis(horizontal); float v = CrossPlatformInputManager.GetAxis(vertical);*/ #if !MOBILE_INPUT float handbrake = CrossPlatformInputManager.GetAxis(jump); m_Car.Move(h, v, v, handbrake); #else m_Car.Move(h, v, v, 0f); #endif } } }
29.3125
73
0.530917
[ "MIT" ]
DanielSzulc98/High-Speed
High Speed/Assets/Standard Assets/Vehicles/Car/Scripts/CarUserControl.cs
1,876
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using VDF = Autodesk.DataManagement.Client.Framework; using Autodesk.DataManagement.Client.Framework.Vault.Currency.Entities; using System.Collections; namespace Autodesk.VltInvSrv.iLogicSampleJob { public partial class iLogicJobAdminForm : Form { int rowIndex; public string mVaultSelected { get; private set; } public iLogicJobAdminForm() { InitializeComponent(); lblDebugInfo.Visible = false; } private void iLogicJobAdminForm_Load(object sender, EventArgs e) { //Read current configuration data from Vault or settings file bool success = mLoadFromVault(); if (success) { //MessageBox.Show("Successfully loaded settings from Vault.", "iLogic Configuration", MessageBoxButtons.OK, MessageBoxIcon.Information); iLogicJobAdmin.mSettingsChanged = false; btnSaveToVlt.Enabled = false; } else { MessageBox.Show("Could not load settings from Vault.", "iLogic Configuration", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnExport_Click(object sender, EventArgs e) { Settings mActiveSettings = new Settings(); //iLogic options tab mActiveSettings.ExternalRuleDirectories = mGetExtRuleDirs(); mActiveSettings.iLogicAddinDLLs = txtDLLsDir.Text; mActiveSettings.iLogicLogLevel = cmbLogLevel.Text; mActiveSettings.iLogicLogDir = txtLogPath.Text; mActiveSettings.ActivateDebugBreak = chckBoxBreak.Checked.ToString(); //job rules options tab mActiveSettings.VaultRuleFullFileName = txtJobRuleVault.Text; mActiveSettings.PropagateProps = chckBoxPropagateProps.Checked.ToString(); mActiveSettings.PropagateItemProps = chckBoxPropagateItemProps.Checked.ToString(); mActiveSettings.InternalRulesOption = cmbRunInternal.Text; mActiveSettings.InternalRulesOptiontext = txtInternalRuleText.Text; mActiveSettings.UseInvApp = chckInvApp.Checked.ToString(); //user rules tab mActiveSettings.UserRules = mGetUserRules(); bool mExpSuccess = mActiveSettings.Save(); if (mExpSuccess == true) { MessageBox.Show("Successfully exported settings to local file.", "Configuration Export", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Export settings to local file failed. Check the permissions Vault Extensions folder.", "Configuration Export", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private string[] mGetExtRuleDirs() { string[] mDirs = new string[dtgrdViewExtRls.Rows.Count]; for (int i = 0; i < dtgrdViewExtRls.Rows.Count; i++) { if (dtgrdViewExtRls.Rows[i].Cells[1].Value != null) { mDirs[i] = dtgrdViewExtRls.Rows[i].Cells[1].Value.ToString(); } } return mDirs; } private string[] mGetUserRules() { string[] mRules = new string[dtGrdUsrRules.RowCount]; for (int i = 0; i < dtGrdUsrRules.Rows.Count; i++) { if (dtGrdUsrRules.Rows[i].Cells[1].Value != null) { mRules[i] = dtGrdUsrRules.Rows[i].Cells[1].Value.ToString() + "|" + dtGrdUsrRules.Rows[i].Cells[2].Value.ToString() + "|" + dtGrdUsrRules.Rows[i].Cells[3].Value.ToString() + "|" + dtGrdUsrRules.Rows[i].Cells[4].Value.ToString(); } } return mRules; } private void cmbLogLevel_SelectedIndexChanged(object sender, EventArgs e) { if (cmbLogLevel.Text != "None") { lblLogPath.Enabled = true; txtLogPath.Enabled = true; btnSelectLogPath.Enabled = true; } else { lblLogPath.Enabled = false; txtLogPath.Enabled = false; btnSelectLogPath.Enabled = false; } iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; } private void cmbRunInternal_SelectedIndexChanged(object sender, EventArgs e) { if (cmbRunInternal.Text == "Containing Text...") { txtInternalRuleText.Enabled = true; lblInternalRuleText.Enabled = true; } else { txtInternalRuleText.Enabled = false; lblInternalRuleText.Enabled = false; } iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; } private void btnAddInDirSearch_Click(object sender, EventArgs e) { folderBrowserDialog1.Description = "Select Directory for iLogic Extensions..."; folderBrowserDialog1.ShowDialog(); txtDLLsDir.Text = folderBrowserDialog1.SelectedPath; folderBrowserDialog1.Dispose(); iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; } private void btnSelectLogPath_Click(object sender, EventArgs e) { folderBrowserDialog1.Description = "Select Directory for iLogic Log-Files..."; folderBrowserDialog1.ShowDialog(); txtLogPath.Text = folderBrowserDialog1.SelectedPath; folderBrowserDialog1.Dispose(); iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; } private void btnRuleDirAdd_Click(object sender, EventArgs e) { folderBrowserDialog1.Description = "Select Directory for External iLogic-Rules..."; folderBrowserDialog1.ShowDialog(); dtgrdViewExtRls.Rows.Add(new string[] { dtgrdViewExtRls.Rows.Count.ToString(), folderBrowserDialog1.SelectedPath }); mRenumber(dtgrdViewExtRls); folderBrowserDialog1.Dispose(); iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; } private void mnuExtRuleDirDelete_Click(object sender, EventArgs e) { try { DataGridViewSelectedCellCollection mSelCells = dtgrdViewExtRls.SelectedCells; DataGridViewSelectedRowCollection mSelRows = dtgrdViewExtRls.SelectedRows; foreach (DataGridViewRow item in mSelRows) { if (dtgrdViewExtRls.Rows.Count > 1 && item.IsNewRow != true) { dtgrdViewExtRls.Rows.Remove(item); } } mRenumber(dtgrdViewExtRls); iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; } catch (Exception) { } } private void btnRuleDirUp_Click(object sender, EventArgs e) { try { rowIndex = dtgrdViewExtRls.SelectedCells[0].OwningRow.Index; if (rowIndex > 0) { DataGridViewRow mRow = (DataGridViewRow)dtgrdViewExtRls.Rows[rowIndex].Clone(); mRow.Cells[0].Value = dtgrdViewExtRls.Rows[rowIndex].Cells[0].Value.ToString(); mRow.Cells[1].Value = dtgrdViewExtRls.Rows[rowIndex].Cells[1].Value.ToString(); dtgrdViewExtRls.Rows.RemoveAt(rowIndex); dtgrdViewExtRls.Rows.Insert(rowIndex - 1, mRow); foreach (DataGridViewRow row in dtgrdViewExtRls.Rows) { row.Selected = false; } //dtgrdViewExtRls.Rows[rowIndex - 1].Selected = true; } mRenumber(dtgrdViewExtRls); iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; } catch (Exception) { //the exception occurs, if the user did not select a cell or row; continue without message } } private void btnRuleDirDown_Click(object sender, EventArgs e) { try { rowIndex = dtgrdViewExtRls.SelectedCells[0].OwningRow.Index; if (rowIndex < dtgrdViewExtRls.Rows.Count - 1) { DataGridViewRow mRow = (DataGridViewRow)dtgrdViewExtRls.Rows[rowIndex].Clone(); mRow.Cells[0].Value = dtgrdViewExtRls.Rows[rowIndex].Cells[0].Value.ToString(); mRow.Cells[1].Value = dtgrdViewExtRls.Rows[rowIndex].Cells[1].Value.ToString(); dtgrdViewExtRls.Rows.RemoveAt(rowIndex); dtgrdViewExtRls.Rows.Insert(rowIndex + 1, mRow); foreach (DataGridViewRow row in dtgrdViewExtRls.Rows) { row.Selected = false; } //dtgrdViewExtRls.Rows[rowIndex + 1].Selected = true; } mRenumber(dtgrdViewExtRls); iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; } catch (Exception) { //the exception occurs, if the user did not select a cell or row; continue without message } } private void mRenumber(DataGridView dataGridView) { for (int i = 0; i < dataGridView.Rows.Count; i++) { dataGridView.Rows[i].Cells[0].Value = (i + 1).ToString(); } } private void btnImport_Click(object sender, EventArgs e) { try { Settings mNewSettings = Settings.Load(); //iLogic options tab mUpdateExtRlsGrid(mNewSettings.ExternalRuleDirectories); txtDLLsDir.Text = mNewSettings.iLogicAddinDLLs; cmbLogLevel.Text = mNewSettings.iLogicLogLevel; txtLogPath.Text = mNewSettings.iLogicLogDir; if (mNewSettings.ActivateDebugBreak == "True") { chckBoxBreak.Checked = true; } else { chckBoxBreak.Checked = false; } //job rules tab txtJobRuleVault.Text = mNewSettings.VaultRuleFullFileName; cmbRunInternal.Text = mNewSettings.InternalRulesOption; txtInternalRuleText.Text = mNewSettings.InternalRulesOptiontext; if (mNewSettings.UseInvApp == "True") { chckInvApp.Checked = true; } else { chckInvApp.Checked = false; } //user rules tab mUpdateUsrRlsGrid(mNewSettings.UserRules); //options tab if (mNewSettings.PropagateProps == "True") { chckBoxPropagateProps.Checked = true; } else { chckBoxPropagateProps.Checked = false; } if (mNewSettings.PropagateItemProps == "True") { chckBoxPropagateItemProps.Checked = true; } else { chckBoxPropagateItemProps.Checked = false; } MessageBox.Show("Successfully imported settings.", "Configuration Import", MessageBoxButtons.OK, MessageBoxIcon.Information); iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; } catch (Exception) { MessageBox.Show("Could not import settings. Check the permissions Vault Extensions folder.", "Configuration Import", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void mUpdateExtRlsGrid(string[] mExtRls) { //clear existing Data dtgrdViewExtRls.Rows.Clear(); //write settings for (int i = 0; i < mExtRls.Count(); i++) { dtgrdViewExtRls.Rows.Add(new string[] { (i + 1).ToString(), mExtRls[i] }); } } private void mUpdateUsrRlsGrid(string[] mUsrRls) { //clear existing Data dtGrdUsrRules.Rows.Clear(); //write settings string[] mRow = null; for (int i = 0; i < mUsrRls.Count(); i++) { mRow = mUsrRls[i].Split('|'); dtGrdUsrRules.Rows.Add(new string[] { (i + 1).ToString(), mRow[0], mRow[1], mRow[2], mRow[3] }); } mRenumber(dtGrdUsrRules); } private void btnOpenJobRuleVault_Click(object sender, EventArgs e) { SelectFromVault selectFromVault = new SelectFromVault(Multiselect: false); var returnval = selectFromVault.ShowDialog(); if (selectFromVault.DialogResult == DialogResult.OK) { txtJobRuleVault.Text = selectFromVault.RetFullNames.FirstOrDefault(); iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; selectFromVault.Dispose(); } } private void btnAddUserRules_Click(object sender, EventArgs e) { List<string> mUserRules = new List<string>(); SelectFromVault selectFromVault = new SelectFromVault(Multiselect: true); var returnval = selectFromVault.ShowDialog(); if (selectFromVault.DialogResult == DialogResult.OK) { for (int i = 0; i < selectFromVault.RetFullNames.Count; i++) { dtGrdUsrRules.Rows.Add(new string[] { "", selectFromVault.RetNames[i], "false", "false", selectFromVault.RetFullNames[i] }); } mRenumber(dtGrdUsrRules); iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; selectFromVault.Dispose(); } } private void mnuUserRulesDelete_Click(object sender, EventArgs e) { try { DataGridViewSelectedCellCollection mSelCells = dtGrdUsrRules.SelectedCells; DataGridViewSelectedRowCollection mSelRows = dtGrdUsrRules.SelectedRows; foreach (DataGridViewRow item in mSelRows) { if (dtGrdUsrRules.Rows.Count > 1 && item.IsNewRow != true) { dtGrdUsrRules.Rows.Remove(item); } } mRenumber(dtGrdUsrRules); iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; } catch (Exception) { } } private void btnUserRuleUp_Click(object sender, EventArgs e) { try { rowIndex = dtGrdUsrRules.SelectedCells[0].OwningRow.Index; if (rowIndex > 0) { dtGrdUsrRules.Rows[rowIndex].Selected = false; DataGridViewRow mRow = (DataGridViewRow)dtGrdUsrRules.Rows[rowIndex].Clone(); mRow.Cells[0].Value = dtGrdUsrRules.Rows[rowIndex].Cells[0].Value.ToString(); mRow.Cells[1].Value = dtGrdUsrRules.Rows[rowIndex].Cells[1].Value.ToString(); mRow.Cells[2].Value = dtGrdUsrRules.Rows[rowIndex].Cells[2].Value.ToString(); mRow.Cells[3].Value = dtGrdUsrRules.Rows[rowIndex].Cells[3].Value.ToString(); mRow.Cells[4].Value = dtGrdUsrRules.Rows[rowIndex].Cells[4].Value.ToString(); dtGrdUsrRules.Rows.RemoveAt(rowIndex); dtGrdUsrRules.Rows.Insert(rowIndex - 1, mRow); foreach (DataGridViewRow row in dtGrdUsrRules.Rows) { row.Selected = false; } //dtGrdUsrRules.Rows[rowIndex - 1].Selected = true; } mRenumber(dtGrdUsrRules); iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; } catch (Exception) { } } private void btnUserRuleDown_Click(object sender, EventArgs e) { try { rowIndex = dtGrdUsrRules.SelectedCells[0].OwningRow.Index; if (rowIndex < dtGrdUsrRules.Rows.Count - 1) { DataGridViewRow mRow = (DataGridViewRow)dtGrdUsrRules.Rows[rowIndex].Clone(); mRow.Cells[0].Value = dtGrdUsrRules.Rows[rowIndex].Cells[0].Value.ToString(); mRow.Cells[1].Value = dtGrdUsrRules.Rows[rowIndex].Cells[1].Value.ToString(); mRow.Cells[2].Value = dtGrdUsrRules.Rows[rowIndex].Cells[2].Value.ToString(); mRow.Cells[3].Value = dtGrdUsrRules.Rows[rowIndex].Cells[3].Value.ToString(); mRow.Cells[4].Value = dtGrdUsrRules.Rows[rowIndex].Cells[4].Value.ToString(); dtGrdUsrRules.Rows.RemoveAt(rowIndex); dtGrdUsrRules.Rows.Insert(rowIndex + 1, mRow); foreach (DataGridViewRow row in dtGrdUsrRules.Rows) { row.Selected = false; } } mRenumber(dtGrdUsrRules); iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; } catch (Exception) { } } private void chckBoxBreak_CheckedChanged(object sender, EventArgs e) { if (chckBoxBreak.Checked == true) { lblDebugInfo.Visible = true; } else { lblDebugInfo.Visible = false; } iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; } private void btnSaveToVlt_Click(object sender, EventArgs e) { mSaveToVault(); } private void mSaveToVault() { Settings mActiveSettings = new Settings(); //iLogic options tab mActiveSettings.ExternalRuleDirectories = mGetExtRuleDirs(); mActiveSettings.iLogicAddinDLLs = txtDLLsDir.Text; mActiveSettings.iLogicLogLevel = cmbLogLevel.Text; mActiveSettings.iLogicLogDir = txtLogPath.Text; mActiveSettings.ActivateDebugBreak = chckBoxBreak.Checked.ToString(); //job rules options tab mActiveSettings.VaultRuleFullFileName = txtJobRuleVault.Text; mActiveSettings.PropagateProps = chckBoxPropagateProps.Checked.ToString(); mActiveSettings.InternalRulesOption = cmbRunInternal.Text; mActiveSettings.InternalRulesOptiontext = txtInternalRuleText.Text; mActiveSettings.UseInvApp = chckInvApp.Checked.ToString(); //user rules tab mActiveSettings.UserRules = mGetUserRules(); bool mExpSuccess = mActiveSettings.SaveToVault(iLogicJobAdmin.mConnection); if (mExpSuccess == true) { MessageBox.Show("Successfully saved settings to Vault.", "iLogic Configuration", MessageBoxButtons.OK, MessageBoxIcon.Information); iLogicJobAdmin.mSettingsChanged = false; btnSaveToVlt.Enabled = false; } else { MessageBox.Show("Saving settings to Vault failed.", "iLogic Configuration", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnLoadFromVlt_Click(object sender, EventArgs e) { var retval = MessageBox.Show("Loading settings from Vault will overwrite all current configuration settings.\n\r Press OK to load, press Cancel to keep current settings.", "iLogic Configuration", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (retval == DialogResult.Cancel) { return; } bool success = mLoadFromVault(); if (success) { MessageBox.Show("Successfully loaded settings from Vault.", "iLogic Configuration", MessageBoxButtons.OK, MessageBoxIcon.Information); iLogicJobAdmin.mSettingsChanged = false; btnSaveToVlt.Enabled = false; } else { MessageBox.Show("Could not load settings from Vault.", "iLogic Configuration", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private bool mLoadFromVault() { try { Settings mNewSettings = Settings.LoadFromVault(iLogicJobAdmin.mConnection); //iLogic options tab mUpdateExtRlsGrid(mNewSettings.ExternalRuleDirectories); txtDLLsDir.Text = mNewSettings.iLogicAddinDLLs; cmbLogLevel.Text = mNewSettings.iLogicLogLevel; txtLogPath.Text = mNewSettings.iLogicLogDir; if (mNewSettings.ActivateDebugBreak == "True") { chckBoxBreak.Checked = true; } else { chckBoxBreak.Checked = false; } //job rules options tab txtJobRuleVault.Text = mNewSettings.VaultRuleFullFileName; cmbRunInternal.Text = mNewSettings.InternalRulesOption; txtInternalRuleText.Text = mNewSettings.InternalRulesOptiontext; if (mNewSettings.UseInvApp == "True") { chckInvApp.Checked = true; } else { chckInvApp.Checked = false; } //user rules tab mUpdateUsrRlsGrid(mNewSettings.UserRules); //options tab if (mNewSettings.PropagateProps == "True") { chckBoxPropagateProps.Checked = true; } else { chckBoxPropagateProps.Checked = false; } if (mNewSettings.PropagateItemProps == "True") { chckBoxPropagateItemProps.Checked = true; } else { chckBoxPropagateItemProps.Checked = false; } return true; } catch (Exception) { return false; } } private void mConfigChanged(object sender, EventArgs e) { iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; } private void iLogicJobAdminForm_FormClosing(object sender, FormClosingEventArgs e) { if (iLogicJobAdmin.mSettingsChanged == true) { DialogResult dialogResult = MessageBox.Show("There are unsaved changes;\n\rDo you want to save them to Vault?", "iLogic Job Administration", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dialogResult == DialogResult.Yes) { mSaveToVault(); } } } private void dtGrdUsrRules_CellContentClick(object sender, DataGridViewCellEventArgs e) { iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; } private void dtGrdUsrRules_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e) { iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; } private void dtGrdUsrRules_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { iLogicJobAdmin.mSettingsChanged = true; btnSaveToVlt.Enabled = true; } } }
37.821053
261
0.544829
[ "MIT" ]
koechlm/Vault-Sample---Job4iLogicRuleExec
Autodesk.VltInvSrv.iLogicSampleJob/iLogicJobAdminForm.cs
25,153
C#
using System; using ShapesApp.Library; namespace ShapesApp.App { static class Program { static void Main(string[] args) { double length = 3; string input; do { Console.WriteLine("Enter a length:"); input = Console.ReadLine(); } while (!double.TryParse(input, out length)); // C# has something alled "out" parameters // an out parameter cannot have a value before you pass it double width; do { Console.WriteLine("Enter a width:"); input = Console.ReadLine(); } while (!double.TryParse(input, out width)); // similar to collection initializer, we have property intializer var rectangle = new Rectangle() { Length = length, Width = width }; //PrintRectangle(rectangle); rectangle.PrintRectangle(); } // extension method // these are used very frequently with a library called LINQ public static void PrintRectangle(this Rectangle r) { Console.WriteLine($"{r.Length}x{r.Width} rectangle ({ShapeDetails(r)})"); } public static string ShapeDetails(IShape shape) { return $"area {shape.Area}, {shape.Sides}"; } } }
28.365385
85
0.505085
[ "MIT" ]
1909-sep30-net/javon-code
ShapesApp/ShapesApp.App/Program.cs
1,477
C#
using System; using System.Diagnostics; using System.Linq; using GemBox.Presentation; class Program { static void Main() { // If using Professional version, put your serial key below. ComponentInfo.SetLicense("FREE-LIMITED-KEY"); // If example exceeds Free version limitations then continue as trial version: // https://www.gemboxsoftware.com/Presentation/help/html/Evaluation_and_Licensing.htm ComponentInfo.FreeLimitReached += (sender, e) => e.FreeLimitReachedAction = FreeLimitReachedAction.ContinueAsTrial; Console.WriteLine("Performance example:"); Console.WriteLine(); var stopwatch = new Stopwatch(); stopwatch.Start(); var presentation = PresentationDocument.Load("Template.pptx", LoadOptions.Pptx); Console.WriteLine("Load file (seconds): " + stopwatch.Elapsed.TotalSeconds); stopwatch.Reset(); stopwatch.Start(); int numberOfShapes = 0; int numberOfParagraphs = 0; foreach (var slide in presentation.Slides) foreach (var shape in slide.Content.Drawings.OfType<Shape>()) { foreach (var paragraph in shape.Text.Paragraphs) ++numberOfParagraphs; ++numberOfShapes; } Console.WriteLine("Iterate through " + numberOfShapes + " shapes and " + numberOfParagraphs + " paragraphs (seconds): " + stopwatch.Elapsed.TotalSeconds); stopwatch.Reset(); stopwatch.Start(); presentation.Save("Report.pptx"); Console.WriteLine("Save file (seconds): " + stopwatch.Elapsed.TotalSeconds); } }
32.607843
162
0.648226
[ "MIT" ]
GemBox-d-o-o/GemBox.Presentation.Examples
C#/Performance/Program.cs
1,663
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.EntityFrameworkCore; using HPlusSports.Models; using System.Threading.Tasks; namespace HPlusSports.DAL.Test { [TestClass] public class TrackingRepositoryTests { [TestMethod] public async Task DeletedEntityIsMarkedAndNotRemoved() { using (var context = TestContextProvider.GetContext("DeletedEntity")) { context.Add(new Salesperson() { Id = 1, Deleted = false }); await context.SaveChangesAsync(); var repo = new TrackingRepository<Salesperson>(context); await repo.Delete(1); await repo.SaveChanges(); } using (var context = TestContextProvider.GetContext("DeletedEntity")) { var person = context.Find<Salesperson>(1); Assert.IsTrue(person.Deleted, "The person should be marked deleted"); } } } }
30.228571
86
0.582231
[ "MIT" ]
Dedac/HPlusSportsPatterns
HPlusSports.DAL.Test/TrackingRepositoryTests.cs
1,058
C#
using System; using CMS.Base.Web.UI; using CMS.Base.Web.UI.ActionsConfig; using CMS.DataEngine; using CMS.DocumentEngine; using CMS.FormEngine.Web.UI; using CMS.Helpers; using CMS.Membership; using CMS.PortalEngine.Web.UI; using CMS.SiteProvider; using CMS.UIControls; public partial class CMSModules_Content_CMSDesk_Properties_Alias_Edit : CMSPropertiesPage { #region "Private variables" private const string PROPERTIES_FOLDER = "~/CMSModules/Content/CMSDesk/Properties/"; protected int aliasId = 0; int defaultNodeID; private DocumentAliasInfo mDocumentAlias; #endregion #region "Private properties" /// <summary> /// Document alias /// </summary> private DocumentAliasInfo DocumentAlias { get { return mDocumentAlias ?? (mDocumentAlias = aliasId > 0 ? DocumentAliasInfoProvider.GetDocumentAliasInfo(aliasId) : new DocumentAliasInfo()); } } #endregion #region "Page events" protected override void OnPreInit(EventArgs e) { aliasId = QueryHelper.GetInteger("aliasid", 0); if (IsDialog) { MasterPageFile = "~/CMSMasterPages/UI/Dialogs/ModalDialogPage.master"; } // Must be called after the master page file is set base.OnPreInit(e); } protected override void OnInit(EventArgs e) { base.OnInit(e); if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerUIElement("CMS.Content", "Properties.URLs")) { RedirectToUIElementAccessDenied("CMS.Content", "Properties.URLs"); } if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerUIElement("CMS.Content", "URLs.Aliases")) { RedirectToUIElementAccessDenied("CMS.Content", "URLs.Aliases"); } ControlsHelper.FillListControlWithEnum<AliasActionModeEnum>(drpAction, "aliasaction", useStringRepresentation: true); // Disable document manager events DocumentManager.RegisterEvents = false; } protected void Page_Load(object sender, EventArgs e) { ScriptHelper.RegisterDialogScript(Page); btnOk.OnClientClick = DocumentManager.GetAllowSubmitScript(); EditedObject = DocumentAlias; if (IsDialog) { PageTitle.TitleText = GetString("content.ui.urlsaliases"); } else { HeaderActions.AddAction(new HeaderAction { Text = GetString("doc.urls.addnewalias"), RedirectUrl = ResolveUrl("Alias_Edit.aspx?nodeid=" + NodeID), ButtonStyle = ButtonStyle.Default }); HeaderActions.AddAction(new HeaderAction { Text = GetString("doc.urls.viewallalias"), OnClientClick = "modalDialog('" + ResolveUrl(PROPERTIES_FOLDER + "Alias_AliasList.aspx") + "?nodeid=" + NodeID + "&dialog=1" + "','AliasManagement','90%','85%');", ButtonStyle = ButtonStyle.Default }); } if (Node != null) { lblUrlInfoText.Text = Node.NodeAliasPath; // Check modify permissions if (!DocumentUIHelper.CheckDocumentPermissions(Node, PermissionsEnum.Modify)) { ShowInformation(String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), Node.NodeAliasPath)); txtURLExtensions.Enabled = false; ctrlURL.Enabled = false; cultureSelector.Enabled = false; } if (!RequestHelper.IsPostBack() && QueryHelper.GetInteger("saved", 0) == 1) { ShowChangesSaved(); } lblDocumentCulture.Text = GetString("general.culture") + ResHelper.Colon; lblURLExtensions.Text = GetString("doc.urls.urlextensions") + ResHelper.Colon; // Show path of document alias only if dialog mode edit pnlUrlInfo.Visible = IsDialog; // For dialog mode use DefaultNodeID defaultNodeID = (IsDialog) ? QueryHelper.GetInteger("defaultNodeID", 0) : NodeID; CreateBreadcrumbs(); cultureSelector.AllowDefault = false; cultureSelector.UniSelector.SpecialFields.Add(new SpecialField { Text = GetString("general.selectall"), Value = String.Empty }); if (!RequestHelper.IsPostBack()) { cultureSelector.Value = Node.DocumentCulture; // Edit existing alias if (DocumentAlias != null && DocumentAlias.AliasID > 0) { txtURLExtensions.Text = DocumentAlias.AliasExtensions; ctrlURL.URLPath = DocumentAlias.AliasURLPath; cultureSelector.Value = DocumentAlias.AliasCulture; PageBreadcrumbs.Items[1].Text = TreePathUtils.GetUrlPathDisplayName(DocumentAlias.AliasURLPath); drpAction.SelectedValue = DocumentAlias.AliasActionMode.ToStringRepresentation(); } } // Register js synchronization script for split mode if (QueryHelper.GetBoolean("refresh", false) && PortalUIHelper.DisplaySplitMode) { RegisterSplitModeSync(true, false, true); } } } #endregion #region "Private methods" /// <summary> /// Creates page breadcrumbs /// </summary> private void CreateBreadcrumbs() { // Initialize breadcrumbs string urls = GetString("Properties.Urls"); string urlsUrl = string.Format(PROPERTIES_FOLDER + "Alias_List.aspx?nodeid={0}&compare=1", defaultNodeID); string addAlias = GetString("doc.urls.addnewalias"); string aliasManagement = GetString("content.ui.urlsaliases"); string managementUrl = PROPERTIES_FOLDER + "Alias_AliasList.aspx?nodeid=" + defaultNodeID; PageBreadcrumbs.Items.Add(new BreadcrumbItem { Text = (IsDialog ? aliasManagement : urls), RedirectUrl = ResolveUrl(IsDialog ? managementUrl : urlsUrl) }); PageBreadcrumbs.Items.Add(new BreadcrumbItem { Text = addAlias }); } protected void btnOK_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(ctrlURL.PlainURLPath)) { ShowError(GetString("doc.urls.requiresurlpath")); return; } // Validate URL path if (!ctrlURL.IsValid()) { ShowError(ctrlURL.ValidationError); return; } if (Node != null) { // Check modify permissions if (!DocumentUIHelper.CheckDocumentPermissions(Node, PermissionsEnum.Modify)) { ShowError(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), Node.NodeAliasPath)); return; } // Check whether if (!DocumentAliasInfoProvider.IsUnique(ctrlURL.URLPath, DocumentAlias.AliasID, Convert.ToString(cultureSelector.Value), txtURLExtensions.Text.Trim(), SiteContext.CurrentSiteName, true, NodeID)) { ShowError(GetString("doc.urls.doacaliasnotunique")); return; } // Set object properties DocumentAlias.AliasURLPath = TreePathUtils.GetSafeUrlPath(ctrlURL.URLPath, Node.NodeSiteName); DocumentAlias.AliasExtensions = txtURLExtensions.Text.Trim(); DocumentAlias.AliasCulture = ValidationHelper.GetString(cultureSelector.Value, ""); DocumentAlias.AliasSiteID = Node.NodeSiteID; DocumentAlias.AliasActionMode = drpAction.SelectedValue.ToEnum<AliasActionModeEnum>(); DocumentAlias.AliasNodeID = NodeID; // Insert into database DocumentAliasInfoProvider.SetDocumentAliasInfo(DocumentAlias); // Log synchronization DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.UpdateDocument, Tree); aliasId = DocumentAlias.AliasID; string url = "Alias_Edit.aspx?saved=1&nodeid=" + NodeID + "&aliasid=" + aliasId + "&dialog=" + IsDialog; if (IsDialog) { url += "&defaultNodeID=" + defaultNodeID; } // Refresh the second frame in split mode if (PortalUIHelper.DisplaySplitMode) { url += "&refresh=1"; } URLHelper.Redirect(UrlResolver.ResolveUrl(url)); } } #endregion }
33.211111
207
0.588826
[ "MIT" ]
CMeeg/kentico-contrib
src/CMS/CMSModules/Content/CMSDesk/Properties/Alias_Edit.aspx.cs
8,969
C#
using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEngine.UIElements; namespace Logical.Editor.UIElements { public class TwoPaneSplitView : VisualElement { private static readonly string s_UssClassName = "unity-two-pane-split-view"; private static readonly string s_ContentContainerClassName = "unity-two-pane-split-view__content-container"; private static readonly string s_HandleDragLineClassName = "unity-two-pane-split-view__dragline"; private static readonly string s_HandleDragLineVerticalClassName = s_HandleDragLineClassName + "--vertical"; private static readonly string s_HandleDragLineHorizontalClassName = s_HandleDragLineClassName + "--horizontal"; private static readonly string s_HandleDragLineAnchorClassName = "unity-two-pane-split-view__dragline-anchor"; private static readonly string s_HandleDragLineAnchorVerticalClassName = s_HandleDragLineAnchorClassName + "--vertical"; private static readonly string s_HandleDragLineAnchorHorizontalClassName = s_HandleDragLineAnchorClassName + "--horizontal"; private static readonly string s_VerticalClassName = "unity-two-pane-split-view--vertical"; private static readonly string s_HorizontalClassName = "unity-two-pane-split-view--horizontal"; public enum Orientation { Horizontal, Vertical } public new class UxmlFactory : UxmlFactory<TwoPaneSplitView, UxmlTraits> { } public new class UxmlTraits : VisualElement.UxmlTraits { UxmlStringAttributeDescription m_Orientation = new UxmlStringAttributeDescription { name = "orientation", defaultValue = "horizontal" }; UxmlIntAttributeDescription m_FixedPaneIndex = new UxmlIntAttributeDescription { name = "fixed-pane-index", defaultValue = 0 }; UxmlIntAttributeDescription m_FixedPaneInitialSize = new UxmlIntAttributeDescription { name = "fixed-pane-initial-size", defaultValue = 100 }; UxmlIntAttributeDescription m_MinPaneSize = new UxmlIntAttributeDescription { name = "min-pane-size", defaultValue = 10 }; public override IEnumerable<UxmlChildElementDescription> uxmlChildElementsDescription { get { yield break; } } public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) { base.Init(ve, bag, cc); var fixedPaneIndex = m_FixedPaneIndex.GetValueFromBag(bag, cc); var fixedPaneInitialSize = m_FixedPaneInitialSize.GetValueFromBag(bag, cc); var minDimension = m_MinPaneSize.GetValueFromBag(bag, cc); var orientationStr = m_Orientation.GetValueFromBag(bag, cc); var orientation = orientationStr == "horizontal" ? Orientation.Horizontal : Orientation.Vertical; ((TwoPaneSplitView)ve).Init(fixedPaneIndex, fixedPaneInitialSize, minDimension, orientation); } } private VisualElement m_LeftPane; private VisualElement m_RightPane; private VisualElement m_FixedPane; private VisualElement m_FlexedPane; private VisualElement m_DragLine; private VisualElement m_DragLineAnchor; private VisualElement m_Content; private Orientation m_Orientation; private int m_FixedPaneIndex; private float m_FixedPaneInitialDimension; private float m_MinDimension; private SquareResizer m_Resizer; public TwoPaneSplitView() { AddToClassList(s_UssClassName); //styleSheets.Add(AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/Examples/Editor/TwoPaneSplitView/TwoPaneSplitView.uss")); styleSheets.Add(Resources.Load<StyleSheet>(ResourceAssetPaths.TwoPaneSplitView_StyleSheet)); m_Content = new VisualElement(); m_Content.name = "unity-content-container"; m_Content.AddToClassList(s_ContentContainerClassName); hierarchy.Add(m_Content); // Create drag anchor line. m_DragLineAnchor = new VisualElement(); m_DragLineAnchor.name = "unity-dragline-anchor"; m_DragLineAnchor.AddToClassList(s_HandleDragLineAnchorClassName); hierarchy.Add(m_DragLineAnchor); // Create drag m_DragLine = new VisualElement(); m_DragLine.name = "unity-dragline"; m_DragLine.AddToClassList(s_HandleDragLineClassName); m_DragLineAnchor.Add(m_DragLine); } public TwoPaneSplitView( int fixedPaneIndex, float fixedPaneStartDimension, float minDimension, Orientation orientation) : this() { Init(fixedPaneIndex, fixedPaneStartDimension, minDimension, orientation); } public void Init(int fixedPaneIndex, float fixedPaneInitialDimension, float minDimension, Orientation orientation) { m_Orientation = orientation; m_MinDimension = minDimension; m_FixedPaneIndex = fixedPaneIndex; m_FixedPaneInitialDimension = fixedPaneInitialDimension; if (m_Orientation == Orientation.Horizontal) style.minWidth = m_FixedPaneInitialDimension; else style.minHeight = m_FixedPaneInitialDimension; m_Content.RemoveFromClassList(s_HorizontalClassName); m_Content.RemoveFromClassList(s_VerticalClassName); if (m_Orientation == Orientation.Horizontal) m_Content.AddToClassList(s_HorizontalClassName); else m_Content.AddToClassList(s_VerticalClassName); // Create drag anchor line. m_DragLineAnchor.RemoveFromClassList(s_HandleDragLineAnchorHorizontalClassName); m_DragLineAnchor.RemoveFromClassList(s_HandleDragLineAnchorVerticalClassName); if (m_Orientation == Orientation.Horizontal) m_DragLineAnchor.AddToClassList(s_HandleDragLineAnchorHorizontalClassName); else m_DragLineAnchor.AddToClassList(s_HandleDragLineAnchorVerticalClassName); // Create drag m_DragLine.RemoveFromClassList(s_HandleDragLineHorizontalClassName); m_DragLine.RemoveFromClassList(s_HandleDragLineVerticalClassName); if (m_Orientation == Orientation.Horizontal) m_DragLine.AddToClassList(s_HandleDragLineHorizontalClassName); else m_DragLine.AddToClassList(s_HandleDragLineVerticalClassName); if (m_Resizer != null) { m_DragLineAnchor.RemoveManipulator(m_Resizer); m_Resizer = null; } if (m_Content.childCount != 2) RegisterCallback<GeometryChangedEvent>(OnPostDisplaySetup); else PostDisplaySetup(); } void OnPostDisplaySetup(GeometryChangedEvent evt) { if (m_Content.childCount != 2) { Debug.LogError("TwoPaneSplitView needs exactly 2 chilren."); return; } PostDisplaySetup(); UnregisterCallback<GeometryChangedEvent>(OnPostDisplaySetup); RegisterCallback<GeometryChangedEvent>(OnSizeChange); if(m_queuedSplitPosition != 0) { m_Resizer.ApplyNewPosition(m_queuedSplitPosition); m_queuedSplitPosition = 0; } } void PostDisplaySetup() { if (m_Content.childCount != 2) { Debug.LogError("TwoPaneSplitView needs exactly 2 children."); return; } m_LeftPane = m_Content[0]; if (m_FixedPaneIndex == 0) { m_FixedPane = m_LeftPane; if (m_Orientation == Orientation.Horizontal) m_LeftPane.style.width = m_FixedPaneInitialDimension; else m_LeftPane.style.height = m_FixedPaneInitialDimension; } else { m_FlexedPane = m_LeftPane; } m_RightPane = m_Content[1]; if (m_FixedPaneIndex == 1) { m_FixedPane = m_RightPane; if (m_Orientation == Orientation.Horizontal) m_RightPane.style.width = m_FixedPaneInitialDimension; else m_RightPane.style.height = m_FixedPaneInitialDimension; } else { m_FlexedPane = m_RightPane; } m_FixedPane.style.flexShrink = 0; m_FlexedPane.style.flexGrow = 1; m_FlexedPane.style.flexShrink = 0; m_FlexedPane.style.flexBasis = 0; if (m_Orientation == Orientation.Horizontal) { if (m_FixedPaneIndex == 0) m_DragLineAnchor.style.left = m_FixedPaneInitialDimension; else m_DragLineAnchor.style.left = this.resolvedStyle.width - m_FixedPaneInitialDimension; } else { if (m_FixedPaneIndex == 0) m_DragLineAnchor.style.top = m_FixedPaneInitialDimension; else m_DragLineAnchor.style.top = this.resolvedStyle.height - m_FixedPaneInitialDimension; } int direction = 1; if (m_FixedPaneIndex == 0) direction = 1; else direction = -1; if (m_FixedPaneIndex == 0) m_Resizer = new SquareResizer(this, direction, m_MinDimension, m_Orientation); else m_Resizer = new SquareResizer(this, direction, m_MinDimension, m_Orientation); m_DragLineAnchor.AddManipulator(m_Resizer); UnregisterCallback<GeometryChangedEvent>(OnPostDisplaySetup); RegisterCallback<GeometryChangedEvent>(OnSizeChange); } void OnSizeChange(GeometryChangedEvent evt) { var maxLength = this.resolvedStyle.width; var dragLinePos = m_DragLineAnchor.resolvedStyle.left; var activeElementPos = m_FixedPane.resolvedStyle.left; if (m_Orientation == Orientation.Vertical) { maxLength = this.resolvedStyle.height; dragLinePos = m_DragLineAnchor.resolvedStyle.top; activeElementPos = m_FixedPane.resolvedStyle.top; } if (m_FixedPaneIndex == 0 && dragLinePos > maxLength) { var delta = maxLength - dragLinePos; m_Resizer.ApplyDelta(delta); } else if (m_FixedPaneIndex == 1) { if (activeElementPos < 0) { var delta = -dragLinePos; m_Resizer.ApplyDelta(delta); } else { if (m_Orientation == Orientation.Horizontal) m_DragLineAnchor.style.left = activeElementPos; else m_DragLineAnchor.style.top = activeElementPos; } } } public float SplitPosition { get { return m_Resizer.Position; } } private float m_queuedSplitPosition = 0; public void SetSplitPosition(float size) { if (m_Resizer != null) { m_Resizer.ApplyNewPosition(size); } else { m_queuedSplitPosition = size; } } public override VisualElement contentContainer { get { return m_Content; } } class SquareResizer : MouseManipulator { private Vector2 m_Start; protected bool m_Active; private TwoPaneSplitView m_SplitView; private VisualElement m_Pane; private int m_Direction; private float m_MinWidth; private Orientation m_Orientation; public float Position { get; private set; } public SquareResizer(TwoPaneSplitView splitView, int dir, float minWidth, Orientation orientation) { m_Orientation = orientation; m_MinWidth = minWidth; m_SplitView = splitView; m_Pane = splitView.m_FixedPane; m_Direction = dir; activators.Add(new ManipulatorActivationFilter { button = MouseButton.LeftMouse }); m_Active = false; } protected override void RegisterCallbacksOnTarget() { target.RegisterCallback<MouseDownEvent>(OnMouseDown); target.RegisterCallback<MouseMoveEvent>(OnMouseMove); target.RegisterCallback<MouseUpEvent>(OnMouseUp); } protected override void UnregisterCallbacksFromTarget() { target.UnregisterCallback<MouseDownEvent>(OnMouseDown); target.UnregisterCallback<MouseMoveEvent>(OnMouseMove); target.UnregisterCallback<MouseUpEvent>(OnMouseUp); } public void ApplyDelta(float delta) { float oldDimension = m_Orientation == Orientation.Horizontal ? m_Pane.resolvedStyle.width : m_Pane.resolvedStyle.height; float newDimension = oldDimension + delta; if (newDimension < oldDimension && newDimension < m_MinWidth) newDimension = m_MinWidth; float maxLength = m_Orientation == Orientation.Horizontal ? m_SplitView.resolvedStyle.width : m_SplitView.resolvedStyle.height; if (newDimension > oldDimension && newDimension > maxLength) newDimension = maxLength; ApplyNewPosition(newDimension); } public void ApplyNewPosition(float position) { if (m_Orientation == Orientation.Horizontal) { m_Pane.style.width = position; if (m_SplitView.m_FixedPaneIndex == 0) target.style.left = position; else target.style.left = m_SplitView.resolvedStyle.width - position; } else { m_Pane.style.height = position; if (m_SplitView.m_FixedPaneIndex == 0) target.style.top = position; else target.style.top = m_SplitView.resolvedStyle.height - position; } Position = position; } protected void OnMouseDown(MouseDownEvent e) { if (m_Active) { e.StopImmediatePropagation(); return; } if (CanStartManipulation(e)) { m_Start = e.localMousePosition; m_Active = true; target.CaptureMouse(); e.StopPropagation(); } } protected void OnMouseMove(MouseMoveEvent e) { if (!m_Active || !target.HasMouseCapture()) return; Vector2 diff = e.localMousePosition - m_Start; float mouseDiff = diff.x; if (m_Orientation == Orientation.Vertical) mouseDiff = diff.y; float delta = m_Direction * mouseDiff; ApplyDelta(delta); e.StopPropagation(); } protected void OnMouseUp(MouseUpEvent e) { if (!m_Active || !target.HasMouseCapture() || !CanStopManipulation(e)) return; m_Active = false; target.ReleaseMouse(); e.StopPropagation(); } } } }
39.035545
154
0.582225
[ "MIT" ]
GeoBT/Logical-Behavior-Trees
Assets/Logical/Editor/UIElements/TwoPaneSplitView.cs
16,475
C#
using System; using System.Drawing; using System.Windows.Forms; using FlashDebugger.Controls; using PluginCore.Localization; using WeifenLuo.WinFormsUI.Docking; using PluginCore; namespace FlashDebugger { internal class PanelsHelper { static public String pluginGuid = "f9d8faf1-31f7-45ca-9c14-2cad27d7a19e"; static public DockContent pluginPanel; static public PluginUI pluginUI; static public String breakPointGuid = "6ee0f809-a3f7-4365-96c7-3bdf89f3aaa4"; static public DockContent breakPointPanel; static public BreakPointUI breakPointUI; static public String stackframeGuid = "49eb0b7e-f601-4860-a190-ae48e122a661"; static public DockContent stackframePanel; static public StackframeUI stackframeUI; static public String watchGuid = "c4a0c90a-236c-4a41-8ece-85486a23960f"; static public DockContent watchPanel; static public WatchUI watchUI; static public String immediateGuid = "7ce31ab1-5a40-42d5-ad32-5df567707afc"; static public DockContent immediatePanel; static public ImmediateUI immediateUI; static public String threadsGuid = "49eb0b7e-f601-4860-a190-ae48e122a662"; static public DockContent threadsPanel; static public ThreadsUI threadsUI; public PanelsHelper(PluginMain pluginMain, Image pluginImage) { pluginUI = new PluginUI(pluginMain); pluginUI.Text = TextHelper.GetString("Title.LocalVariables"); pluginPanel = PluginBase.MainForm.CreateDockablePanel(pluginUI, pluginGuid, pluginImage, DockState.DockLeft); pluginPanel.Hide(); stackframeUI = new StackframeUI(pluginMain, MenusHelper.imageList); stackframeUI.Text = TextHelper.GetString("Title.StackTrace"); stackframePanel = PluginBase.MainForm.CreateDockablePanel(stackframeUI, stackframeGuid, pluginImage, DockState.DockLeft); stackframePanel.Hide(); watchUI = new WatchUI(); watchUI.Text = TextHelper.GetString("Title.Watch"); watchPanel = PluginBase.MainForm.CreateDockablePanel(watchUI, watchGuid, pluginImage, DockState.DockLeft); watchPanel.Hide(); breakPointUI = new BreakPointUI(pluginMain, PluginMain.breakPointManager); breakPointUI.Text = TextHelper.GetString("Title.Breakpoints"); breakPointPanel = PluginBase.MainForm.CreateDockablePanel(breakPointUI, breakPointGuid, pluginImage, DockState.DockLeft); breakPointPanel.Hide(); immediateUI = new ImmediateUI(); immediateUI.Text = TextHelper.GetString("Title.Immediate"); immediatePanel = PluginBase.MainForm.CreateDockablePanel(immediateUI, immediateGuid, pluginImage, DockState.DockLeft); immediatePanel.Hide(); threadsUI = new ThreadsUI(pluginMain, MenusHelper.imageList); threadsUI.Text = TextHelper.GetString("Title.Threads"); threadsPanel = PluginBase.MainForm.CreateDockablePanel(threadsUI, threadsGuid, pluginImage, DockState.DockLeft); threadsPanel.Hide(); } } }
42.219178
133
0.730694
[ "MIT" ]
SlavaRa/flashdevelop-macros
External/Plugins/FlashDebugger/Helpers/PanelsHelper.cs
3,084
C#
using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using AElf.Kernel; using AElf.OS.Network.Grpc; using AElf.OS.Network.Infrastructure; using Google.Protobuf; using Shouldly; using Xunit; namespace AElf.OS.Network { public class PeerConnectionServiceTests : ServerServiceTestBase { private readonly IConnectionService _connectionService; private readonly IPeerPool _peerPool; public PeerConnectionServiceTests() { _connectionService = GetRequiredService<IConnectionService>(); _peerPool = GetRequiredService<IPeerPool>(); } [Fact] public async Task DoHandshake_MaxPeersPerHostReached_Test() { var peerEndpoint = new DnsEndPoint("1.2.3.4", 1234); var firstPeerFromHostResp = await _connectionService.DoHandshakeAsync(peerEndpoint, GetHandshake("pubKey1")); firstPeerFromHostResp.Error.ShouldBe(HandshakeError.HandshakeOk); var secondPeerFromHostResp = await _connectionService.DoHandshakeAsync(peerEndpoint, GetHandshake("pubKey2")); secondPeerFromHostResp.Error.ShouldBe(HandshakeError.ConnectionRefused); _peerPool.GetPeers(true).Count.ShouldBe(1); _peerPool.GetHandshakingPeers().Values.Count.ShouldBe(0); } [Fact] public async Task DoHandshake_LocalhostMaxHostIgnored_Test() { var grpcUriLocal = new DnsEndPoint(IPAddress.Loopback.ToString(), 1234); var grpcUriLocalhostIp = new DnsEndPoint("127.0.0.1", 1234); var firstLocalPeerResp = await _connectionService.DoHandshakeAsync(grpcUriLocal, GetHandshake("pubKey1")); firstLocalPeerResp.Error.ShouldBe(HandshakeError.HandshakeOk); var secondLocalPeerResp = await _connectionService.DoHandshakeAsync(grpcUriLocal, GetHandshake("pubKey2")); secondLocalPeerResp.Error.ShouldBe(HandshakeError.HandshakeOk); var thirdPeerFromHostResp = await _connectionService.DoHandshakeAsync(grpcUriLocalhostIp, GetHandshake("pubKey3")); thirdPeerFromHostResp.Error.ShouldBe(HandshakeError.HandshakeOk); _peerPool.GetPeers(true).Count.ShouldBe(3); _peerPool.GetHandshakingPeers().Values.Count.ShouldBe(0); } private Handshake GetHandshake(string pubKey = "mockPubKey") { return new Handshake { HandshakeData = new HandshakeData { Pubkey = ByteString.CopyFromUtf8(pubKey)}}; } } }
42.31746
128
0.670668
[ "MIT" ]
380086154/AElf
test/AElf.OS.Network.Grpc.Tests/PeerConnectionServiceTests.cs
2,666
C#
using System; using Axis.Pollux.Common.Models; using Axis.Pollux.Identity.Models; namespace Axis.Pollux.Authentication.Models { public class MultiFactorCredential: BaseModel<Guid> { public User TargetUser { get; set; } public string CredentialKey { get; set; } public string CredentialToken { get; set; } public DateTimeOffset ExpiresOn { get; set; } public bool IsAuthenticated { get; set; } /// <summary> /// A string representing the entity - usually a contract operation call, that the multi-factor authentication is being employed to guard" /// </summary> public string EventLabel { get; set; } } }
32.904762
146
0.665702
[ "MIT" ]
d-dantte/Axis.Pollox
Axis.Pollux.Authentication/Models/MultiFactorCredential.cs
693
C#
using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Reveche { class RevitFile : INotifyPropertyChanged { private static Regex EndYear = new Regex(@"_20\d{2}$"); private static Regex StartYear = new Regex(@"^20\d{2}_"); public RevitFile() { } public RevitFile(string file) { Filename = Path.GetFileNameWithoutExtension(file); Extension = Path.GetExtension(file); Directory = Path.GetDirectoryName(file); } public string Filename { get; set; } private string _newFilename; public string NewFilename { set { _newFilename = value; OnPropertyChanged("NewFilename"); } get { return _newFilename; } } public string Extension { get; set; } public string Directory { get; set; } public string Version { get; set; } public string AdditionalInfo { get; set; } public string FullPath { get { return Path.Combine(Directory, Filename + Extension); } } public string NewFullPath { get { return Path.Combine(Directory, NewFilename + Extension); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public void RefreshName(Action action) { //by defaul remove any appended and prepended YEAR _newFilename = EndYear.Replace(Filename, ""); _newFilename = StartYear.Replace(_newFilename, ""); if (action == Action.Append) _newFilename = _newFilename + "_" + Version; else if (action == Action.Prepend) _newFilename = Version + "_" + _newFilename; OnPropertyChanged("NewFilename"); } #endregion } }
26.695652
87
0.54886
[ "MIT" ]
chuongmep/Reveche
Reveche/RevitFile.cs
2,458
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class StartSceneCanvas : MonoBehaviour { public void LoadingNextLevel(string nextLevelName)//加载loading场景 { SceneManager.LoadScene(nextLevelName); } /// <summary> /// 关闭窗口 /// </summary> /// <param name="closeGameObject">窗口</param> public void Close(GameObject closeGameObject) { closeGameObject.SetActive(false); } /// <summary> /// 开启窗口 /// </summary> /// <param name="closeGameObject">窗口</param> public void Open(GameObject openGameObject) { openGameObject.SetActive(true); } /// <summary> /// 退出游戏 /// </summary> public void QuitAllGame() { Application.Quit(); } }
21
67
0.627595
[ "MIT" ]
05Robot/05_Robot
Assets/Script/Mono/UI/StartSceneCanvas.cs
861
C#
using System.ComponentModel.DataAnnotations; namespace AdventureWorks.BaseDomain.Interfaces { public interface ICaching { [Timestamp] byte[] RowVersion { get; set; } byte?[] CashedRowVersion { get; set; } } }
20.5
46
0.654472
[ "Unlicense" ]
CodeSwifterGit/adventure-works
src/AdventureWorks.BaseDomain/Interfaces/ICaching.cs
246
C#
// *********************************************************************** // <copyright file="RequestExtensions.cs" company="ServiceStack, Inc."> // Copyright (c) ServiceStack, Inc. All Rights Reserved. // </copyright> // <summary>Fork for YetAnotherForum.NET, Licensed under the Apache License, Version 2.0</summary> // *********************************************************************** using System; using System.Collections.Generic; using System.Collections.Specialized; using ServiceStack.Text; using ServiceStack.Web; namespace ServiceStack { /// <summary> /// Class RequestExtensions. /// </summary> public static class RequestExtensions { /// <summary> /// Duplicate Params are given a unique key by appending a #1 suffix /// </summary> /// <param name="request">The request.</param> /// <returns>Dictionary&lt;System.String, System.String&gt;.</returns> /// <exception cref="System.ArgumentNullException">request</exception> public static Dictionary<string, string> GetRequestParams(this IRequest request) { if (request == null) throw new ArgumentNullException(nameof(request)); var map = new Dictionary<string, string>(); AddToMap(request.QueryString, map); if ((request.Verb == HttpMethods.Post || request.Verb == HttpMethods.Put) && request.FormData != null) { AddToMap(request.FormData, map); } return map; } /// <summary> /// Adds to map. /// </summary> /// <param name="nvc">The NVC.</param> /// <param name="map">The map.</param> private static void AddToMap(NameValueCollection nvc, IDictionary<string, string> map) { for (int index = 0; index < nvc.Count; index++) { var name = nvc.GetKey(index); var values = nvc.GetValues(name); // Only use string name instead of index which returns multiple values if (name == null) //thank you .NET Framework! { if (values?.Length > 0) map[values[0]] = null; continue; } if (values == null || values.Length == 0) { map[name] = null; } else if (values.Length == 1) { map[name] = values[0]; } else { for (var i = 0; i < values.Length; i++) { map[name + (i == 0 ? "" : "#" + i)] = values[i]; } } } } } }
35.9625
121
0.46472
[ "Apache-2.0" ]
Spinks90/YAFNET
yafsrc/ServiceStack/ServiceStack/Common/RequestExtensions.cs
2,800
C#
using System ; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace SpeedCubeSolver { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
27.444444
70
0.608637
[ "MIT" ]
MichaelKappel/SpeedCube
RC/SpeedCubeSolver/Program.cs
741
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class TaskReport : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Menu Menu1 = (Menu)Master.FindControl("Menu1"); Menu1.Items[3].Selected = true; } protected void GridViewForms_RowCommand(object sender, GridViewCommandEventArgs e) { var procedure = "[INBOUND].[dbo].[reportForm]"; if (e.CommandName != "") procedure = e.CommandName; Response.Redirect("~/reports/Report.aspx?Procedure="+procedure+"&IdAllString=1&report=form_IdForm_" + e.CommandArgument); } }
31.869565
133
0.675307
[ "Apache-2.0" ]
nsadovin/Wilstream
Questinary/TaskReport.aspx.cs
735
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Text; using Silk.NET.Core; using Silk.NET.Core.Native; using Silk.NET.Core.Attributes; using Silk.NET.Core.Contexts; using Silk.NET.Core.Loader; #pragma warning disable 1591 namespace Silk.NET.Vulkan { [NativeName("Name", "VkPipelineDiscardRectangleStateCreateInfoEXT")] public unsafe partial struct PipelineDiscardRectangleStateCreateInfoEXT { public PipelineDiscardRectangleStateCreateInfoEXT ( StructureType? sType = StructureType.PipelineDiscardRectangleStateCreateInfoExt, void* pNext = null, uint? flags = null, DiscardRectangleModeEXT? discardRectangleMode = null, uint? discardRectangleCount = null, Rect2D* pDiscardRectangles = null ) : this() { if (sType is not null) { SType = sType.Value; } if (pNext is not null) { PNext = pNext; } if (flags is not null) { Flags = flags.Value; } if (discardRectangleMode is not null) { DiscardRectangleMode = discardRectangleMode.Value; } if (discardRectangleCount is not null) { DiscardRectangleCount = discardRectangleCount.Value; } if (pDiscardRectangles is not null) { PDiscardRectangles = pDiscardRectangles; } } /// <summary></summary> [NativeName("Type", "VkStructureType")] [NativeName("Type.Name", "VkStructureType")] [NativeName("Name", "sType")] public StructureType SType; /// <summary></summary> [NativeName("Type", "void*")] [NativeName("Type.Name", "void")] [NativeName("Name", "pNext")] public void* PNext; /// <summary></summary> [NativeName("Type", "VkPipelineDiscardRectangleStateCreateFlagsEXT")] [NativeName("Type.Name", "VkPipelineDiscardRectangleStateCreateFlagsEXT")] [NativeName("Name", "flags")] public uint Flags; /// <summary></summary> [NativeName("Type", "VkDiscardRectangleModeEXT")] [NativeName("Type.Name", "VkDiscardRectangleModeEXT")] [NativeName("Name", "discardRectangleMode")] public DiscardRectangleModeEXT DiscardRectangleMode; /// <summary></summary> [NativeName("Type", "uint32_t")] [NativeName("Type.Name", "uint32_t")] [NativeName("Name", "discardRectangleCount")] public uint DiscardRectangleCount; /// <summary></summary> [NativeName("Type", "VkRect2D*")] [NativeName("Type.Name", "VkRect2D")] [NativeName("Name", "pDiscardRectangles")] public Rect2D* PDiscardRectangles; } }
32.126316
92
0.60616
[ "MIT" ]
DmitryGolubenkov/Silk.NET
src/Vulkan/Silk.NET.Vulkan/Structs/PipelineDiscardRectangleStateCreateInfoEXT.gen.cs
3,052
C#
// *** WARNING: this file was generated by crd2pulumi. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Kubernetes.Types.Inputs.Elasticsearch.V1 { /// <summary> /// RoleSource references roles to create in the Elasticsearch cluster. /// </summary> public class ElasticsearchSpecAuthRolesArgs : Pulumi.ResourceArgs { /// <summary> /// SecretName is the name of the secret. /// </summary> [Input("secretName")] public Input<string>? SecretName { get; set; } public ElasticsearchSpecAuthRolesArgs() { } } }
27.310345
81
0.661616
[ "Apache-2.0" ]
pulumi/pulumi-kubernetes-crds
operators/elastic-cloud-eck/dotnet/Kubernetes/Crds/Operators/ElasticCloudEck/Elasticsearch/V1/Inputs/ElasticsearchSpecAuthRolesArgs.cs
792
C#
namespace Sanderling { public enum ShipManeuverTypeEnum { None = 0, Stop = 9, Approach = 10, Orbit = 11, KeepAtRange = 12, Dock = 17, Docked = 18, Undock = 19, Warp = 30, Jump = 31, } public enum ShipCargoSpaceTypeEnum { None = 0, General = 1, DroneBay = 3, OreHold = 7, } public enum OreTypeEnum { None = 0, Arkonor = 100, Bistot = 110, Crokite = 120, Dark_Ochre = 130, Gneiss = 140, Hedbergite = 150, Hemorphite = 160, Jaspet = 170, Kernite = 180, Mercoxit = 190, Omber = 200, Plagioclase = 210, Pyroxeres = 220, Scordite = 230, Spodumain = 240, Veldspar = 250, } }
13.680851
35
0.600311
[ "Apache-2.0" ]
SDManson/Sanderling
src/Sanderling/Sanderling/GameWorldStatic.cs
645
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 #region Usings using System; using System.Data; using System.Globalization; using DotNetNuke.Entities.Users; #endregion namespace DotNetNuke.Services.Tokens { public class DataRowPropertyAccess : IPropertyAccess { private readonly DataRow dr; public DataRowPropertyAccess(DataRow row) { this.dr = row; } #region IPropertyAccess Members public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) { if (this.dr == null) { return string.Empty; } object valueObject = this.dr[propertyName]; string OutputFormat = format; if (string.IsNullOrEmpty(format)) { OutputFormat = "g"; } if (valueObject != null) { switch (valueObject.GetType().Name) { case "String": return PropertyAccess.FormatString(Convert.ToString(valueObject), format); case "Boolean": return (PropertyAccess.Boolean2LocalizedYesNo(Convert.ToBoolean(valueObject), formatProvider)); case "DateTime": case "Double": case "Single": case "Int32": case "Int64": return (((IFormattable) valueObject).ToString(OutputFormat, formatProvider)); default: return PropertyAccess.FormatString(valueObject.ToString(), format); } } else { PropertyNotFound = true; return string.Empty; } } public CacheLevel Cacheability { get { return CacheLevel.notCacheable; } } #endregion } }
29.592105
167
0.532681
[ "MIT" ]
MaiklT/Dnn.Platform
DNN Platform/Library/Services/Tokens/PropertyAccess/DataRowPropertyAccess.cs
2,251
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the connect-2017-08-08.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Connect.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Connect.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for LimitExceededException Object /// </summary> public class LimitExceededExceptionUnmarshaller : IErrorResponseUnmarshaller<LimitExceededException, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public LimitExceededException Unmarshall(JsonUnmarshallerContext context) { return this.Unmarshall(context, new Amazon.Runtime.Internal.ErrorResponse()); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <param name="errorResponse"></param> /// <returns></returns> public LimitExceededException Unmarshall(JsonUnmarshallerContext context, Amazon.Runtime.Internal.ErrorResponse errorResponse) { context.Read(); LimitExceededException unmarshalledObject = new LimitExceededException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { } return unmarshalledObject; } private static LimitExceededExceptionUnmarshaller _instance = new LimitExceededExceptionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static LimitExceededExceptionUnmarshaller Instance { get { return _instance; } } } }
35.105882
135
0.671247
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/Connect/Generated/Model/Internal/MarshallTransformations/LimitExceededExceptionUnmarshaller.cs
2,984
C#
using kSlovnik.Windows; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; namespace kSlovnik.Controls { public static class Prompt { public static string SelectedGamePath { get; private set; } public static bool ChooseGame() { SelectedGamePath = null; var promptWidth = (int)(Program.MainView.ClientSize.Width / 1.5); var promptHeight = (int)(Program.MainView.ClientSize.Height / 2); var aspectRatio = (double)Program.MainView.ClientSize.Width / Program.MainView.ClientSize.Height; Form prompt = new Form() { Text = "Зареждане на запазена игра", Width = promptWidth, Height = promptHeight, MinimizeBox = false, MaximizeBox = false, FormBorderStyle = FormBorderStyle.FixedDialog, StartPosition = FormStartPosition.CenterParent }; var gamePreviewPanel = new Panel() { Left = Constants.Padding.Left / 2, Top = Constants.Padding.Top / 2, Height = prompt.ClientSize.Height - Constants.Padding.Vertical / 2 }; gamePreviewPanel.Width = (int)(gamePreviewPanel.Height * aspectRatio); prompt.Controls.Add(gamePreviewPanel); var placeHolderLabel = new Label() { Name = "PlaceholderLabel", Width = gamePreviewPanel.Width, Height = gamePreviewPanel.Height, Text = "Не сте избрали игра.", TextAlign = ContentAlignment.MiddleCenter }; gamePreviewPanel.Controls.Add(placeHolderLabel); var imagePreview = new PictureBox() { Name = "ImagePreview", Width = gamePreviewPanel.Width, Height = gamePreviewPanel.Height, SizeMode = PictureBoxSizeMode.StretchImage }; gamePreviewPanel.Controls.Add(imagePreview); var gameList = new ListView() { Left = gamePreviewPanel.Right + Constants.Padding.Left / 2, Top = Constants.Padding.Top / 2, Height = (int)((prompt.ClientSize.Height - Constants.Padding.Vertical / 2) * 0.82), View = View.List, MultiSelect = false, ShowItemToolTips = true }; gameList.Width = prompt.ClientSize.Width - gamePreviewPanel.Right - Constants.Padding.Horizontal / 2; prompt.Controls.Add(gameList); Panel buttonPanel = new Panel() { Left = gameList.Left, Top = gameList.Bottom, Width = gameList.Width, Height = (int)((prompt.ClientSize.Height - Constants.Padding.Vertical / 2) * 0.18), }; prompt.Controls.Add(buttonPanel); Button confirmButton = new Button() { Name = "ConfirmButton", Left = 0, Top = Constants.Padding.Top / 2, Width = (buttonPanel.Width - Constants.Padding.Left / 2) / 2, Height = buttonPanel.Height - Constants.Padding.Vertical / 2, Text = "ОК", DialogResult = DialogResult.OK }; buttonPanel.Controls.Add(confirmButton); Button cancelButton = new Button() { Name = "CancelButton", Left = confirmButton.Right + Constants.Padding.Left / 2, Top = confirmButton.Top, Width = confirmButton.Width, Height = confirmButton.Height, Text = "Отказ", DialogResult = DialogResult.Cancel }; buttonPanel.Controls.Add(cancelButton); if (Directory.Exists(Constants.SavesFolder)) { // Get all saves var saveFilePaths = Directory.GetFiles(Constants.SavesFolder).Where(p => Path.GetFileName(p).EndsWith(".save")).ToList(); gameList.LargeImageList = new ImageList(); gameList.LargeImageList.ImageSize = new Size(Math.Min(gameList.Size.Width, 256), Math.Min(gameList.Size.Height, 256)); foreach (var saveFilePath in saveFilePaths) { var fileName = Path.GetFileName(saveFilePath); gameList.LargeImageList.Images.Add(key: saveFilePath, image: Game.Game.LoadSaveFileThumbnail(saveFilePath)); var item = new ListViewItem(text: Path.GetFileNameWithoutExtension(saveFilePath), imageKey: saveFilePath); item.ToolTipText = item.Text; gameList.Items.Add(item); } gameList.SelectedIndexChanged += GameList_SelectedIndexChanged; gameList.DoubleClick += GameList_DoubleClick; if (gameList.Items.Count > 0) { gameList.Items[0].Selected = true; gameList.Select(); } } var response = prompt.ShowDialog(); if (response == DialogResult.OK && gameList.SelectedItems.Count > 0) { SelectedGamePath = gameList.SelectedItems[0].ImageKey; return true; } return false; } private static void GameList_DoubleClick(object sender, EventArgs e) { var prompt = sender; if (prompt is Control control) { while (prompt is Form == false) { prompt = control.Parent; } } if (prompt is Form form) { SelectedGamePath = (sender as ListView).SelectedItems[0].ImageKey; var confirmButton = form.Controls.Find("ConfirmButton", true).FirstOrDefault(); if (confirmButton is Button button) { button.PerformClick(); } } } private static void GameList_SelectedIndexChanged(object sender, EventArgs e) { if(sender is ListView gameList && gameList.Parent is Form prompt) { var placeholderLabel = prompt.Controls.Find("PlaceholderLabel", true).FirstOrDefault(); var imagePreviewList = prompt.Controls.Find("ImagePreview", true).Select(c => c as PictureBox).Where(c => c != null).ToList(); if(imagePreviewList != null && imagePreviewList.Count > 0) { if (gameList.SelectedItems.Count > 0) { imagePreviewList[0].Image = gameList.LargeImageList.Images[gameList.SelectedItems[0].ImageKey]; imagePreviewList[0].Visible = true; if (placeholderLabel != null) placeholderLabel.Visible = false; } else { imagePreviewList[0].Image = null; imagePreviewList[0].Visible = false; if (placeholderLabel != null) placeholderLabel.Visible = true; } } } } public static bool ChooseLetter(out char letter) { var promptWidth = Program.MainView.ClientSize.Width / 8; var promptHeight = Program.MainView.ClientSize.Height / 8; Form prompt = new Form() { MaximizeBox = false, FormBorderStyle = FormBorderStyle.FixedDialog, //Text = Constants.Texts.ChooseLetterPromptTitle, StartPosition = FormStartPosition.CenterParent }; int currentStartingY = Constants.Padding.Top / 2; Label textLabel = new Label() { Left = Constants.Padding.Left / 2, Top = currentStartingY, Width = (int)(promptWidth * 0.8), Height = (int)(promptHeight * 0.2), Text = Constants.Texts.ChooseLetterPromptText }; textLabel.Left = Constants.Padding.Left / 2 + ((promptWidth - textLabel.Width) / 2); currentStartingY += textLabel.Height + Constants.SidebarSeparatorHeight / 2; TextBox textBox = new TextBox() { Top = currentStartingY, Width = (int)(promptWidth * 0.8), Height = (int)(promptHeight * 0.3), MaxLength = 1 }; textBox.Font = new Font(Constants.Fonts.Default.FontFamily, Constants.Fonts.Default.Size * 2, FontStyle.Bold); textBox.Left = Constants.Padding.Left / 2 + ((promptWidth - textBox.Width) / 2); currentStartingY += textBox.Height + Constants.SidebarSeparatorHeight; Button confirmButton = new Button() { Left = Constants.Padding.Left / 2, Top = currentStartingY, Width = (int)(promptWidth * 0.4), Height = (int)(promptHeight * 0.3), Text = "ОК", DialogResult = DialogResult.OK }; confirmButton.Left = Constants.Padding.Left / 2 + ((promptWidth - confirmButton.Width) / 2); confirmButton.Click += (sender, e) => prompt.Close(); currentStartingY += confirmButton.Height; prompt.ClientSize = new Size(promptWidth + Constants.Padding.Horizontal / 2, currentStartingY + Constants.Padding.Bottom / 2); prompt.Controls.Add(textBox); prompt.Controls.Add(confirmButton); prompt.Controls.Add(textLabel); prompt.AcceptButton = confirmButton; var response = prompt.ShowDialog(); if (response == DialogResult.OK && !string.IsNullOrEmpty(textBox.Text)) { letter = textBox.Text.ToLowerInvariant()[0]; // Check if letter is valid if (Constants.DeckInfo.PieceColors.ContainsKey(letter)) return true; } letter = '~'; return false; } } }
40.498069
142
0.533511
[ "BSD-3-Clause" ]
martin-chulev/kSlovnik
kSlovnik/Controls/Prompt.cs
10,539
C#