content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace HarmonyCore.CliTool.Commands { class RegenCommand { SolutionInfo _solutionInfo; public RegenCommand(SolutionInfo solutionInfo) { _solutionInfo = solutionInfo; } public int Run(RegenOptions opts) { var result = _solutionInfo.CodeGenSolution.GenerateSolution((tsk, message) => Console.WriteLine("{0} : {1}", string.Join(',', tsk.Templates), message), CancellationToken.None); foreach (var error in result.ValidationErrors) { Console.WriteLine(error); } return 0; } } }
25.137931
188
0.610425
[ "BSD-2-Clause" ]
danellis06460/HarmonyCore
HarmonyCore.CliTool/Commands/RegenCommand.cs
731
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the appstream-2016-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.AppStream.Model { /// <summary> /// Describes a fleet. /// </summary> public partial class Fleet { private string _arn; private ComputeCapacityStatus _computeCapacityStatus; private DateTime? _createdTime; private string _description; private int? _disconnectTimeoutInSeconds; private string _displayName; private DomainJoinInfo _domainJoinInfo; private bool? _enableDefaultInternetAccess; private List<FleetError> _fleetErrors = new List<FleetError>(); private FleetType _fleetType; private string _iamRoleArn; private int? _idleDisconnectTimeoutInSeconds; private string _imageArn; private string _imageName; private string _instanceType; private int? _maxUserDurationInSeconds; private string _name; private FleetState _state; private StreamView _streamView; private VpcConfig _vpcConfig; /// <summary> /// Gets and sets the property Arn. /// <para> /// The Amazon Resource Name (ARN) for the fleet. /// </para> /// </summary> [AWSProperty(Required=true)] public string Arn { get { return this._arn; } set { this._arn = value; } } // Check to see if Arn property is set internal bool IsSetArn() { return this._arn != null; } /// <summary> /// Gets and sets the property ComputeCapacityStatus. /// <para> /// The capacity status for the fleet. /// </para> /// </summary> [AWSProperty(Required=true)] public ComputeCapacityStatus ComputeCapacityStatus { get { return this._computeCapacityStatus; } set { this._computeCapacityStatus = value; } } // Check to see if ComputeCapacityStatus property is set internal bool IsSetComputeCapacityStatus() { return this._computeCapacityStatus != null; } /// <summary> /// Gets and sets the property CreatedTime. /// <para> /// The time the fleet was created. /// </para> /// </summary> public DateTime CreatedTime { get { return this._createdTime.GetValueOrDefault(); } set { this._createdTime = value; } } // Check to see if CreatedTime property is set internal bool IsSetCreatedTime() { return this._createdTime.HasValue; } /// <summary> /// Gets and sets the property Description. /// <para> /// The description to display. /// </para> /// </summary> [AWSProperty(Min=1)] public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property DisconnectTimeoutInSeconds. /// <para> /// The amount of time that a streaming session remains active after users disconnect. /// If they try to reconnect to the streaming session after a disconnection or network /// interruption within this time interval, they are connected to their previous session. /// Otherwise, they are connected to a new session with a new streaming instance. /// </para> /// /// <para> /// Specify a value between 60 and 360000. /// </para> /// </summary> public int DisconnectTimeoutInSeconds { get { return this._disconnectTimeoutInSeconds.GetValueOrDefault(); } set { this._disconnectTimeoutInSeconds = value; } } // Check to see if DisconnectTimeoutInSeconds property is set internal bool IsSetDisconnectTimeoutInSeconds() { return this._disconnectTimeoutInSeconds.HasValue; } /// <summary> /// Gets and sets the property DisplayName. /// <para> /// The fleet name to display. /// </para> /// </summary> [AWSProperty(Min=1)] public string DisplayName { get { return this._displayName; } set { this._displayName = value; } } // Check to see if DisplayName property is set internal bool IsSetDisplayName() { return this._displayName != null; } /// <summary> /// Gets and sets the property DomainJoinInfo. /// <para> /// The name of the directory and organizational unit (OU) to use to join the fleet to /// a Microsoft Active Directory domain. /// </para> /// </summary> public DomainJoinInfo DomainJoinInfo { get { return this._domainJoinInfo; } set { this._domainJoinInfo = value; } } // Check to see if DomainJoinInfo property is set internal bool IsSetDomainJoinInfo() { return this._domainJoinInfo != null; } /// <summary> /// Gets and sets the property EnableDefaultInternetAccess. /// <para> /// Indicates whether default internet access is enabled for the fleet. /// </para> /// </summary> public bool EnableDefaultInternetAccess { get { return this._enableDefaultInternetAccess.GetValueOrDefault(); } set { this._enableDefaultInternetAccess = value; } } // Check to see if EnableDefaultInternetAccess property is set internal bool IsSetEnableDefaultInternetAccess() { return this._enableDefaultInternetAccess.HasValue; } /// <summary> /// Gets and sets the property FleetErrors. /// <para> /// The fleet errors. /// </para> /// </summary> public List<FleetError> FleetErrors { get { return this._fleetErrors; } set { this._fleetErrors = value; } } // Check to see if FleetErrors property is set internal bool IsSetFleetErrors() { return this._fleetErrors != null && this._fleetErrors.Count > 0; } /// <summary> /// Gets and sets the property FleetType. /// <para> /// The fleet type. /// </para> /// <dl> <dt>ALWAYS_ON</dt> <dd> /// <para> /// Provides users with instant-on access to their apps. You are charged for all running /// instances in your fleet, even if no users are streaming apps. /// </para> /// </dd> <dt>ON_DEMAND</dt> <dd> /// <para> /// Provide users with access to applications after they connect, which takes one to two /// minutes. You are charged for instance streaming when users are connected and a small /// hourly fee for instances that are not streaming apps. /// </para> /// </dd> </dl> /// </summary> public FleetType FleetType { get { return this._fleetType; } set { this._fleetType = value; } } // Check to see if FleetType property is set internal bool IsSetFleetType() { return this._fleetType != null; } /// <summary> /// Gets and sets the property IamRoleArn. /// <para> /// The ARN of the IAM role that is applied to the fleet. To assume a role, the fleet /// instance calls the AWS Security Token Service (STS) <code>AssumeRole</code> API operation /// and passes the ARN of the role to use. The operation creates a new session with temporary /// credentials. AppStream 2.0 retrieves the temporary credentials and creates the <b>appstream_machine_role</b> /// credential profile on the instance. /// </para> /// /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/appstream2/latest/developerguide/using-iam-roles-to-grant-permissions-to-applications-scripts-streaming-instances.html">Using /// an IAM Role to Grant Permissions to Applications and Scripts Running on AppStream /// 2.0 Streaming Instances</a> in the <i>Amazon AppStream 2.0 Administration Guide</i>. /// </para> /// </summary> public string IamRoleArn { get { return this._iamRoleArn; } set { this._iamRoleArn = value; } } // Check to see if IamRoleArn property is set internal bool IsSetIamRoleArn() { return this._iamRoleArn != null; } /// <summary> /// Gets and sets the property IdleDisconnectTimeoutInSeconds. /// <para> /// The amount of time that users can be idle (inactive) before they are disconnected /// from their streaming session and the <code>DisconnectTimeoutInSeconds</code> time /// interval begins. Users are notified before they are disconnected due to inactivity. /// If users try to reconnect to the streaming session before the time interval specified /// in <code>DisconnectTimeoutInSeconds</code> elapses, they are connected to their previous /// session. Users are considered idle when they stop providing keyboard or mouse input /// during their streaming session. File uploads and downloads, audio in, audio out, and /// pixels changing do not qualify as user activity. If users continue to be idle after /// the time interval in <code>IdleDisconnectTimeoutInSeconds</code> elapses, they are /// disconnected. /// </para> /// /// <para> /// To prevent users from being disconnected due to inactivity, specify a value of 0. /// Otherwise, specify a value between 60 and 3600. The default value is 0. /// </para> /// <note> /// <para> /// If you enable this feature, we recommend that you specify a value that corresponds /// exactly to a whole number of minutes (for example, 60, 120, and 180). If you don't /// do this, the value is rounded to the nearest minute. For example, if you specify a /// value of 70, users are disconnected after 1 minute of inactivity. If you specify a /// value that is at the midpoint between two different minutes, the value is rounded /// up. For example, if you specify a value of 90, users are disconnected after 2 minutes /// of inactivity. /// </para> /// </note> /// </summary> public int IdleDisconnectTimeoutInSeconds { get { return this._idleDisconnectTimeoutInSeconds.GetValueOrDefault(); } set { this._idleDisconnectTimeoutInSeconds = value; } } // Check to see if IdleDisconnectTimeoutInSeconds property is set internal bool IsSetIdleDisconnectTimeoutInSeconds() { return this._idleDisconnectTimeoutInSeconds.HasValue; } /// <summary> /// Gets and sets the property ImageArn. /// <para> /// The ARN for the public, private, or shared image. /// </para> /// </summary> public string ImageArn { get { return this._imageArn; } set { this._imageArn = value; } } // Check to see if ImageArn property is set internal bool IsSetImageArn() { return this._imageArn != null; } /// <summary> /// Gets and sets the property ImageName. /// <para> /// The name of the image used to create the fleet. /// </para> /// </summary> [AWSProperty(Min=1)] public string ImageName { get { return this._imageName; } set { this._imageName = value; } } // Check to see if ImageName property is set internal bool IsSetImageName() { return this._imageName != null; } /// <summary> /// Gets and sets the property InstanceType. /// <para> /// The instance type to use when launching fleet instances. The following instance types /// are available: /// </para> /// <ul> <li> /// <para> /// stream.standard.medium /// </para> /// </li> <li> /// <para> /// stream.standard.large /// </para> /// </li> <li> /// <para> /// stream.compute.large /// </para> /// </li> <li> /// <para> /// stream.compute.xlarge /// </para> /// </li> <li> /// <para> /// stream.compute.2xlarge /// </para> /// </li> <li> /// <para> /// stream.compute.4xlarge /// </para> /// </li> <li> /// <para> /// stream.compute.8xlarge /// </para> /// </li> <li> /// <para> /// stream.memory.large /// </para> /// </li> <li> /// <para> /// stream.memory.xlarge /// </para> /// </li> <li> /// <para> /// stream.memory.2xlarge /// </para> /// </li> <li> /// <para> /// stream.memory.4xlarge /// </para> /// </li> <li> /// <para> /// stream.memory.8xlarge /// </para> /// </li> <li> /// <para> /// stream.memory.z1d.large /// </para> /// </li> <li> /// <para> /// stream.memory.z1d.xlarge /// </para> /// </li> <li> /// <para> /// stream.memory.z1d.2xlarge /// </para> /// </li> <li> /// <para> /// stream.memory.z1d.3xlarge /// </para> /// </li> <li> /// <para> /// stream.memory.z1d.6xlarge /// </para> /// </li> <li> /// <para> /// stream.memory.z1d.12xlarge /// </para> /// </li> <li> /// <para> /// stream.graphics-design.large /// </para> /// </li> <li> /// <para> /// stream.graphics-design.xlarge /// </para> /// </li> <li> /// <para> /// stream.graphics-design.2xlarge /// </para> /// </li> <li> /// <para> /// stream.graphics-design.4xlarge /// </para> /// </li> <li> /// <para> /// stream.graphics-desktop.2xlarge /// </para> /// </li> <li> /// <para> /// stream.graphics.g4dn.xlarge /// </para> /// </li> <li> /// <para> /// stream.graphics.g4dn.2xlarge /// </para> /// </li> <li> /// <para> /// stream.graphics.g4dn.4xlarge /// </para> /// </li> <li> /// <para> /// stream.graphics.g4dn.8xlarge /// </para> /// </li> <li> /// <para> /// stream.graphics.g4dn.12xlarge /// </para> /// </li> <li> /// <para> /// stream.graphics.g4dn.16xlarge /// </para> /// </li> <li> /// <para> /// stream.graphics-pro.4xlarge /// </para> /// </li> <li> /// <para> /// stream.graphics-pro.8xlarge /// </para> /// </li> <li> /// <para> /// stream.graphics-pro.16xlarge /// </para> /// </li> </ul> /// </summary> [AWSProperty(Required=true, Min=1)] public string InstanceType { get { return this._instanceType; } set { this._instanceType = value; } } // Check to see if InstanceType property is set internal bool IsSetInstanceType() { return this._instanceType != null; } /// <summary> /// Gets and sets the property MaxUserDurationInSeconds. /// <para> /// The maximum amount of time that a streaming session can remain active, in seconds. /// If users are still connected to a streaming instance five minutes before this limit /// is reached, they are prompted to save any open documents before being disconnected. /// After this time elapses, the instance is terminated and replaced by a new instance. /// /// </para> /// /// <para> /// Specify a value between 600 and 360000. /// </para> /// </summary> public int MaxUserDurationInSeconds { get { return this._maxUserDurationInSeconds.GetValueOrDefault(); } set { this._maxUserDurationInSeconds = value; } } // Check to see if MaxUserDurationInSeconds property is set internal bool IsSetMaxUserDurationInSeconds() { return this._maxUserDurationInSeconds.HasValue; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the fleet. /// </para> /// </summary> [AWSProperty(Required=true, Min=1)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property State. /// <para> /// The current state for the fleet. /// </para> /// </summary> [AWSProperty(Required=true)] public FleetState State { get { return this._state; } set { this._state = value; } } // Check to see if State property is set internal bool IsSetState() { return this._state != null; } /// <summary> /// Gets and sets the property StreamView. /// <para> /// The AppStream 2.0 view that is displayed to your users when they stream from the fleet. /// When <code>APP</code> is specified, only the windows of applications opened by users /// display. When <code>DESKTOP</code> is specified, the standard desktop that is provided /// by the operating system displays. /// </para> /// /// <para> /// The default value is <code>APP</code>. /// </para> /// </summary> public StreamView StreamView { get { return this._streamView; } set { this._streamView = value; } } // Check to see if StreamView property is set internal bool IsSetStreamView() { return this._streamView != null; } /// <summary> /// Gets and sets the property VpcConfig. /// <para> /// The VPC configuration for the fleet. /// </para> /// </summary> public VpcConfig VpcConfig { get { return this._vpcConfig; } set { this._vpcConfig = value; } } // Check to see if VpcConfig property is set internal bool IsSetVpcConfig() { return this._vpcConfig != null; } } }
32.86262
200
0.5367
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/AppStream/Generated/Model/Fleet.cs
20,572
C#
using System; using System.ComponentModel.DataAnnotations; namespace PerPush.Api.Entities { public class Paper { [Required] public Guid Id { get; set; } [Required] public Guid UserId { get; set; } [Required] [StringLength(512, MinimumLength = 1)] public string Title { get; set; } [Required] public string Description { get; set; } [Required] [StringLength(512, MinimumLength = 1)] public string Lable { get; set; } public bool Auth { get; set; } = true; /// <summary> /// 创建时间 /// </summary> public DateTimeOffset StartTime { get; set; } = DateTimeOffset.Now; /// <summary> /// 参观人数 /// </summary> public int Visitors { get; set; } = 0; /// <summary> /// 喜欢的人数 /// </summary> public int Likes { get; set; } = 0; public User Author { get; set; } } }
23.829268
75
0.516888
[ "MIT" ]
Erosionying/PerPush.Api
PerPush.Api/Entities/Paper.cs
1,005
C#
using System; // HACKER RANK > FAILED CASE 4 & 5 // ------------------------------- // ReSharper disable once CheckNamespace // ReSharper disable once ArrangeTypeModifiers class LargestPrimeFactor2 { public static void LargestPrimeFactor2Main(string[] args) { var t = Convert.ToInt32(Console.ReadLine()); for (var a0 = 0; a0 < t; a0++) { var n = Convert.ToInt64(Console.ReadLine()); Console.WriteLine(GetLargestPrimeFactor(n)); } Console.ReadLine(); } private static long GetLargestPrimeFactor(long theNumber) { var largestPrimeFactor = theNumber + 1; // Is the same number Max if (theNumber % 2 == 1 && IsPrime(theNumber)) { return theNumber; } // Others from max to min var i = theNumber % 2 == 0 ? theNumber / 2: (theNumber + 1) / 2; if (i % 2 == 0) { i--; } while (largestPrimeFactor > theNumber && i > 1) { if (theNumber % i != 0 || !IsPrime(i)) { i = GetPreviousMaybePrime(i); continue; } largestPrimeFactor = i; } return largestPrimeFactor; } private static bool IsPrime(long number) { if (IsFirstPrime(number)) { return true; } if (IsDivisibleByFirstPrimes(number)) { return false; } var isPrime = true; long oddNumber = 29; while (isPrime && number > oddNumber) { if (number % oddNumber == 0) { isPrime = false; } oddNumber = GetNextMaybePrime(oddNumber); } return isPrime; } private static bool IsFirstPrime(long number) { return number == 2 || number == 3 || number == 5 || number == 7 || number == 11 || number == 13 || number == 17 || number == 19 || number == 23; } private static bool IsDivisibleByFirstPrimes(long number) { return number % 2 == 0 || number % 3 == 0 || number % 5 == 0 || number % 7 == 0 || number % 11 == 0 || number % 13 == 0 || number % 17 == 0 || number % 19 == 0 || number % 23 == 0; } private static long GetNextMaybePrime(long oddNumber) { do { oddNumber = oddNumber + 2; } while (IsDivisibleByFirstPrimes(oddNumber)); return oddNumber; } private static long GetPreviousMaybePrime(long oddNumber) { do { oddNumber = oddNumber - 2; if (oddNumber == 1) { oddNumber = 2; } } while (!IsFirstPrime(oddNumber) && IsDivisibleByFirstPrimes(oddNumber) && oddNumber > 1); return oddNumber; } }
21.709402
95
0.564173
[ "MIT" ]
gabrielizalo/HackerRank
Contests/ProjectEuler+/003 Largest Prime Factor 2.cs
2,540
C#
// Copyright 2017 Esri // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ControlStyles { public class RadioButtonStyleViewModel : StyleViewModelBase { public RadioButtonStyleViewModel() { LoadRadioBtns(); } public override void Initialize() { if (_listRadioBtns.Count > 0) SelectedRadioBtn = _listRadioBtns[0]; } private void LoadRadioBtns() { if (_listRadioBtns == null) { _listRadioBtns = new ObservableCollection<string>(); foreach (string chkBx in CheckBoxStyles) { _listRadioBtns.Add(chkBx); } this.NotifyPropertyChanged(() => ListOfRadioBtns); } } private static readonly string[] CheckBoxStyles = { "RadioButton" }; #region properties /// <summary> /// Collection of Styles that will be displayed /// </summary> private ObservableCollection<string> _listRadioBtns; public IList<string> ListOfRadioBtns { get { return _listRadioBtns; } } private string _selectedRadioBtn; public string SelectedRadioBtn { get { return _selectedRadioBtn; } set { SetProperty(ref _selectedRadioBtn, value, () => SelectedRadioBtn); StyleXaml = string.Format("<RadioButton Content=\"RadioButton\" IsChecked=\"True\" IsEnabled=\"True\"></RadioButton>"); } } #endregion } }
31.944444
135
0.604348
[ "Apache-2.0" ]
yong7743/arcgis-pro-sdk-community-samples
Framework/Styling-with-ArcGIS-Pro/ControlStyles/RadioButtonStyleViewModel.cs
2,302
C#
namespace Owin.Scim.Tests.Querying.Filtering.Normalization { using Machine.Specifications; using Scim.Querying; public class with_terminal_attribute_and_grouped_filter : when_normalizing_a_path_filter { Establish context = () => PathFilter = "[displayName eq \"Daniel\"]"; It should_contain = () => ScimFilter.Paths.ShouldContainOnly( new PathFilterExpression(null, "displayName eq \"Daniel\"")); It should_equal = () => ScimFilter.NormalizedFilterExpression.ShouldEqual("displayName eq \"Daniel\""); } }
35.3125
111
0.702655
[ "MIT" ]
Mysonemo/Owin.Scim
source/_tests/Owin.Scim.Tests/Querying/Filtering/Normalization/with_terminal_attribute_and_grouped_filter.cs
567
C#
namespace Alex.Blocks.Minecraft { public class Pumpkin : Block { public Pumpkin() : base() { Solid = true; Transparent = false; } } }
12.416667
31
0.624161
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
codingwatching/Alex
src/Alex/Blocks/Minecraft/Pumpkin.cs
149
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Stormancer.Core.DependencyResolver { public class DefaultConstructorRegistrationBuilder<T> : DefaultRegistrationBuilderBase where T : class { public override Type SelfType => typeof(T); } }
24.142857
106
0.766272
[ "MIT" ]
Stormancer/Stormancer
src/Common/Stormancer.Core/DependencyResolver/DefaultConstructorRegistrationBuilder.cs
340
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ReserveLevel.cs" company="Martin Amareld"> // Copyright(c) 2017 Martin Amareld. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace EdNetApi.Journal.Enums { public enum ReserveLevel { UnknownValue = -1, Pristine = 0, Major, Common, Low, Depleted } }
32.555556
121
0.332765
[ "MIT" ]
ambedatpro/ednetapi
EdNetApi/Journal/Enums/ReserveLevel.cs
588
C#
// <copyright file="MathCalculatorController.cs" company="PlaceholderCompany"> // Copyright (c) PlaceholderCompany. All rights reserved. // </copyright> namespace SimpleCalculator.Controllers { using System.Web.Http.Cors; using Microsoft.AspNetCore.Mvc; using SimpleArithmeticCalculator; using SimpleArithmeticCalculator.Enums; /// <summary> /// Controller MathCalculatorController is created. /// </summary> [EnableCors("http://localhost:4200", "*", "GET,PUT,POST")] public class MathCalculatorController { /// <summary> /// API Request Recieving Method. /// </summary> /// <param name="firstValue">Inputs first param.</param> /// <param name="secondValue">Inputs second param.</param> /// <param name="operationType">Type of operation.</param> /// <returns>Returns calculated output.</returns> [HttpGet] public double ArithmeticCalculator(double firstValue = 0, double secondValue = 0, int operationType = 1) { Calculator calculator = new Calculator(); var commandType = (CommandType)operationType; var command = calculator.CreateCommand(commandType); double output = command.Calculate(firstValue, secondValue); return output; } } }
36.888889
111
0.652108
[ "MIT" ]
ahamed1997/SimpleCalculator
SimpleCalculator/SimpleCalculator/Controllers/MathCalculatorController.cs
1,330
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Jdenticon extensions for WPF .NET 4.5")]
28.5
66
0.812865
[ "MIT" ]
dmester/jdenticon-net
Targets/Jdenticon.Wpf.Net45/Properties/AssemblyInfo.cs
173
C#
using System.Diagnostics; using LottieUWP.Animation.Content; using LottieUWP.Model.Layer; namespace LottieUWP.Model.Content { public class MergePaths : IContentModel { public enum MergePathsMode { Merge = 1, Add = 2, Subtract = 3, Intersect = 4, ExcludeIntersections = 5 } private readonly MergePathsMode _mode; public MergePaths(string name, MergePathsMode mode) { Name = name; _mode = mode; } public virtual string Name { get; } internal virtual MergePathsMode Mode => _mode; public IContent ToContent(LottieDrawable drawable, BaseLayer layer) { if (!drawable.EnableMergePathsForKitKatAndAbove()) { Debug.WriteLine("Animation contains merge paths but they are disabled.", LottieLog.Tag); return null; } return new MergePathsContent(this); } public override string ToString() { return "MergePaths{" + "mode=" + _mode + '}'; } } }
25.466667
104
0.557592
[ "Apache-2.0" ]
TanayParikh/LottieUWP
LottieUWP/Model/Content/MergePaths.cs
1,148
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Measure.LabCommon.Models; using System.Collections; namespace Measure.LabDataAccess { public class CustomerOrderInstrumentDaoImpl { /// <summary> /// 增加一条数据. /// </summary> public void Add(CustomerOrderInstrumentModel model) { DBProvider2.customerDbMapper.Insert("CustomerOrder_Instrument.Insert", model); } /// <summary> /// 更新一条数据. /// </summary> public void Update(CustomerOrderInstrumentModel model) { DBProvider2.customerDbMapper.Update("CustomerOrder_Instrument.Update", model); } /// <summary> /// 删除一条数据. /// </summary> public void DeleteById(int InstrumentId) { DBProvider2.customerDbMapper.Delete("CustomerOrder_Instrument.DeleteById", InstrumentId); } /// <summary> /// 得到一个对象实体. /// </summary> public CustomerOrderInstrumentModel GetById(int InstrumentId) { return DBProvider2.customerDbMapper.SelectObject<CustomerOrderInstrumentModel>("CustomerOrder_Instrument.GetByID", InstrumentId); } public IList<CustomerOrderInstrumentModel> GetByOrderId(int orderId) { return DBProvider2.customerDbMapper.SelectList<CustomerOrderInstrumentModel>("CustomerOrder_Instrument.GetByOrderId", orderId); } public IList<CustomerOrderInstrumentModel> GetByOrderIdList(IList<int> orderIdList) { if (orderIdList == null || orderIdList.Count < 0) { return new List<CustomerOrderInstrumentModel>(); } return DBProvider2.customerDbMapper.SelectList<CustomerOrderInstrumentModel>("CustomerOrder_Instrument.GetByOrderIdList", orderIdList); } /// <summary> /// 获得所有记录. /// </summary> public IList<CustomerOrderInstrumentModel> GetAll() { return DBProvider2.customerDbMapper.SelectList<CustomerOrderInstrumentModel>("CustomerOrder_Instrument.GetAll"); } } }
31.185714
147
0.641319
[ "MIT" ]
aliostad/deep-learning-lang-detection
data/test/csharp/49ace354eb3d49e2f31e29ca33e5944a1e5abc5dCustomerOrderInstrumentDaoImpl.cs
2,249
C#
using System.Web; using System.Web.Mvc; namespace Developerbackpack.Webapi { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
19.785714
80
0.66787
[ "MIT" ]
developerbackpack/webapi-tutorials
src/Developerbackpack.Webapi/App_Start/FilterConfig.cs
279
C#
using Rationals; using System.Collections; using System.Collections.Generic; using System.Text; using System; namespace Algebra { namespace Atoms { internal class Arctan : AtomicMonad { new public static Expression ArctanOf(Expression argument) { return new Arctan(argument); } public Arctan(Expression argument) : base(argument) { } public override Expression GetDerivative(string wrt) { Expression derivative = _argument.GetDerivative(wrt); return derivative / (1 + Pow(_argument, ConstantFrom(2))); } public override Func<Expression, Expression> GetSimplifyingConstructor() { return ArctanOf; } protected override int GetHashSeed() { return 1726209880; } protected override string GetMonadFunctionName() { return "arctan"; } public override void Map(IMapping mapping) { mapping.EvaluateArctan(_argument); } public override T Map<T>(IMapping<T> mapping) { return mapping.EvaluateArctan(_argument); } public override T Map<T>(IExtendedMapping<T> mapping) { return mapping.EvaluateArctan(this, _argument); } public override T Map<T>(Expression otherExpression, IDualMapping<T> mapping) { if (otherExpression is Arctan other) { return mapping.EvaluateArctans(this._argument, other._argument); } return mapping.EvaluateOthers(this, otherExpression); } } } }
26.873239
89
0.520964
[ "MIT" ]
Joeoc2001/AlgebraSystem
AlgebraSystem/Atoms/Arctan.cs
1,910
C#
// class Abc { public string DefGhi(float jkl, bool mno) { //
10
45
0.585714
[ "MIT" ]
HighSchoolHacking/GLS-Draft
test/integration/MemberFunctionDeclareStart/public two parameters.cs
70
C#
// submitted by Julian Schacher (jspp), thanks to gustorn for the help using System; using System.Collections.Generic; using System.Linq; namespace HuffmanCoding { public class EncodingResult { public string BitString { get; set; } public Dictionary<char, string> Dictionary { get; set; } public HuffmanCoding.Node Tree { get; set; } public EncodingResult(string bitString, Dictionary<char, string> dictionary, HuffmanCoding.Node tree) { this.BitString = bitString; this.Dictionary = dictionary; this.Tree = tree; } } public class HuffmanCoding { // The Node class used for the Huffman Tree. public class Node : IComparable<Node> { public Node LeftChild { get; set; } public Node RightChild { get; set; } public string BitString { get; set; } = ""; public int Weight { get; set; } public string Key { get; set; } public bool IsLeaf => LeftChild == null && RightChild == null; // Creates a leaf. So just a node is created with the given values. public static Node CreateLeaf(char key, int weight) => new Node(key.ToString(), weight, null, null); // Creates a branch. Here a node is created by adding the keys and weights of both childs together. public static Node CreateBranch(Node leftChild, Node rightChild) => new Node(leftChild.Key + rightChild.Key, leftChild.Weight + rightChild.Weight, leftChild, rightChild); private Node(string key, int weight, Node leftChild, Node rightChild) { this.Key = key; this.Weight = weight; this.LeftChild = leftChild; this.RightChild = rightChild; } public int CompareTo(Node other) => this.Weight - other.Weight; } // Node with biggest value at the top. class NodePriorityList { public int Count => nodes.Count; private List<Node> nodes = new List<Node>(); public NodePriorityList() { } public NodePriorityList(List<Node> givenNodes) { this.nodes = givenNodes.ToList(); this.nodes.Sort(); } public void Add(Node newNode) { var index = this.nodes.BinarySearch(newNode); if (index < 0) this.nodes.Insert(~index, newNode); else this.nodes.Insert(index, newNode); } public Node Pop() { var result = this.nodes[0]; this.nodes.RemoveAt(0); return result; } } public EncodingResult Encode(string input) { var root = CreateTree(input); var dictionary = CreateDictionary(root); var bitString = CreateBitString(input, dictionary); return new EncodingResult(bitString, dictionary, root); } public string Decode(EncodingResult result) { var output = ""; Node currentNode = result.Tree; foreach (var bit in result.BitString) { // Go down the tree. if (bit == '0') currentNode = currentNode.LeftChild; else currentNode = currentNode.RightChild; if (currentNode.IsLeaf) { output += currentNode.Key; currentNode = result.Tree; } } return output; } private Node CreateTree(string input) { // Create a List of all characters and their count in input by putting them into nodes. var nodes = input .GroupBy(c => c) .Select(n => Node.CreateLeaf(n.Key, n.Count())) .ToList(); // Convert list of nodes to a NodePriorityList. var nodePriorityList = new NodePriorityList(nodes); // Create Tree. while (nodePriorityList.Count > 1) { // Pop the two nodes with the smallest weights from the nodePriorityList and create a parentNode with the CreateBranch method. (This method adds the keys and weights of the childs together.) var leftChild = nodePriorityList.Pop(); var rightChild = nodePriorityList.Pop(); var parentNode = Node.CreateBranch(leftChild, rightChild); nodePriorityList.Add(parentNode); } return nodePriorityList.Pop(); } private Dictionary<char, string> CreateDictionary(Node root) { // We're using a string instead of a actual bits here, since it makes the code somewhat more readable and this is an educational example. var dictionary = new Dictionary<char, string>(); CreateDictionary(root, "", dictionary); return dictionary; void CreateDictionary(Node node, string bitString, Dictionary<char, string> localDictionary) { if (node.IsLeaf) localDictionary.Add(node.Key[0], bitString); else { if (node.LeftChild != null) CreateDictionary(node.LeftChild, bitString + '0', localDictionary); if (node.RightChild != null) CreateDictionary(node.RightChild, bitString + '1', localDictionary); } } } private string CreateBitString(string input, Dictionary<char, string> dictionary) { // We're using a string right here. While no compression is achieved with a string, it's the easiest way to display what the compressed result looks like. Also this is just an educational example. var bitString = ""; foreach (var character in input) bitString += dictionary[character]; return bitString; } } }
37.25
208
0.545861
[ "MIT" ]
chrisb2244/algorithm-archive
chapters/data_compression/huffman/code/cs/HuffmanCoding.cs
6,258
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace TypeLitePlus { public static class TsFiles { public static Regex regex = new Regex("declare module (\\S+) {(.*?})\r\n}", RegexOptions.Singleline | RegexOptions.CultureInvariant); /// <summary> /// Splits the current TypeScriptFluent output into several files, one per module /// </summary> /// <param name="path">The path where the files should be saved.</param> /// <returns></returns> public static string ToModules(this TypeScriptFluent typeScriptFluent, string path) { string typeScript = typeScriptFluent.Generate(); return ToModules(typeScript, path); } /// <summary> /// Splits template output into several files, one per module /// </summary> /// <param name="typeScript">The current template output</param> /// <param name="path">The path where the files should be saved.</param> /// <returns></returns> public static string ToModules(string typeScript, string path) { StringBuilder result = new StringBuilder(); DirectoryInfo directoryInfo = new DirectoryInfo(path); if (!directoryInfo.Exists) { directoryInfo.Create(); } Dictionary<string, string> moduleNames = new Dictionary<string, string>(); MatchCollection matchCollection = regex.Matches(typeScript); foreach (Match match in matchCollection) { if (match.Groups.Count == 3) { string moduleName = match.Groups[1].Value; moduleNames.Add(moduleName, moduleName.convertToIdentifier()); } } foreach (Match match in matchCollection) { if (match.Groups.Count == 3) { string moduleName = match.Groups[1].Value; string moduleContent = match.Groups[2].Value; foreach (KeyValuePair<string, string> namePair in moduleNames) { if (moduleContent.Contains(namePair.Key)) { var header = String.Format("import {0} = require(\"{1}\");\r\n", namePair.Value, namePair.Key); moduleContent = moduleContent.Replace(namePair.Key, namePair.Value); moduleContent = header + moduleContent; } } string fileName = String.Format("{0}\\{1}.ts", path, moduleName); moduleContent.SaveToFile(fileName); result.AppendLine(fileName); } } return result.ToString(); } /// <summary> /// Saves a string to a text file /// </summary> /// <param name="aString">The contents to save to the text file.</param> /// <param name="aFileName">The name of the file.</param> private static void SaveToFile(this string aString, string aFileName) { FileInfo fileInfo = new FileInfo(aFileName); if (fileInfo.Exists) { fileInfo.Delete(); } using (FileStream stream = new FileStream(fileInfo.FullName, FileMode.Create)) { using (StreamWriter sw = new StreamWriter(stream)) { sw.Write(aString); sw.Close(); } } } /// <summary> /// Converts a string to a JavaScript Identifier /// </summary> /// <param name="text">The text that should be converted</param> /// <returns></returns> private static string convertToIdentifier(this string text) { string result = text; string firstLetter = text[0].ToString().ToLower(); result = firstLetter + text.Substring(1); result = result.Replace(".", ""); return result; } } }
36.410256
141
0.530751
[ "MIT" ]
CloudNimble/TypeLitePlus
TypeLitePlus.Core/TsFiles.cs
4,262
C#
namespace Machete.X12Schema.V5010.Maps { using X12; using X12.Configuration; public class LoopNM1_2_820Map : X12LayoutMap<LoopNM1_2_820, X12Entity> { public LoopNM1_2_820Map() { Id = "Loop_NM1_2_820"; Name = "Loop NM1"; Segment(x => x.IndividualOrOrganizationName, 0); Segment(x => x.ReferenceIdentification, 1); Segment(x => x.MaintenanceType, 2); Layout(x => x.LoopAIN, 3); Layout(x => x.LoopPEN, 4); } } }
25.409091
60
0.538462
[ "Apache-2.0" ]
ahives/Machete
src/Machete.X12Schema/V5010/Layouts/Maps/LoopNM1_2_820Map.cs
559
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EventStore; using Proximo.Cqrs.Core.Support; using Proximo.Cqrs.Server.Eventing; using Sample.QueryModel.Builder; namespace Sample.QueryModel.Rebuilder { /// <summary> /// holds on some information that are relevant to decide if a projection need to be run again /// </summary> public class DenormalizerRebuilder { private DenormalizersHashes _previosHashes; private readonly IDenormalizerCatalog _catalog; private readonly IStoreEvents _eventStore; private readonly IDenormalizersHashesStore _denormalizersHashesStore; private readonly IHashcodeGenerator _hashcodeGenerator; private readonly ILogger _logger; private readonly IDomainEventHandlerCatalog _domainEventHandlerCatalog; public DenormalizerRebuilder(IDenormalizerCatalog catalog, IDenormalizersHashesStore hashesStore, IHashcodeGenerator hashcodeGenerator, IDomainEventHandlerCatalog domainEventCatalog, IStoreEvents eventStore, ILogger logger) { _catalog = catalog; _eventStore = eventStore; _hashcodeGenerator = hashcodeGenerator; _domainEventHandlerCatalog = domainEventCatalog; _denormalizersHashesStore = hashesStore; _logger = logger; } public void Rebuild() { // get the list of previous hashes _previosHashes = _denormalizersHashesStore.Load(); // create an instance of // get the new list of denormalizers from the catalog DenormalizersHashes newHashes = new DenormalizersHashes(); List<DenormalizerToRebuild> denormalizersToRebuild = new List<DenormalizerToRebuild>(); // cycle through the list and compute the hashes for each denormalizer foreach (var denorm in _catalog.Denormalizers) { DenormalizerHash hash = new DenormalizerHash(); hash.Name = denorm.ToString(); hash.Hash = _hashcodeGenerator.Generate(denorm); hash.Timestamp = DateTime.Now; newHashes.Hashes.Add(hash); var ri = new DenormalizerToRebuild(hash, denorm); // check this list with the previous one to find if we need to rebuild the data DenormalizerHash prev = null; if (_previosHashes != null) prev = _previosHashes.Hashes.Where(p => p.Name == hash.Name).FirstOrDefault(); // rebuild the data if the denormalizer was not present before or if it was changed ri.IsRebuildNeeded = prev == null || prev.Hash != ri.Hash; if (ri.IsRebuildNeeded) denormalizersToRebuild.Add(ri); } // rebuild the data only for the denormalizer that are changed if (denormalizersToRebuild.Count > 0) { // ask the engine to perform a complete event replay _logger.Info("Commits Replay Start"); // get all the commits and related events var commitList = _eventStore.Advanced.GetFrom(DateTime.MinValue); _logger.Info(string.Format("Processing {0} commits", commitList.Count())); foreach (var commit in commitList) { if (commit.Headers.Count > 0) _logger.Info(string.Format("Commit Header {0}", DumpDictionaryToString(commit.Headers))); foreach (var committedEvent in commit.Events) { _logger.Info(string.Format("Replaying event: {0}", committedEvent.Body.ToString())); if (committedEvent.Headers.Count > 0) _logger.Info(string.Format("Event Header {0}", DumpDictionaryToString(committedEvent.Headers))); // it has side effects, like generating new commits on the eventstore //OriginalDomainEventRouter.Dispatch(committedEvent.Body); var eventType = committedEvent.Body.GetType(); var handlerList = _domainEventHandlerCatalog.GetAllHandlerFor(eventType); foreach (var invoker in handlerList) { if (typeof(IDomainEventDenormalizer).IsAssignableFrom(invoker.DefiningType)) { invoker.Invoke(committedEvent.Body as IDomainEvent); } } _logger.Info("Event Replay Completed"); } } // persist the new series of hashes _denormalizersHashesStore.Save(newHashes); } } private string DumpDictionaryToString(IDictionary<string, object> data) { StringBuilder sb = new StringBuilder(); foreach (var e in data) { sb.AppendFormat("{0} - {1}", e.Key, e.Value.ToString()); } return sb.ToString(); } } public class DenormalizerToRebuild : DenormalizerHash { public Type DenormalyzerType { get; set; } public bool IsRebuildNeeded { get; set; } public DenormalizerToRebuild(DenormalizerHash hash, Type t) { this.Hash = hash.Hash; this.Name = hash.Name; this.Timestamp = hash.Timestamp; this.DenormalyzerType = t; } } }
33.471014
128
0.733059
[ "BSD-3-Clause" ]
andreabalducci/Prxm.Cqrs
Sample.QueryModel.Rebuilder/DenormalizerRebuilder.cs
4,621
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract class SourceMemberFieldSymbol : SourceFieldSymbolWithSyntaxReference { private readonly DeclarationModifiers _modifiers; internal SourceMemberFieldSymbol( SourceMemberContainerTypeSymbol containingType, DeclarationModifiers modifiers, string name, SyntaxReference syntax, Location location) : base(containingType, name, syntax, location) { _modifiers = modifiers; } protected sealed override DeclarationModifiers Modifiers { get { return _modifiers; } } protected abstract TypeSyntax TypeSyntax { get; } protected abstract SyntaxTokenList ModifiersTokenList { get; } protected void TypeChecks(TypeSymbol type, BindingDiagnosticBag diagnostics) { if (type.IsStatic) { // Cannot declare a variable of static type '{0}' diagnostics.Add(ErrorCode.ERR_VarDeclIsStaticClass, this.ErrorLocation, type); } else if (type.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_FieldCantHaveVoidType, TypeSyntax?.Location ?? this.Locations[0]); } else if (type.IsRestrictedType(ignoreSpanLikeTypes: true)) { diagnostics.Add(ErrorCode.ERR_FieldCantBeRefAny, TypeSyntax?.Location ?? this.Locations[0], type); } else if (type.IsRefLikeType && (this.IsStatic || !containingType.IsRefLikeType)) { diagnostics.Add(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, TypeSyntax?.Location ?? this.Locations[0], type); } else if (IsConst && !type.CanBeConst()) { SyntaxToken constToken = default(SyntaxToken); foreach (var modifier in ModifiersTokenList) { if (modifier.Kind() == SyntaxKind.ConstKeyword) { constToken = modifier; break; } } Debug.Assert(constToken.Kind() == SyntaxKind.ConstKeyword); diagnostics.Add(ErrorCode.ERR_BadConstType, constToken.GetLocation(), type); } else if (IsVolatile && !type.IsValidVolatileFieldType()) { // '{0}': a volatile field cannot be of the type '{1}' diagnostics.Add(ErrorCode.ERR_VolatileStruct, this.ErrorLocation, this, type); } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (!this.IsNoMoreVisibleThan(type, ref useSiteInfo)) { // Inconsistent accessibility: field type '{1}' is less accessible than field '{0}' diagnostics.Add(ErrorCode.ERR_BadVisFieldType, this.ErrorLocation, this, type); } diagnostics.Add(this.ErrorLocation, useSiteInfo); } public abstract bool HasInitializer { get; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = this.DeclaringCompilation; var value = this.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); // Synthesize DecimalConstantAttribute when the default value is of type decimal if (this.IsConst && value != null && this.Type.SpecialType == SpecialType.System_Decimal) { var data = GetDecodedWellKnownAttributeData(); if (data == null || data.ConstValue == CodeAnalysis.ConstantValue.Unset) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDecimalConstantAttribute(value.DecimalValue)); } } // Synthesize RequiredMemberAttribute if this field is required if (IsRequired) { AddSynthesizedAttribute( ref attributes, this.DeclaringCompilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_RequiredMemberAttribute__ctor)); } } public override Symbol AssociatedSymbol { get { return null; } } public override int FixedSize { get { Debug.Assert(!this.IsFixedSizeBuffer, "Subclasses representing fixed fields must override"); state.NotePartComplete(CompletionPart.FixedSize); return 0; } } internal static DeclarationModifiers MakeModifiers(NamedTypeSymbol containingType, SyntaxToken firstIdentifier, SyntaxTokenList modifiers, BindingDiagnosticBag diagnostics, out bool modifierErrors) { bool isInterface = containingType.IsInterface; DeclarationModifiers defaultAccess = isInterface ? DeclarationModifiers.Public : DeclarationModifiers.Private; DeclarationModifiers allowedModifiers = DeclarationModifiers.AccessibilityMask | DeclarationModifiers.Const | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Volatile | DeclarationModifiers.Fixed | DeclarationModifiers.Unsafe | DeclarationModifiers.Abstract | DeclarationModifiers.Required; // Some of these are filtered out later, when illegal, for better error messages. var errorLocation = new SourceLocation(firstIdentifier); DeclarationModifiers result = ModifierUtils.MakeAndCheckNontypeMemberModifiers( isForTypeDeclaration: false, isForInterfaceMember: isInterface, modifiers, defaultAccess, allowedModifiers, errorLocation, diagnostics, out modifierErrors); if ((result & DeclarationModifiers.Abstract) != 0) { diagnostics.Add(ErrorCode.ERR_AbstractField, errorLocation); result &= ~DeclarationModifiers.Abstract; } if ((result & DeclarationModifiers.Fixed) != 0) { if ((result & DeclarationModifiers.Static) != 0) { // The modifier 'static' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.StaticKeyword)); } if ((result & DeclarationModifiers.ReadOnly) != 0) { // The modifier 'readonly' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.ReadOnlyKeyword)); } if ((result & DeclarationModifiers.Const) != 0) { // The modifier 'const' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.ConstKeyword)); } if ((result & DeclarationModifiers.Volatile) != 0) { // The modifier 'volatile' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.VolatileKeyword)); } if ((result & DeclarationModifiers.Required) != 0) { // The modifier 'required' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.RequiredKeyword)); } result &= ~(DeclarationModifiers.Static | DeclarationModifiers.ReadOnly | DeclarationModifiers.Const | DeclarationModifiers.Volatile | DeclarationModifiers.Required); Debug.Assert((result & ~(DeclarationModifiers.AccessibilityMask | DeclarationModifiers.Fixed | DeclarationModifiers.Unsafe | DeclarationModifiers.New)) == 0); } if ((result & DeclarationModifiers.Const) != 0) { if ((result & DeclarationModifiers.Static) != 0) { // The constant '{0}' cannot be marked static diagnostics.Add(ErrorCode.ERR_StaticConstant, errorLocation, firstIdentifier.ValueText); } if ((result & DeclarationModifiers.ReadOnly) != 0) { // The modifier 'readonly' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.ReadOnlyKeyword)); } if ((result & DeclarationModifiers.Volatile) != 0) { // The modifier 'volatile' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.VolatileKeyword)); } if ((result & DeclarationModifiers.Unsafe) != 0) { // The modifier 'unsafe' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.UnsafeKeyword)); } if ((result & DeclarationModifiers.Required) != 0) { // The modifier 'required' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.RequiredKeyword)); result &= ~DeclarationModifiers.Required; } result |= DeclarationModifiers.Static; // "constants are considered static members" } else { if ((result & DeclarationModifiers.Static) != 0 && (result & DeclarationModifiers.Required) != 0) { // The modifier 'required' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.RequiredKeyword)); result &= ~DeclarationModifiers.Required; } // NOTE: always cascading on a const, so suppress. // NOTE: we're being a bit sneaky here - we're using the containingType rather than this symbol // to determine whether or not unsafe is allowed. Since this symbol and the containing type are // in the same compilation, it won't make a difference. We do, however, have to pass the error // location explicitly. containingType.CheckUnsafeModifier(result, errorLocation, diagnostics); } return result; } internal sealed override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.Type: GetFieldType(ConsList<FieldSymbol>.Empty); break; case CompletionPart.FixedSize: int discarded = this.FixedSize; break; case CompletionPart.ConstantValue: GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); break; case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols state.NotePartComplete(CompletionPart.All & ~CompletionPart.FieldSymbolAll); break; } state.SpinWaitComplete(incompletePart, cancellationToken); } } internal override NamedTypeSymbol FixedImplementationType(PEModuleBuilder emitModule) { Debug.Assert(!this.IsFixedSizeBuffer, "Subclasses representing fixed fields must override"); return null; } } internal class SourceMemberFieldSymbolFromDeclarator : SourceMemberFieldSymbol { private readonly bool _hasInitializer; private TypeWithAnnotations.Boxed _lazyType; // Non-zero if the type of the field has been inferred from the type of its initializer expression // and the errors of binding the initializer have been or are being reported to compilation diagnostics. private int _lazyFieldTypeInferred; internal SourceMemberFieldSymbolFromDeclarator( SourceMemberContainerTypeSymbol containingType, VariableDeclaratorSyntax declarator, DeclarationModifiers modifiers, bool modifierErrors, BindingDiagnosticBag diagnostics) : base(containingType, modifiers, declarator.Identifier.ValueText, declarator.GetReference(), declarator.Identifier.GetLocation()) { _hasInitializer = declarator.Initializer != null; this.CheckAccessibility(diagnostics); if (!modifierErrors) { this.ReportModifiersDiagnostics(diagnostics); } if (containingType.IsInterface) { if (this.IsStatic) { Binder.CheckFeatureAvailability(declarator, MessageID.IDS_DefaultInterfaceImplementation, diagnostics, ErrorLocation); if (!ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, ErrorLocation); } } else { diagnostics.Add(ErrorCode.ERR_InterfacesCantContainFields, ErrorLocation); } } } protected sealed override TypeSyntax TypeSyntax { get { return GetFieldDeclaration(VariableDeclaratorNode).Declaration.Type; } } protected sealed override SyntaxTokenList ModifiersTokenList { get { return GetFieldDeclaration(VariableDeclaratorNode).Modifiers; } } public sealed override bool HasInitializer { get { return _hasInitializer; } } protected VariableDeclaratorSyntax VariableDeclaratorNode { get { return (VariableDeclaratorSyntax)this.SyntaxNode; } } private static BaseFieldDeclarationSyntax GetFieldDeclaration(CSharpSyntaxNode declarator) { return (BaseFieldDeclarationSyntax)declarator.Parent.Parent; } protected override SyntaxList<AttributeListSyntax> AttributeDeclarationSyntaxList { get { if (this.containingType.AnyMemberHasAttributes) { return GetFieldDeclaration(this.SyntaxNode).AttributeLists; } return default(SyntaxList<AttributeListSyntax>); } } internal override bool HasPointerType { get { if (_lazyType != null) { bool isPointerType = _lazyType.Value.DefaultType.Kind switch { SymbolKind.PointerType => true, SymbolKind.FunctionPointerType => true, _ => false }; Debug.Assert(isPointerType == IsPointerFieldSyntactically()); return isPointerType; } return IsPointerFieldSyntactically(); } } private bool IsPointerFieldSyntactically() { var declaration = GetFieldDeclaration(VariableDeclaratorNode).Declaration; if (declaration.Type.Kind() switch { SyntaxKind.PointerType => true, SyntaxKind.FunctionPointerType => true, _ => false }) { // public int * Blah; // pointer return true; } return IsFixedSizeBuffer; } internal sealed override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound) { Debug.Assert(fieldsBeingBound != null); if (_lazyType != null) { return _lazyType.Value; } var declarator = VariableDeclaratorNode; var fieldSyntax = GetFieldDeclaration(declarator); var typeSyntax = fieldSyntax.Declaration.Type; var compilation = this.DeclaringCompilation; var diagnostics = BindingDiagnosticBag.GetInstance(); TypeWithAnnotations type; // When we have multiple declarators, we report the type diagnostics on only the first. var diagnosticsForFirstDeclarator = BindingDiagnosticBag.GetInstance(); Symbol associatedPropertyOrEvent = this.AssociatedSymbol; if ((object)associatedPropertyOrEvent != null && associatedPropertyOrEvent.Kind == SymbolKind.Event) { EventSymbol @event = (EventSymbol)associatedPropertyOrEvent; if (@event.IsWindowsRuntimeEvent) { NamedTypeSymbol tokenTableType = this.DeclaringCompilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T); Binder.ReportUseSite(tokenTableType, diagnosticsForFirstDeclarator, this.ErrorLocation); // CONSIDER: Do we want to guard against the possibility that someone has created their own EventRegistrationTokenTable<T> // type that has additional generic constraints? type = TypeWithAnnotations.Create(tokenTableType.Construct(ImmutableArray.Create(@event.TypeWithAnnotations))); } else { type = @event.TypeWithAnnotations; } } else { var binderFactory = compilation.GetBinderFactory(SyntaxTree); var binder = binderFactory.GetBinder(typeSyntax); binder = binder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); if (!ContainingType.IsScriptClass) { type = binder.BindType(typeSyntax, diagnosticsForFirstDeclarator); } else { bool isVar; type = binder.BindTypeOrVarKeyword(typeSyntax, diagnostics, out isVar); Debug.Assert(type.HasType || isVar); if (isVar) { if (this.IsConst) { diagnosticsForFirstDeclarator.Add(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, typeSyntax.Location); } if (fieldsBeingBound.ContainsReference(this)) { diagnostics.Add(ErrorCode.ERR_RecursivelyTypedVariable, this.ErrorLocation, this); type = default; } else if (fieldSyntax.Declaration.Variables.Count > 1) { diagnosticsForFirstDeclarator.Add(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, typeSyntax.Location); } else if (this.IsConst && this.ContainingType.IsScriptClass) { // For const var in script, we won't try to bind the initializer (case below), as it can lead to an unbound recursion type = default; } else { fieldsBeingBound = new ConsList<FieldSymbol>(this, fieldsBeingBound); var syntaxNode = (EqualsValueClauseSyntax)declarator.Initializer; var initializerBinder = new ImplicitlyTypedFieldBinder(binder, fieldsBeingBound); var executableBinder = new ExecutableCodeBinder(syntaxNode, this, initializerBinder); var initializerOpt = executableBinder.BindInferredVariableInitializer(diagnostics, RefKind.None, syntaxNode, declarator); if (initializerOpt != null) { if ((object)initializerOpt.Type != null && !initializerOpt.Type.IsErrorType()) { type = TypeWithAnnotations.Create(initializerOpt.Type); } _lazyFieldTypeInferred = 1; } } if (!type.HasType) { type = TypeWithAnnotations.Create(binder.CreateErrorType("var")); } } } if (IsFixedSizeBuffer) { type = TypeWithAnnotations.Create(new PointerTypeSymbol(type)); if (ContainingType.TypeKind != TypeKind.Struct) { diagnostics.Add(ErrorCode.ERR_FixedNotInStruct, ErrorLocation); } var elementType = ((PointerTypeSymbol)type.Type).PointedAtType; int elementSize = elementType.FixedBufferElementSizeInBytes(); if (elementSize == 0) { var loc = typeSyntax.Location; diagnostics.Add(ErrorCode.ERR_IllegalFixedType, loc); } if (!binder.InUnsafeRegion) { diagnosticsForFirstDeclarator.Add(ErrorCode.ERR_UnsafeNeeded, declarator.Location); } } } Debug.Assert(type.DefaultType.IsPointerOrFunctionPointer() == IsPointerFieldSyntactically()); // update the lazyType only if it contains value last seen by the current thread: if (Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(type.WithModifiers(this.RequiredCustomModifiers)), null) == null) { TypeChecks(type.Type, diagnostics); // CONSIDER: SourceEventFieldSymbol would like to suppress these diagnostics. AddDeclarationDiagnostics(diagnostics); bool isFirstDeclarator = fieldSyntax.Declaration.Variables[0] == declarator; if (isFirstDeclarator) { AddDeclarationDiagnostics(diagnosticsForFirstDeclarator); } state.NotePartComplete(CompletionPart.Type); } diagnostics.Free(); diagnosticsForFirstDeclarator.Free(); return _lazyType.Value; } internal bool FieldTypeInferred(ConsList<FieldSymbol> fieldsBeingBound) { if (!ContainingType.IsScriptClass) { return false; } GetFieldType(fieldsBeingBound); // lazyIsImplicitlyTypedField can only transition from value 0 to 1: return _lazyFieldTypeInferred != 0 || Volatile.Read(ref _lazyFieldTypeInferred) != 0; } protected sealed override ConstantValue MakeConstantValue(HashSet<SourceFieldSymbolWithSyntaxReference> dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics) { if (!this.IsConst || VariableDeclaratorNode.Initializer == null) { return null; } return ConstantValueUtils.EvaluateFieldConstant(this, (EqualsValueClauseSyntax)VariableDeclaratorNode.Initializer, dependencies, earlyDecodingWellKnownAttributes, diagnostics); } internal override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken)) { if (this.SyntaxTree == tree) { if (!definedWithinSpan.HasValue) { return true; } var fieldDeclaration = GetFieldDeclaration(this.SyntaxNode); return fieldDeclaration.SyntaxTree.HasCompilationUnitRoot && fieldDeclaration.Span.IntersectsWith(definedWithinSpan.Value); } return false; } internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { // This check prevents redundant ManagedAddr diagnostics on the underlying pointer field of a fixed-size buffer if (!IsFixedSizeBuffer) { Type.CheckAllConstraints(DeclaringCompilation, conversions, ErrorLocation, diagnostics); } base.AfterAddingTypeMembersChecks(conversions, diagnostics); } } }
42.531447
205
0.578521
[ "MIT" ]
BillWagner/roslyn
src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberFieldSymbol.cs
27,052
C#
// Decompiled with JetBrains decompiler // Type: Game.Logic.Effects.GuardEffect // Assembly: Game.Logic, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: E8B04D54-7E5B-47C4-9280-AF82495F6281 // Assembly location: C:\Users\Pham Van Hungg\Desktop\Decompiler\Road\Game.Logic.dll using Game.Logic.Phy.Object; namespace Game.Logic.Effects { public class GuardEffect : AbstractEffect { private int m_count; public GuardEffect(int count) : base(eEffectType.GuardEffect) { this.m_count = count; } public override void OnAttached(Living living) { living.BeginSelfTurn += new LivingEventHandle(this.player_BeginFitting); living.Game.SendPlayerPicture(living, 30, true); } public override void OnRemoved(Living living) { living.BeginSelfTurn -= new LivingEventHandle(this.player_BeginFitting); living.Game.SendPlayerPicture(living, 30, false); } private void player_BeginFitting(Living living) { --this.m_count; if (this.m_count > 0) return; this.Stop(); } public override bool Start(Living living) { GuardEffect ofType = living.EffectList.GetOfType(eEffectType.GuardEffect) as GuardEffect; if (ofType == null) return base.Start(living); ofType.m_count = this.m_count; return true; } } }
26.72549
95
0.687454
[ "MIT" ]
HuyTruong19x/DDTank4.1
Source Server/Game.Logic/Effects/GuardEffect.cs
1,365
C#
using Group3r.Options.AssessmentOptions; using Sddl.Parser; using System; using System.Collections.Generic; namespace Group3r.Assessment { public class SddlAnalyser { private AssessmentOptions AssessmentOptions { get; set; } public SddlAnalyser(AssessmentOptions assessmentOptions) { AssessmentOptions = assessmentOptions; } public List<SimpleAce> AnalyseSddl(Sddl.Parser.Sddl sddl) { // simplify it once List<SimpleAce> simpleAC = SimplifyAC(sddl); // assess and strip out defaults etc List<SimpleAce> AclResult = AssessSimpleAC(simpleAC); return AclResult; } public List<SimpleAce> AssessSimpleAC(List<SimpleAce> SimpleAC) { List<SimpleAce> aclResult = new List<SimpleAce>(); // make a new List<SimpleAce> to put the ones that aren't boring into. foreach (SimpleAce ace in SimpleAC) { List<String> intRights = new List<string>(); foreach (string right in ace.Rights) { // check if there's any interesting rights being handed out if (AssessmentOptions.InterestingRights.Contains(right) && ace.ACEType.Equals(ACEType.Allow)) { intRights.Add(right); }; } if (intRights.Count > 0) { // iterate over trustees in assessmentoptions foreach (TrusteeOption trustee in AssessmentOptions.TrusteeOptions) { // find the match (if any) if (trustee.DisplayName.ToLower().Equals(ace.Trustee.ToLower())) { if (trustee.LowPriv && intRights.Count > 0) { SimpleAce aceResult = new SimpleAce { ACEType = ace.ACEType, Trustee = ace.Trustee, Rights = ace.Rights }; AceFinding aceFinding = new AceFinding { Triage = LibSnaffle.Classifiers.Rules.Constants.Triage.Red, FindingReason = "AccessControl on this object grants interesting privileges to a very common low-privilege group or user.", FindingDetail = ace.Trustee + " was assigned the following rights: " + String.Join(", ", intRights) + "." }; aceResult.AceFinding = aceFinding; aclResult.Add(aceResult); break; } else if (trustee.HighPriv) { // boring break; } else if (!trustee.LowPriv) { SimpleAce aceResult = new SimpleAce { Trustee = ace.Trustee, Rights = ace.Rights }; aclResult.Add(aceResult); break; } } } // iterate over users and groups in targettrustees foreach (string trustee in AssessmentOptions.TargetTrustees) { if (trustee.ToLower().Equals(ace.Trustee.ToLower())) { if (intRights.Count > 0) { SimpleAce aceResult = new SimpleAce { ACEType = ace.ACEType, Trustee = ace.Trustee, Rights = ace.Rights }; AceFinding aceFinding = new AceFinding { Triage = LibSnaffle.Classifiers.Rules.Constants.Triage.Red, FindingReason = "AccessControl on this object grants interesting privileges to an explicitly targeted user or group.", FindingDetail = "By default this targets the current user and any groups they're a member of. Specifically, " + ace.Trustee + " was assigned the following rights: " + String.Join(", ", intRights) + "." }; aceResult.AceFinding = aceFinding; } if (intRights.Count == 0) { SimpleAce aceResult = new SimpleAce { ACEType = ace.ACEType, Trustee = ace.Trustee, Rights = ace.Rights }; aclResult.Add(aceResult); } } } } } return aclResult; } public List<SimpleAce> SimplifyAC(Sddl.Parser.Sddl sddl) { List<SimpleAce> SimpleAC = new List<SimpleAce>(); if (sddl.Owner != null) { if (!String.IsNullOrWhiteSpace(sddl.Owner.Alias)) { SimpleAC.Add(new SimpleAce() { ACEType = ACEType.Allow, Rights = new string[1] { "Owner" }, Trustee = sddl.Owner.Alias }); } } if (sddl.Dacl.Aces.Length > 0) { foreach (Ace ace in sddl.Dacl.Aces) { SimpleAce simpleAce = new SimpleAce { Trustee = ace.AceSid.Alias }; switch (ace.AceType) { case "OBJECT_ACCESS_ALLOWED": simpleAce.ACEType = ACEType.Allow; break; case "OBJECT_ACCESS_DENIED": simpleAce.ACEType = ACEType.Deny; break; default: break; } simpleAce.Rights = SimplifyRights(ace.Rights); SimpleAC.Add(simpleAce); } } return SimpleAC; } public string[] SimplifyRights(string[] rights) { //TODO actually simplify these? does it matter? return rights; } } public class SimpleAce { public string Trustee { get; set; } public ACEType ACEType { get; set; } //public List<SimpleRight> Rights { get; set; } public string[] Rights { get; set; } public AceFinding AceFinding { get; set; } } public enum SimpleRight { List, Read, LimitedWrite, Modify, Full } public enum ACEType { Allow, Deny } public class AceFinding { public string FindingReason { get; set; } public string FindingDetail { get; set; } public LibSnaffle.Classifiers.Rules.Constants.Triage Triage { get; set; } } }
38.609756
237
0.415793
[ "MIT" ]
topotam/Group3r
Group3r/Assessment/SddlAnalyser.cs
7,917
C#
using System; namespace Parquet.Data { /// <summary> /// Element of dataset's schema /// </summary> public abstract class Field { /// <summary> /// Type of schema in this field /// </summary> public SchemaType SchemaType { get; } /// <summary> /// Column name /// </summary> public string Name { get; private set; } /// <summary> /// Only used internally! /// </summary> internal string Path { get; set; } internal virtual string PathPrefix { set { } } /// <summary> /// Constructs a field with only requiremd parameters /// </summary> /// <param name="name">Field name, required</param> /// <param name="schemaType">Type of schema of this field</param> protected Field(string name, SchemaType schemaType) { Name = name ?? throw new ArgumentNullException(nameof(name)); if(Name.Contains(Schema.PathSeparator)) { throw new ArgumentException($"'{Schema.PathSeparator}' is not allowed in field name as it's used internally as path separator"); } SchemaType = schemaType; Path = name; } #region [ Internal Helpers ] internal virtual void Assign(Field field) { //only used by some schema fields internally to help construct a field hierarchy } #endregion } }
25.709091
140
0.582744
[ "MIT" ]
dominiqueplante/parquet-dotnet
src/Parquet/Data/Schema/Field.cs
1,416
C#
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; namespace DFC.App.Account.Services.DSS.Models { class UpdateLastLoginRequest { public DateTime LastLoggedInDateTime { get; set; } [JsonProperty("id_token")] public string Token { get; set; } } }
22
58
0.685065
[ "MIT" ]
SkillsFundingAgency/dfc-app-account
DFC.App.Account.Services.DSS/Models/UpdateLastLoginRequest.cs
310
C#
using System; using System.Management.Automation; using System.Management.Automation.Language; namespace ClosureRewriter.Commands { [Cmdlet(VerbsCommon.New, "Closure")] [OutputType(typeof(ScriptBlock))] public class NewClosureCommand : PSCmdlet { [Parameter(Mandatory = true, Position = 0)] [ValidateNotNull] public ScriptBlock ScriptBlock { get; set; } [Parameter()] [ValidateNotNull] public Type DelegateType { get; set; } protected override void EndProcessing() { var closure = ClosureRewriter.CreateNewClosure(ScriptBlock, DelegateType); var sbAst = ScriptBlock.Ast as ScriptBlockAst; var e = sbAst.Extent; var invokeDelegateExpr = new InvokeMemberExpressionAst( e, new ConstantExpressionAst(e, closure), new StringConstantExpressionAst(e, nameof(Action.Invoke), StringConstantType.BareWord), Array.Empty<ExpressionAst>(), @static: false); var invokeDelegateStmt = new CommandExpressionAst( e, invokeDelegateExpr, Array.Empty<RedirectionAst>()); var newSbAst = new ScriptBlockAst( e, sbAst.UsingStatements, Array.Empty<AttributeAst>(), null, null, null, new NamedBlockAst( e, TokenKind.End, new StatementBlockAst(e, new[] { invokeDelegateStmt }, Array.Empty<TrapStatementAst>()), unnamed: true), null); WriteObject(newSbAst.GetScriptBlock()); } } }
32.796296
108
0.560136
[ "MIT" ]
SeeminglyScience/PSSyntaxRewriter
examples/ClosureRewriter/Commands/NewClosureCommand.cs
1,771
C#
using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; [assembly: XamlCompilation (XamlCompilationOptions.Compile)] namespace bm_hw_xam_forms { public partial class App : Application { public App () { InitializeComponent(); MainPage = new MainPage(); } protected override void OnStart () { // Handle when your app starts } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } }
15.818182
60
0.687739
[ "Apache-2.0" ]
colinsteffen/ba-xamarin-android
bm_hw_xam_forms/bm_hw_xam_forms/bm_hw_xam_forms/App.xaml.cs
522
C#
using System.Threading; using System.Threading.Tasks; namespace AwaitAndGetResult { public static class TaskExtensions { public static T AwaitAndGetResult<T>(this Task<T> task) => AwaitAndGetResult(task, new TaskFactory()); public static T AwaitAndGetResult<T>(this Task<T> task, TaskFactory taskFactory) { return taskFactory .StartNew(async () => await task.ConfigureAwait(false)) .Unwrap<T>() .GetAwaiter() .GetResult(); } } }
27.6
110
0.599638
[ "MIT" ]
piccaso/nuggets
AwaitAndGetResult/AwaitAndGetResult.cs
554
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ssm-2014-11-06.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SimpleSystemsManagement.Model { /// <summary> /// Information about a task defined for a maintenance window. /// </summary> public partial class MaintenanceWindowTask { private string _description; private LoggingInfo _loggingInfo; private string _maxConcurrency; private string _maxErrors; private string _name; private int? _priority; private string _serviceRoleArn; private List<Target> _targets = new List<Target>(); private string _taskArn; private Dictionary<string, MaintenanceWindowTaskParameterValueExpression> _taskParameters = new Dictionary<string, MaintenanceWindowTaskParameterValueExpression>(); private MaintenanceWindowTaskType _type; private string _windowId; private string _windowTaskId; /// <summary> /// Gets and sets the property Description. /// <para> /// A description of the task. /// </para> /// </summary> [AWSProperty(Min=1, Max=128)] public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property LoggingInfo. /// <para> /// Information about an Amazon S3 bucket to write task-level logs to. /// </para> /// <note> /// <para> /// <code>LoggingInfo</code> has been deprecated. To specify an S3 bucket to contain /// logs, instead use the <code>OutputS3BucketName</code> and <code>OutputS3KeyPrefix</code> /// options in the <code>TaskInvocationParameters</code> structure. For information about /// how Systems Manager handles these options for the supported maintenance window task /// types, see <a>MaintenanceWindowTaskInvocationParameters</a>. /// </para> /// </note> /// </summary> public LoggingInfo LoggingInfo { get { return this._loggingInfo; } set { this._loggingInfo = value; } } // Check to see if LoggingInfo property is set internal bool IsSetLoggingInfo() { return this._loggingInfo != null; } /// <summary> /// Gets and sets the property MaxConcurrency. /// <para> /// The maximum number of targets this task can be run for, in parallel. /// </para> /// </summary> [AWSProperty(Min=1, Max=7)] public string MaxConcurrency { get { return this._maxConcurrency; } set { this._maxConcurrency = value; } } // Check to see if MaxConcurrency property is set internal bool IsSetMaxConcurrency() { return this._maxConcurrency != null; } /// <summary> /// Gets and sets the property MaxErrors. /// <para> /// The maximum number of errors allowed before this task stops being scheduled. /// </para> /// </summary> [AWSProperty(Min=1, Max=7)] public string MaxErrors { get { return this._maxErrors; } set { this._maxErrors = value; } } // Check to see if MaxErrors property is set internal bool IsSetMaxErrors() { return this._maxErrors != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The task name. /// </para> /// </summary> [AWSProperty(Min=3, Max=128)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Priority. /// <para> /// The priority of the task in the maintenance window. The lower the number, the higher /// the priority. Tasks that have the same priority are scheduled in parallel. /// </para> /// </summary> [AWSProperty(Min=0)] public int Priority { get { return this._priority.GetValueOrDefault(); } set { this._priority = value; } } // Check to see if Priority property is set internal bool IsSetPriority() { return this._priority.HasValue; } /// <summary> /// Gets and sets the property ServiceRoleArn. /// <para> /// The ARN of the IAM service role to use to publish Amazon Simple Notification Service /// (Amazon SNS) notifications for maintenance window Run Command tasks. /// </para> /// </summary> public string ServiceRoleArn { get { return this._serviceRoleArn; } set { this._serviceRoleArn = value; } } // Check to see if ServiceRoleArn property is set internal bool IsSetServiceRoleArn() { return this._serviceRoleArn != null; } /// <summary> /// Gets and sets the property Targets. /// <para> /// The targets (either instances or tags). Instances are specified using Key=instanceids,Values=&lt;instanceid1&gt;,&lt;instanceid2&gt;. /// Tags are specified using Key=&lt;tag name&gt;,Values=&lt;tag value&gt;. /// </para> /// </summary> [AWSProperty(Min=0, Max=5)] public List<Target> Targets { get { return this._targets; } set { this._targets = value; } } // Check to see if Targets property is set internal bool IsSetTargets() { return this._targets != null && this._targets.Count > 0; } /// <summary> /// Gets and sets the property TaskArn. /// <para> /// The resource that the task uses during execution. For RUN_COMMAND and AUTOMATION task /// types, <code>TaskArn</code> is the Systems Manager document name or ARN. For LAMBDA /// tasks, it's the function name or ARN. For STEP_FUNCTIONS tasks, it's the state machine /// ARN. /// </para> /// </summary> [AWSProperty(Min=1, Max=1600)] public string TaskArn { get { return this._taskArn; } set { this._taskArn = value; } } // Check to see if TaskArn property is set internal bool IsSetTaskArn() { return this._taskArn != null; } /// <summary> /// Gets and sets the property TaskParameters. /// <para> /// The parameters that should be passed to the task when it is run. /// </para> /// <note> /// <para> /// <code>TaskParameters</code> has been deprecated. To specify parameters to pass to /// a task when it runs, instead use the <code>Parameters</code> option in the <code>TaskInvocationParameters</code> /// structure. For information about how Systems Manager handles these options for the /// supported maintenance window task types, see <a>MaintenanceWindowTaskInvocationParameters</a>. /// </para> /// </note> /// </summary> public Dictionary<string, MaintenanceWindowTaskParameterValueExpression> TaskParameters { get { return this._taskParameters; } set { this._taskParameters = value; } } // Check to see if TaskParameters property is set internal bool IsSetTaskParameters() { return this._taskParameters != null && this._taskParameters.Count > 0; } /// <summary> /// Gets and sets the property Type. /// <para> /// The type of task. The type can be one of the following: RUN_COMMAND, AUTOMATION, LAMBDA, /// or STEP_FUNCTIONS. /// </para> /// </summary> public MaintenanceWindowTaskType Type { get { return this._type; } set { this._type = value; } } // Check to see if Type property is set internal bool IsSetType() { return this._type != null; } /// <summary> /// Gets and sets the property WindowId. /// <para> /// The ID of the maintenance window where the task is registered. /// </para> /// </summary> [AWSProperty(Min=20, Max=20)] public string WindowId { get { return this._windowId; } set { this._windowId = value; } } // Check to see if WindowId property is set internal bool IsSetWindowId() { return this._windowId != null; } /// <summary> /// Gets and sets the property WindowTaskId. /// <para> /// The task ID. /// </para> /// </summary> [AWSProperty(Min=36, Max=36)] public string WindowTaskId { get { return this._windowTaskId; } set { this._windowTaskId = value; } } // Check to see if WindowTaskId property is set internal bool IsSetWindowTaskId() { return this._windowTaskId != null; } } }
33.063091
172
0.567503
[ "Apache-2.0" ]
TallyUpTeam/aws-sdk-net
sdk/src/Services/SimpleSystemsManagement/Generated/Model/MaintenanceWindowTask.cs
10,481
C#
// Copyright 2019 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using ArcGISRuntime.Samples.Shared.Models; using System; using System.Diagnostics; using Xamarin.Essentials; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace ArcGISRuntime { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SamplePage { private readonly MarkedNet.Marked _markdownRenderer = new MarkedNet.Marked(); private ContentPage _sample; public SamplePage() { InitializeComponent(); ToolbarItems[0].Clicked += (o, e) => { SampleDetailPage.IsVisible = !SampleDetailPage.IsVisible; }; } public SamplePage(ContentPage sample, SampleInfo sampleInfo) : this() { // Set the sample variable. _sample = sample; // Update the binding context - this is important for the description tab. BindingContext = sampleInfo; // Update the content - this displays the sample. SampleContentPage.Content = sample.Content; // Because the sample control isn't navigated to (its content is displayed directly), // navigation won't work from within the sample until the parent is manually set. sample.Parent = this; // Set the title. If the sample control didn't // define the title, use the name from the sample metadata. if (!String.IsNullOrWhiteSpace(sample.Title)) { Title = sample.Title; } else { Title = sampleInfo.SampleName; } // Set up the description page. try { string folderPath = sampleInfo.Path; string baseUrl = ""; string readmePath = ""; string basePath = ""; #if WINDOWS_UWP baseUrl = "ms-appx-web:///"; basePath = $"{baseUrl}{folderPath.Substring(folderPath.LastIndexOf("Samples"))}"; readmePath = System.IO.Path.Combine(folderPath, "readme.md"); #elif XAMARIN_ANDROID baseUrl = "file:///android_asset"; basePath = System.IO.Path.Combine(baseUrl, folderPath); readmePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), folderPath, "readme.md"); #elif __IOS__ baseUrl = Foundation.NSBundle.MainBundle.BundlePath; basePath = folderPath; readmePath = System.IO.Path.Combine(folderPath, "readme.md"); #endif string cssPath = $"{baseUrl}/github-markdown.css"; string readmeContent = System.IO.File.ReadAllText(readmePath); readmeContent = _markdownRenderer.Parse(readmeContent); // Fix paths for images. readmeContent = readmeContent.Replace("src='", "src=\"").Replace(".jpg'", ".jpg\"").Replace("src=\"", $"src=\"{basePath}/"); string htmlString = $"<!doctype html><head><link rel=\"stylesheet\" href=\"{cssPath}\" /></head><body class=\"markdown-body\">{readmeContent}</body>"; DescriptionView.Source = new HtmlWebViewSource() { Html = htmlString, BaseUrl = basePath }; DescriptionView.Navigating += Webview_Navigating; } catch (Exception ex) { Debug.WriteLine(ex); } } protected override void OnDisappearing() { if (_sample is IDisposable) ((IDisposable)_sample).Dispose(); base.OnDisappearing(); } private void Webview_Navigating(object sender, WebNavigatingEventArgs e) { // Open links in a new window instead of inside the web view. if (e.Url.StartsWith("http")) { try { Launcher.OpenAsync(new Uri(e.Url)); e.Cancel = true; } catch (Exception ex) { Debug.WriteLine(ex); } } } } }
39.07377
166
0.576673
[ "Apache-2.0" ]
kGhime/arcgis-runtime-samples-dotnet
src/Forms/Shared/SamplePage.xaml.cs
4,769
C#
using FreeSql.Internal.Model; using System; using System.Collections.Generic; using System.Data.Common; using System.Linq.Expressions; using System.Threading.Tasks; namespace FreeSql { public interface IUpdate<T1> where T1 : class { /// <summary> /// 指定事务对象 /// </summary> /// <param name="transaction"></param> /// <returns></returns> IUpdate<T1> WithTransaction(DbTransaction transaction); /// <summary> /// 指定事务对象 /// </summary> /// <param name="connection"></param> /// <returns></returns> IUpdate<T1> WithConnection(DbConnection connection); /// <summary> /// 不使用参数化,可通过 IFreeSql.CodeFirst.IsNotCommandParameter 全局性设置 /// </summary> /// <param name="isNotCommandParameter">是否不使用参数化</param> /// <returns></returns> IUpdate<T1> NoneParameter(bool isNotCommandParameter = true); /// <summary> /// 批量执行选项设置,一般不需要使用该方法<para></para> /// 各数据库 rows, parameters 限制不一样,默认设置:<para></para> /// MySql 500 3000<para></para> /// PostgreSQL 500 3000<para></para> /// SqlServer 500 2100<para></para> /// Oracle 200 999<para></para> /// Sqlite 200 999<para></para> /// 若没有事务传入,内部(默认)会自动开启新事务,保证拆包执行的完整性。 /// </summary> /// <param name="rowsLimit">指定根据 rows 上限数量拆分执行</param> /// <param name="parameterLimit">指定根据 parameters 上限数量拆分执行</param> /// <param name="autoTransaction">是否自动开启事务</param> /// <returns></returns> IUpdate<T1> BatchOptions(int rowsLimit, int parameterLimit, bool autoTransaction = true); /// <summary> /// 批量执行时,分批次执行的进度状态 /// </summary> /// <param name="callback">批量执行时的回调委托</param> /// <returns></returns> IUpdate<T1> BatchProgress(Action<BatchProgressStatus<T1>> callback); /// <summary> /// 更新数据,设置更新的实体<para></para> /// 注意:实体必须定义主键,并且最终会自动附加条件 where id = source.Id /// </summary> /// <param name="source">实体</param> /// <returns></returns> IUpdate<T1> SetSource(T1 source); /// <summary> /// 更新数据,设置更新的实体集合<para></para> /// 注意:实体必须定义主键,并且最终会自动附加条件 where id in (source.Id) /// </summary> /// <param name="source">实体集合</param> /// <returns></returns> IUpdate<T1> SetSource(IEnumerable<T1> source); /// <summary> /// 更新数据,设置更新的实体,同时设置忽略的列<para></para> /// 忽略 null 属性:fsql.Update&lt;T&gt;().SetSourceAndIgnore(item, colval => colval == null)<para></para> /// 注意:参数 ignore 与 IUpdate.IgnoreColumns/UpdateColumns 不能同时使用 /// </summary> /// <param name="source">实体</param> /// <param name="ignore">属性值忽略判断, true忽略</param> /// <returns></returns> IUpdate<T1> SetSourceIgnore(T1 source, Func<object, bool> ignore); /// <summary> /// 忽略的列,IgnoreColumns(a => a.Name) | IgnoreColumns(a => new{a.Name,a.Time}) | IgnoreColumns(a => new[]{"name","time"})<para></para> /// 注意:不能与 UpdateColumns 不能同时使用 /// </summary> /// <param name="columns">lambda选择列</param> /// <returns></returns> IUpdate<T1> IgnoreColumns(Expression<Func<T1, object>> columns); /// <summary> /// 忽略的列<para></para> /// 注意:不能与 UpdateColumns 不能同时使用 /// </summary> /// <param name="columns">属性名,或者字段名</param> /// <returns></returns> IUpdate<T1> IgnoreColumns(string[] columns); /// <summary> /// 指定的列,UpdateColumns(a => a.Name) | UpdateColumns(a => new{a.Name,a.Time}) | UpdateColumns(a => new[]{"name","time"})<para></para> /// 注意:不能与 IgnoreColumns 不能同时使用 /// </summary> /// <param name="columns">lambda选择列</param> /// <returns></returns> IUpdate<T1> UpdateColumns(Expression<Func<T1, object>> columns); /// <summary> /// 指定的列<para></para> /// 注意:不能与 IgnoreColumns 同时使用 /// </summary> /// <param name="columns">属性名,或者字段名</param> /// <returns></returns> IUpdate<T1> UpdateColumns(string[] columns); /// <summary> /// 设置列的新值,Set(a => a.Name, "newvalue") /// </summary> /// <typeparam name="TMember"></typeparam> /// <param name="column">lambda选择列</param> /// <param name="value">新值</param> /// <returns></returns> IUpdate<T1> Set<TMember>(Expression<Func<T1, TMember>> column, TMember value); /// <summary> /// 设置列的新值,Set(a => a.Name, "newvalue") /// </summary> /// <typeparam name="TMember"></typeparam> /// <param name="condition">true 时生效</param> /// <param name="column">lambda选择列</param> /// <param name="value">新值</param> /// <returns></returns> IUpdate<T1> SetIf<TMember>(bool condition, Expression<Func<T1, TMember>> column, TMember value); /// <summary> /// 设置列的的新值为基础上增加,格式:Set(a => a.Clicks + 1) 相当于 clicks=clicks+1 /// <para></para> /// 指定更新,格式:Set(a => new T { Clicks = a.Clicks + 1, Time = DateTime.Now }) 相当于 set clicks=clicks+1,time='2019-06-19....' /// </summary> /// <typeparam name="TMember"></typeparam> /// <param name="exp"></param> /// <returns></returns> IUpdate<T1> Set<TMember>(Expression<Func<T1, TMember>> exp); /// <summary> /// 设置列的的新值为基础上增加,格式:Set(a => a.Clicks + 1) 相当于 clicks=clicks+1 /// <para></para> /// 指定更新,格式:Set(a => new T { Clicks = a.Clicks + 1, Time = DateTime.Now }) 相当于 set clicks=clicks+1,time='2019-06-19....' /// </summary> /// <typeparam name="TMember"></typeparam> /// <param name="condition">true 时生效</param> /// <param name="exp"></param> /// <returns></returns> IUpdate<T1> SetIf<TMember>(bool condition, Expression<Func<T1, TMember>> exp); /// <summary> /// 设置值,自定义SQL语法,SetRaw("title = ?title", new { title = "newtitle" })<para></para> /// 提示:parms 参数还可以传 Dictionary&lt;string, object&gt; /// </summary> /// <param name="sql">sql语法</param> /// <param name="parms">参数</param> /// <returns></returns> IUpdate<T1> SetRaw(string sql, object parms = null); /// <summary> /// 设置更新的列<para></para> /// SetDto(new { title = "xxx", clicks = 2 })<para></para> /// SetDto(new Dictionary&lt;string, object&gt; { ["title"] = "xxx", ["clicks"] = 2 })<para></para> /// 注意:标记 [Column(CanUpdate = false)] 的属性不会被更新 /// </summary> /// <param name="dto">dto 或 Dictionary&lt;string, object&gt;</param> /// <returns></returns> IUpdate<T1> SetDto(object dto); /// <summary> /// lambda表达式条件,仅支持实体基础成员(不包含导航对象)<para></para> /// 若想使用导航对象,请使用 ISelect.ToUpdate() 方法 /// </summary> /// <param name="exp">lambda表达式条件</param> /// <returns></returns> IUpdate<T1> Where(Expression<Func<T1, bool>> exp); /// <summary> /// lambda表达式条件,仅支持实体基础成员(不包含导航对象)<para></para> /// 若想使用导航对象,请使用 ISelect.ToUpdate() 方法 /// </summary> /// <param name="condition">true 时生效</param> /// <param name="exp">lambda表达式条件</param> /// <returns></returns> IUpdate<T1> WhereIf(bool condition, Expression<Func<T1, bool>> exp); /// <summary> /// 原生sql语法条件,Where("id = ?id", new { id = 1 })<para></para> /// 提示:parms 参数还可以传 Dictionary&lt;string, object&gt; /// </summary> /// <param name="sql">sql语法条件</param> /// <param name="parms">参数</param> /// <returns></returns> IUpdate<T1> Where(string sql, object parms = null); /// <summary> /// 传入实体,将主键作为条件 /// </summary> /// <param name="item">实体</param> /// <returns></returns> IUpdate<T1> Where(T1 item); /// <summary> /// 传入实体集合,将主键作为条件 /// </summary> /// <param name="items">实体集合</param> /// <returns></returns> IUpdate<T1> Where(IEnumerable<T1> items); /// <summary> /// 传入动态条件,如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1} /// </summary> /// <param name="dywhere">主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合</param> /// <param name="not">是否标识为NOT</param> /// <returns></returns> IUpdate<T1> WhereDynamic(object dywhere, bool not = false); /// <summary> /// 禁用全局过滤功能,不传参数时将禁用所有 /// </summary> /// <param name="name">零个或多个过滤器名字</param> /// <returns></returns> IUpdate<T1> DisableGlobalFilter(params string[] name); /// <summary> /// 设置表名规则,可用于分库/分表,参数1:默认表名;返回值:新表名; /// </summary> /// <param name="tableRule"></param> /// <returns></returns> IUpdate<T1> AsTable(Func<string, string> tableRule); /// <summary> /// 动态Type,在使用 Update&lt;object&gt; 后使用本方法,指定实体类型 /// </summary> /// <param name="entityType"></param> /// <returns></returns> IUpdate<T1> AsType(Type entityType); /// <summary> /// 返回即将执行的SQL语句 /// </summary> /// <returns></returns> string ToSql(); /// <summary> /// 执行SQL语句,返回影响的行数 /// </summary> /// <returns></returns> int ExecuteAffrows(); /// <summary> /// 执行SQL语句,返回更新后的记录<para></para> /// 注意:此方法只有 Postgresql/SqlServer 有效果 /// </summary> /// <returns></returns> List<T1> ExecuteUpdated(); #if net40 #else Task<int> ExecuteAffrowsAsync(); Task<List<T1>> ExecuteUpdatedAsync(); #endif } }
39.248
140
0.541887
[ "MIT" ]
5118234/FreeSql
FreeSql/Interface/Curd/IUpdate.cs
11,470
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace p356___Upcast_an_entire_list { enum KindOfDuck { Mallard, Muscovy, Decoy, } }
15.066667
39
0.619469
[ "MIT" ]
head-first-csharp/second-edition
Chapter 8/p356 - Upcast an entire list/p356 - Upcast an entire list/KindOfDuck.cs
228
C#
using ConsoleApp2.Alibaba.Models; using System; using System.Threading.Tasks; namespace ConsoleApp2.Alibaba { public static class AlibabaDataCache { private readonly static AlibabaApi alibabaApi = new AlibabaApi(); private readonly static string cacheRootPath = @"Data\缓存\Alibaba\"; public static async Task<Base2Response<CategoryResult[]>> GetAllApiCategoryAsync() { var path = cacheRootPath; if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); var f = System.IO.Path.Combine(path, "AllApiCategorys.json"); if (System.IO.File.Exists(f)) return Newtonsoft.Json.JsonConvert.DeserializeObject<Base2Response<CategoryResult[]>>(System.IO.File.ReadAllText(f)); var sssddd = await alibabaApi.GetAllApiCategory(); System.IO.File.WriteAllText(f, Newtonsoft.Json.JsonConvert.SerializeObject(sssddd)); return sssddd; } public static async Task<BaseResponse<Datum[]>> ListPublicApiByCacheAsync() { var path = cacheRootPath; if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); var f = System.IO.Path.Combine(path, "PublicApis.json"); if (System.IO.File.Exists(f)) return Newtonsoft.Json.JsonConvert.DeserializeObject<BaseResponse<Datum[]>>(System.IO.File.ReadAllText(f)); var sssddd = await alibabaApi.ListPublicApiAsync(); System.IO.File.WriteAllText(f, Newtonsoft.Json.JsonConvert.SerializeObject(sssddd)); return sssddd; } public static async Task<BaseResponse<ArgumentData>> GetApiArgumentsByCacheAsync(string @namespace, string name, int version) { var path = System.IO.Path.Combine(cacheRootPath, @"ApiArguments\"); if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); var f = System.IO.Path.Combine(path, @namespace + "_" + name + "_" + version + ".json"); if (System.IO.File.Exists(f)) return Newtonsoft.Json.JsonConvert.DeserializeObject<BaseResponse<ArgumentData>>(System.IO.File.ReadAllText(f)); var sssddd = await alibabaApi.GetApiArguments(@namespace, name, version); System.IO.File.WriteAllText(f, Newtonsoft.Json.JsonConvert.SerializeObject(sssddd)); return sssddd; } public static async Task<Base2Response<ListByCategoryResult[]>> GetAopApiListByCategoryByCacheAsync(string aopApiCategory) { var path = System.IO.Path.Combine(cacheRootPath, @"ApiCategory\"); if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); var f = System.IO.Path.Combine(path, aopApiCategory + ".json"); if (System.IO.File.Exists(f)) return Newtonsoft.Json.JsonConvert.DeserializeObject<Base2Response<ListByCategoryResult[]>>(System.IO.File.ReadAllText(f)); var sssddd = await alibabaApi.GetAopApiListByCategory(aopApiCategory); System.IO.File.WriteAllText(f, Newtonsoft.Json.JsonConvert.SerializeObject(sssddd)); return sssddd; } public static async Task<Base2Response<DetailResult>> GetApiDetailByCacheAsync(string @namespace, string name, int version) { try { var path = System.IO.Path.Combine(cacheRootPath, @"ApiDetail\"); if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); var f = System.IO.Path.Combine(path, @namespace + "_" + name + "_" + version + ".json"); if (System.IO.File.Exists(f)) return Newtonsoft.Json.JsonConvert.DeserializeObject<Base2Response<DetailResult>>(System.IO.File.ReadAllText(f)); var sssddd = await alibabaApi.GetApiDetail(@namespace, name, version); System.IO.File.WriteAllText(f, Newtonsoft.Json.JsonConvert.SerializeObject(sssddd)); return sssddd; } catch (Exception ex) { return null; //throw; } } public static async Task<Base2Response<ModelInfoResult[]>> GetModelInfoByCacheAsync(string @namespace, string apiname, int version, string typeName) { try { var path = System.IO.Path.Combine(cacheRootPath, @"ModelInfo\"); if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); var f = System.IO.Path.Combine(path, @namespace + "_" + apiname + "_" + version + "_" + typeName + ".json"); if (System.IO.File.Exists(f)) return Newtonsoft.Json.JsonConvert.DeserializeObject<Base2Response<ModelInfoResult[]>>(System.IO.File.ReadAllText(f)); var sssddd = await alibabaApi.GetModelInfo(@namespace, apiname, version, typeName); System.IO.File.WriteAllText(f, Newtonsoft.Json.JsonConvert.SerializeObject(sssddd)); return sssddd; } catch (Exception ex) { return null; //throw; } } public static async Task<Datum[]> GetSolutionApiAndMessageListDetailByCacheAsync() { try { var path = cacheRootPath; if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); var f = System.IO.Path.Combine(path, "SolutionApiAndMessageListDetail.json"); if (System.IO.File.Exists(f)) return Newtonsoft.Json.JsonConvert.DeserializeObject<Datum[]>(System.IO.File.ReadAllText(f)); var sssddd = await alibabaApi.GetSolutionApiAndMessageListDetail(); System.IO.File.WriteAllText(f, Newtonsoft.Json.JsonConvert.SerializeObject(sssddd)); return sssddd; } catch (Exception ex) { return null; //throw; } } public static async Task<Base2Response<ddd.TopicGroupsResult[]>> GetTopicGroups() { var path = cacheRootPath; if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); var f = System.IO.Path.Combine(path, "GetTopicGroups.json"); if (System.IO.File.Exists(f)) return Newtonsoft.Json.JsonConvert.DeserializeObject<Base2Response<ddd.TopicGroupsResult[]>>(System.IO.File.ReadAllText(f)); var sssddd = await alibabaApi.GetTopicGroups(); System.IO.File.WriteAllText(f, Newtonsoft.Json.JsonConvert.SerializeObject(sssddd)); return sssddd; } public static async Task<Base2Response<ddd.TopicsByGroupAndOwnerResult[]>> GetTopicsByGroupAndOwner(string topicGroup) { var path = System.IO.Path.Combine(cacheRootPath, @"TopicsByGroupAndOwner\"); if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); var f = System.IO.Path.Combine(path, "GetTopicsByGroupAndOwner_" + topicGroup + ".json"); if (System.IO.File.Exists(f)) return Newtonsoft.Json.JsonConvert.DeserializeObject<Base2Response<ddd.TopicsByGroupAndOwnerResult[]>>(System.IO.File.ReadAllText(f)); var sssddd = await alibabaApi.GetTopicsByGroupAndOwner(topicGroup); System.IO.File.WriteAllText(f, Newtonsoft.Json.JsonConvert.SerializeObject(sssddd)); return sssddd; } public static async Task<Base2Response<ddd.TopicsByGroupAndOwnerResult[]>> GetAllTopics() { var path = cacheRootPath; if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); var f = System.IO.Path.Combine(path, "GetAllTopics.json"); if (System.IO.File.Exists(f)) return Newtonsoft.Json.JsonConvert.DeserializeObject<Base2Response<ddd.TopicsByGroupAndOwnerResult[]>>(System.IO.File.ReadAllText(f)); var sssddd = await alibabaApi.GetAllTopics(); System.IO.File.WriteAllText(f, Newtonsoft.Json.JsonConvert.SerializeObject(sssddd)); return sssddd; } public static async Task<Base2Response<ddd.TopicResult>> GetTopic(string topicId) { var path = System.IO.Path.Combine(cacheRootPath, @"Topic\"); if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path); var f = System.IO.Path.Combine(path, "GetTopic_" + topicId + ".json"); if (System.IO.File.Exists(f)) return Newtonsoft.Json.JsonConvert.DeserializeObject<Base2Response<ddd.TopicResult>>(System.IO.File.ReadAllText(f)); var sssddd = await alibabaApi.GetTopic(topicId); System.IO.File.WriteAllText(f, Newtonsoft.Json.JsonConvert.SerializeObject(sssddd)); return sssddd; } } }
53.063953
156
0.633286
[ "MIT" ]
mccj/AlibabaSDKFor1688
src/tools/AlibabaSDKFor1688GenerationApp/Alibaba/AlibabaDataCache.cs
9,133
C#
namespace IFPS.Factory.Domain.Enums { public enum EventTypeEnum { None = 0, NewAppointment = 1, AppointmentReminder = 2, NewFilesUploaded = 3, NewMessages = 4, ChangedOrderState = 5, OrderEvaluation = 6, Other = 1000 } }
18.588235
37
0.525316
[ "MIT" ]
encosoftware/ifps
ButorRevolutionWebAPI/src/backend/factory/IFPS.Factory.Domain/Enums/EventTypeEnum.cs
318
C#
using DotNetNuke.Collections; using DotNetNuke.Common; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Modules.Definitions; using DotNetNuke.UI.Modules; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Routing; namespace DotNetNuke.Web.Mvc.RazorPages.SDK.NETFramework.Routing { public class StandardModuleRoutingProvider : ModuleRoutingProvider { private const string ExcludedQueryStringParams = "tabid,mid,ctl,language,popup,action,controller"; private const string ExcludedRouteValues = "mid,ctl,popup"; public override string GenerateUrl(RouteValueDictionary routeValues, ModuleInstanceContext moduleContext) { //Look for a module control string controlKey = (routeValues.ContainsKey("ctl")) ? (string)routeValues["ctl"] : String.Empty; List<string> additionalParams = (from routeValue in routeValues where !ExcludedRouteValues.Split(',').ToList().Contains(routeValue.Key.ToLower()) select routeValue.Key + "=" + routeValue.Value) .ToList(); string url; if (String.IsNullOrEmpty(controlKey)) { additionalParams.Insert(0, "moduleId=" + moduleContext.Configuration.ModuleID); url = Globals.NavigateURL("", additionalParams.ToArray()); } else { url = moduleContext.EditUrl(String.Empty, String.Empty, controlKey, additionalParams.ToArray()); } return url; } public override RouteData GetRouteData(HttpContextBase httpContext, ModuleControlInfo moduleControl) { var assemblyName = moduleControl.ControlTitle; var segments = moduleControl.ControlSrc.Replace(".razorpages", "").Split('/'); string routeNamespace = String.Empty; string routeModuleName; string routePageName; if (segments.Length == 3) { routeNamespace = segments[0]; routeModuleName = segments[1]; routePageName = segments[2]; } else { routeModuleName = segments[0]; routePageName = segments[1]; } var pageName = (httpContext == null) ? routePageName : httpContext.Request.QueryString.GetValueOrDefault("action", routePageName); var moduleName = (httpContext == null) ? routeModuleName : httpContext.Request.QueryString.GetValueOrDefault("controller", routeModuleName); var routeData = new RouteData(); routeData.Values.Add("module", moduleName); routeData.Values.Add("page", pageName); routeData.Values.Add("assembly", assemblyName); var moduleDef = ModuleDefinitionController.GetModuleDefinitionByID(moduleControl.ModuleDefID); var desktopModule = DesktopModuleController.GetDesktopModule(moduleDef.DesktopModuleID, -1); routeData.Values.Add("page-path", $"~/DesktopModules/MVC/{desktopModule.FolderName}/Pages/{pageName}.cshtml"); if (httpContext != null) { foreach (var param in httpContext.Request.QueryString.AllKeys) { if (!ExcludedQueryStringParams.Split(',').ToList().Contains(param.ToLower())) { routeData.Values.Add(param, httpContext.Request.QueryString[param]); } } } if (!String.IsNullOrEmpty(routeNamespace)) { routeData.DataTokens.Add("namespaces", new string[] { routeNamespace }); } return routeData; } } }
41.536842
152
0.594019
[ "MIT" ]
ahoefling/DnnRazorPagesSDK
src/DotNetNuke.Web.Mvc.RazorPages.SDK.NETFramework/Routing/StandardModuleRoutingProvider.cs
3,948
C#
/* Copyright (c) 2022 bradson * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ using System.Diagnostics; namespace BetterLog; /// <summary> /// Log Functions that only do something when compiling in Debug Mode /// </summary> public static class DebugLog { [Conditional("DEBUG")] public static void Message(string text) => Log.Message(text); [Conditional("DEBUG")] public static void Warning(string text) => Log.Warning(text); [Conditional("DEBUG")] public static void Error(string text) => Log.Error(text); }
30.727273
70
0.718935
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
bbradson/BetterLog
Source/DebugLog.cs
678
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Titanfall2_SkinTool.Titanfall2.WeaponData.Default.SubmachineGun; namespace Titanfall2_SkinTool.Titanfall2.WeaponData { public class WeaponDataControl { public string[,] FilePath = new string[1, 4]; //col,nml,gls,spc,ilm,ao,cav //2为2048x2048,1为1024x1024,0为512x512 public WeaponDataControl(string WeaponName, int imagecheck) { //单独为专注的弹夹写判断emmm。。。。 if (WeaponName.Contains("Devotion_clip") && WeaponName.Contains("Default")) { Default.LightMachineGun.Devotion devotion_clip = new Default.LightMachineGun.Devotion(); if (WeaponName.Contains("col")) { int i = 0; FilePath[0, i] = devotion_clip.Devotion_clip_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_col[imagecheck].seeklength); } if (WeaponName.Contains("nml")) { int i = 0; FilePath[0, i] = devotion_clip.Devotion_clip_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_nml[imagecheck].seeklength); } if (WeaponName.Contains("gls")) { int i = 0; FilePath[0, i] = devotion_clip.Devotion_clip_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_gls[imagecheck].seeklength); } if (WeaponName.Contains("spc")) { int i = 0; FilePath[0, i] = devotion_clip.Devotion_clip_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_spc[imagecheck].seeklength); } if (WeaponName.Contains("ilm")) { int i = 0; FilePath[0, i] = devotion_clip.Devotion_clip_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_ilm[imagecheck].seeklength); } if (WeaponName.Contains("ao")) { int i = 0; FilePath[0, i] = devotion_clip.Devotion_clip_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_ao[imagecheck].seeklength); } if (WeaponName.Contains("cav")) { int i = 0; FilePath[0, i] = devotion_clip.Devotion_clip_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_cav[imagecheck].seeklength); } return; } if (WeaponName.Contains("Devotion_clip") && WeaponName.Contains("Skin31")) { Default.LightMachineGun.Devotion devotion_clip = new Default.LightMachineGun.Devotion(); if (WeaponName.Contains("col")) { int i = 0; FilePath[0, i] = devotion_clip.Devotion_clip_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_col[imagecheck].seeklength); } if (WeaponName.Contains("nml")) { int i = 0; FilePath[0, i] = devotion_clip.Devotion_clip_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_nml[imagecheck].seeklength); } if (WeaponName.Contains("gls")) { int i = 0; FilePath[0, i] = devotion_clip.Devotion_clip_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_gls[imagecheck].seeklength); } if (WeaponName.Contains("spc")) { int i = 0; FilePath[0, i] = devotion_clip.Devotion_clip_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_spc[imagecheck].seeklength); } if (WeaponName.Contains("ilm")) { int i = 0; FilePath[0, i] = devotion_clip.Devotion_clip_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_ilm[imagecheck].seeklength); } if (WeaponName.Contains("ao")) { int i = 0; FilePath[0, i] = devotion_clip.Devotion_clip_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_ao[imagecheck].seeklength); } if (WeaponName.Contains("cav")) { int i = 0; FilePath[0, i] = devotion_clip.Devotion_clip_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion_clip.Devotion_clip_cav[imagecheck].seeklength); } return; } string s = WeaponName; int toname = s.LastIndexOf("\\")+1; string str = s.Substring(toname, s.Length - toname); toname = str.IndexOf("_"); string temp = str.Substring(toname, str.Length - toname); s = str.Replace(temp, ""); if (str.Contains("Default")) { switch (s) { //冲锋枪 case "CAR": Default.SubmachineGun.CAR car = new Default.SubmachineGun.CAR(); //col,nml,gls,spc,ilm,ao,cav if (str.Contains("col")) { int i = 0; FilePath[0, i] = car.CAR_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(car.CAR_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(car.CAR_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(car.CAR_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = car.CAR_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(car.CAR_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(car.CAR_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(car.CAR_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = car.CAR_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(car.CAR_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(car.CAR_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(car.CAR_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = car.CAR_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(car.CAR_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(car.CAR_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(car.CAR_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = car.CAR_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(car.CAR_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(car.CAR_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(car.CAR_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = car.CAR_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(car.CAR_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(car.CAR_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(car.CAR_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = car.CAR_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(car.CAR_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(car.CAR_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(car.CAR_cav[imagecheck].seeklength); } break; case "Alternator": Default.SubmachineGun.Alternator alternator = new Default.SubmachineGun.Alternator(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = alternator.Alternator_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(alternator.Alternator_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(alternator.Alternator_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(alternator.Alternator_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = alternator.Alternator_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(alternator.Alternator_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(alternator.Alternator_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(alternator.Alternator_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = alternator.Alternator_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(alternator.Alternator_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(alternator.Alternator_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(alternator.Alternator_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = alternator.Alternator_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(alternator.Alternator_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(alternator.Alternator_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(alternator.Alternator_spc[imagecheck].seeklength); } //转换者没有ilm if (str.Contains("ao")) { int i = 0; FilePath[0, i] = alternator.Alternator_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(alternator.Alternator_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(alternator.Alternator_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(alternator.Alternator_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = alternator.Alternator_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(alternator.Alternator_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(alternator.Alternator_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(alternator.Alternator_cav[imagecheck].seeklength); } break; case "R97": Default.SubmachineGun.R97 r97 = new Default.SubmachineGun.R97(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = r97.R97_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r97.R97_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r97.R97_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r97.R97_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = r97.R97_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r97.R97_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r97.R97_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r97.R97_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = r97.R97_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r97.R97_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r97.R97_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r97.R97_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = r97.R97_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r97.R97_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r97.R97_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r97.R97_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = r97.R97_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r97.R97_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r97.R97_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r97.R97_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = r97.R97_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r97.R97_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r97.R97_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r97.R97_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = r97.R97_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r97.R97_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r97.R97_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r97.R97_cav[imagecheck].seeklength); } break; case "Volt": Default.SubmachineGun.Volt volt = new Default.SubmachineGun.Volt(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = volt.Volt_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(volt.Volt_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(volt.Volt_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(volt.Volt_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = volt.Volt_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(volt.Volt_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(volt.Volt_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(volt.Volt_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = volt.Volt_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(volt.Volt_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(volt.Volt_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(volt.Volt_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = volt.Volt_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(volt.Volt_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(volt.Volt_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(volt.Volt_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = volt.Volt_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(volt.Volt_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(volt.Volt_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(volt.Volt_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = volt.Volt_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(volt.Volt_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(volt.Volt_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(volt.Volt_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = volt.Volt_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(volt.Volt_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(volt.Volt_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(volt.Volt_cav[imagecheck].seeklength); } break; //狙击步枪 case "DoubleTake": Default.Sniper.DoubleTake doubletake = new Default.Sniper.DoubleTake(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = doubletake.DoubleTake_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(doubletake.DoubleTake_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(doubletake.DoubleTake_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(doubletake.DoubleTake_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = doubletake.DoubleTake_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(doubletake.DoubleTake_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(doubletake.DoubleTake_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(doubletake.DoubleTake_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = doubletake.DoubleTake_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(doubletake.DoubleTake_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(doubletake.DoubleTake_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(doubletake.DoubleTake_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = doubletake.DoubleTake_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(doubletake.DoubleTake_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(doubletake.DoubleTake_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(doubletake.DoubleTake_spc[imagecheck].seeklength); } //双击没有ilm if (str.Contains("ao")) { int i = 0; FilePath[0, i] = doubletake.DoubleTake_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(doubletake.DoubleTake_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(doubletake.DoubleTake_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(doubletake.DoubleTake_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = doubletake.DoubleTake_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(doubletake.DoubleTake_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(doubletake.DoubleTake_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(doubletake.DoubleTake_cav[imagecheck].seeklength); } break; case "Kraber": Default.Sniper.Kraber kraber = new Default.Sniper.Kraber(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = kraber.Kraber_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = kraber.Kraber_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = kraber.Kraber_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = kraber.Kraber_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = kraber.Kraber_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = kraber.Kraber_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = kraber.Kraber_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(kraber.Kraber_cav[imagecheck].seeklength); } break; case "LongbowDMR": Default.Sniper.LongbowDMR longbowdmr = new Default.Sniper.LongbowDMR(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = longbowdmr.LongbowDMR_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(longbowdmr.LongbowDMR_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(longbowdmr.LongbowDMR_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(longbowdmr.LongbowDMR_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = longbowdmr.LongbowDMR_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(longbowdmr.LongbowDMR_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(longbowdmr.LongbowDMR_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(longbowdmr.LongbowDMR_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = longbowdmr.LongbowDMR_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(longbowdmr.LongbowDMR_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(longbowdmr.LongbowDMR_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(longbowdmr.LongbowDMR_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = longbowdmr.LongbowDMR_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(longbowdmr.LongbowDMR_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(longbowdmr.LongbowDMR_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(longbowdmr.LongbowDMR_spc[imagecheck].seeklength); } //DMR没有ilm if (str.Contains("ao")) { int i = 0; FilePath[0, i] = longbowdmr.LongbowDMR_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(longbowdmr.LongbowDMR_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(longbowdmr.LongbowDMR_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(longbowdmr.LongbowDMR_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = longbowdmr.LongbowDMR_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(longbowdmr.LongbowDMR_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(longbowdmr.LongbowDMR_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(longbowdmr.LongbowDMR_cav[imagecheck].seeklength); } break; //散弹枪 case "EVA8": Default.Shotgun.EVA8 eva8 = new Default.Shotgun.EVA8(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = eva8.EVA8_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = eva8.EVA8_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = eva8.EVA8_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = eva8.EVA8_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = eva8.EVA8_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = eva8.EVA8_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = eva8.EVA8_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(eva8.EVA8_cav[imagecheck].seeklength); } break; case "Mastiff": Default.Shotgun.Mastiff mastiff = new Default.Shotgun.Mastiff(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = mastiff.Mastiff_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = mastiff.Mastiff_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = mastiff.Mastiff_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = mastiff.Mastiff_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = mastiff.Mastiff_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = mastiff.Mastiff_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = mastiff.Mastiff_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mastiff.Mastiff_cav[imagecheck].seeklength); } break; //手枪类只有两种分辨率,1024和512 case "Mozambique": Default.Pistol.Mozambique mozambique = new Default.Pistol.Mozambique(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = mozambique.Mozambique_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mozambique.Mozambique_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mozambique.Mozambique_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mozambique.Mozambique_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = mozambique.Mozambique_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mozambique.Mozambique_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mozambique.Mozambique_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mozambique.Mozambique_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = mozambique.Mozambique_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mozambique.Mozambique_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mozambique.Mozambique_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mozambique.Mozambique_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = mozambique.Mozambique_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mozambique.Mozambique_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mozambique.Mozambique_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mozambique.Mozambique_spc[imagecheck].seeklength); } //莫三比克没有ilm if (str.Contains("ao")) { int i = 0; FilePath[0, i] = mozambique.Mozambique_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mozambique.Mozambique_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mozambique.Mozambique_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mozambique.Mozambique_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = mozambique.Mozambique_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mozambique.Mozambique_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mozambique.Mozambique_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mozambique.Mozambique_cav[imagecheck].seeklength); } break; case "P2016": Default.Pistol.P2016 p2016 = new Default.Pistol.P2016(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = p2016.P2016_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(p2016.P2016_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(p2016.P2016_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(p2016.P2016_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = p2016.P2016_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(p2016.P2016_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(p2016.P2016_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(p2016.P2016_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = p2016.P2016_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(p2016.P2016_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(p2016.P2016_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(p2016.P2016_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = p2016.P2016_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(p2016.P2016_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(p2016.P2016_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(p2016.P2016_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = p2016.P2016_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(p2016.P2016_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(p2016.P2016_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(p2016.P2016_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = p2016.P2016_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(p2016.P2016_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(p2016.P2016_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(p2016.P2016_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = p2016.P2016_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(p2016.P2016_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(p2016.P2016_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(p2016.P2016_cav[imagecheck].seeklength); } break; case "RE45": Default.Pistol.RE45 re45 = new Default.Pistol.RE45(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = re45.RE45_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(re45.RE45_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(re45.RE45_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(re45.RE45_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = re45.RE45_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(re45.RE45_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(re45.RE45_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(re45.RE45_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = re45.RE45_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(re45.RE45_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(re45.RE45_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(re45.RE45_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = re45.RE45_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(re45.RE45_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(re45.RE45_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(re45.RE45_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = re45.RE45_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(re45.RE45_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(re45.RE45_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(re45.RE45_ilm[imagecheck].seeklength); }//RE45只有一个分辨率.....也许以后会有BUG? if (str.Contains("ao")) { int i = 0; FilePath[0, i] = re45.RE45_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(re45.RE45_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(re45.RE45_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(re45.RE45_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = re45.RE45_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(re45.RE45_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(re45.RE45_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(re45.RE45_cav[imagecheck].seeklength); } break; case "SmartPistol": Default.Pistol.SmartPistol smartpistol = new Default.Pistol.SmartPistol(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = smartpistol.SmartPistol_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = smartpistol.SmartPistol_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = smartpistol.SmartPistol_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = smartpistol.SmartPistol_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = smartpistol.SmartPistol_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = smartpistol.SmartPistol_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = smartpistol.SmartPistol_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(smartpistol.SmartPistol_cav[imagecheck].seeklength); } break; case "Wingman": Default.Pistol.Wingman wingman = new Default.Pistol.Wingman(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = wingman.Wingman_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = wingman.Wingman_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = wingman.Wingman_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = wingman.Wingman_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = wingman.Wingman_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = wingman.Wingman_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = wingman.Wingman_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(wingman.Wingman_cav[imagecheck].seeklength); } break; case "WingmanElite": Default.Pistol.WingmanElite wingmanelite = new Default.Pistol.WingmanElite(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = wingmanelite.WingmanElite_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = wingmanelite.WingmanElite_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = wingmanelite.WingmanElite_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = wingmanelite.WingmanElite_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = wingmanelite.WingmanElite_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = wingmanelite.WingmanElite_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = wingmanelite.WingmanElite_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(wingmanelite.WingmanElite_cav[imagecheck].seeklength); } break; //手枪类结束 //轻机枪 case "Devotion": Default.LightMachineGun.Devotion devotion = new Default.LightMachineGun.Devotion(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = devotion.Devotion_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion.Devotion_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion.Devotion_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion.Devotion_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = devotion.Devotion_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion.Devotion_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion.Devotion_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion.Devotion_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = devotion.Devotion_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion.Devotion_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion.Devotion_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion.Devotion_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = devotion.Devotion_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion.Devotion_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion.Devotion_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion.Devotion_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = devotion.Devotion_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion.Devotion_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion.Devotion_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion.Devotion_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = devotion.Devotion_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(devotion.Devotion_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(devotion.Devotion_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(devotion.Devotion_ao[imagecheck].seeklength); } //专注没有cav break; case "LSTAR": Default.LightMachineGun.LSTAR lstar = new Default.LightMachineGun.LSTAR(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = lstar.LSTAR_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = lstar.LSTAR_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = lstar.LSTAR_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = lstar.LSTAR_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = lstar.LSTAR_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = lstar.LSTAR_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = lstar.LSTAR_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(lstar.LSTAR_cav[imagecheck].seeklength); } break; case "Spitfire": Default.LightMachineGun.Spitfire spitfire = new Default.LightMachineGun.Spitfire(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = spitfire.Spitfire_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = spitfire.Spitfire_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = spitfire.Spitfire_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = spitfire.Spitfire_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = spitfire.Spitfire_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = spitfire.Spitfire_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = spitfire.Spitfire_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(spitfire.Spitfire_cav[imagecheck].seeklength); } break; //榴弹枪 case "ColdWar": Default.Grenadier.ColdWar coldwar = new Default.Grenadier.ColdWar(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = coldwar.ColdWar_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = coldwar.ColdWar_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = coldwar.ColdWar_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = coldwar.ColdWar_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = coldwar.ColdWar_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = coldwar.ColdWar_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = coldwar.ColdWar_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(coldwar.ColdWar_cav[imagecheck].seeklength); } break; case "EPG": Default.Grenadier.EPG epg = new Default.Grenadier.EPG(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = epg.EPG_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(epg.EPG_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(epg.EPG_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(epg.EPG_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = epg.EPG_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(epg.EPG_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(epg.EPG_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(epg.EPG_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = epg.EPG_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(epg.EPG_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(epg.EPG_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(epg.EPG_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = epg.EPG_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(epg.EPG_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(epg.EPG_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(epg.EPG_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = epg.EPG_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(epg.EPG_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(epg.EPG_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(epg.EPG_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = epg.EPG_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(epg.EPG_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(epg.EPG_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(epg.EPG_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = epg.EPG_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(epg.EPG_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(epg.EPG_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(epg.EPG_cav[imagecheck].seeklength); } break; case "SMR": Default.Grenadier.SMR smr = new Default.Grenadier.SMR(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = smr.SMR_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(smr.SMR_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(smr.SMR_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(smr.SMR_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = smr.SMR_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(smr.SMR_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(smr.SMR_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(smr.SMR_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = smr.SMR_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(smr.SMR_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(smr.SMR_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(smr.SMR_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = smr.SMR_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(smr.SMR_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(smr.SMR_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(smr.SMR_spc[imagecheck].seeklength); } //SMR没有ilm if (str.Contains("ao")) { int i = 0; FilePath[0, i] = smr.SMR_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(smr.SMR_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(smr.SMR_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(smr.SMR_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = smr.SMR_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(smr.SMR_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(smr.SMR_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(smr.SMR_cav[imagecheck].seeklength); } break; case "Softball": Default.Grenadier.Softball softball = new Default.Grenadier.Softball(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = softball.Softball_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(softball.Softball_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(softball.Softball_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(softball.Softball_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = softball.Softball_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(softball.Softball_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(softball.Softball_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(softball.Softball_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = softball.Softball_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(softball.Softball_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(softball.Softball_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(softball.Softball_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = softball.Softball_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(softball.Softball_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(softball.Softball_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(softball.Softball_spc[imagecheck].seeklength); } //垒球没有ilm if (str.Contains("ao")) { int i = 0; FilePath[0, i] = softball.Softball_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(softball.Softball_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(softball.Softball_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(softball.Softball_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = softball.Softball_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(softball.Softball_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(softball.Softball_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(softball.Softball_cav[imagecheck].seeklength); } break; //突击步枪 case "G2A5": Default.AssaultRifle.G2A5 g2a5 = new Default.AssaultRifle.G2A5(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = g2a5.G2A5_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = g2a5.G2A5_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = g2a5.G2A5_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = g2a5.G2A5_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = g2a5.G2A5_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = g2a5.G2A5_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = g2a5.G2A5_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(g2a5.G2A5_cav[imagecheck].seeklength); } break; case "HemlokBFR": Default.AssaultRifle.HemlokBFR hemlokbfr = new Default.AssaultRifle.HemlokBFR(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = hemlokbfr.HemlokBFR_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = hemlokbfr.HemlokBFR_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = hemlokbfr.HemlokBFR_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = hemlokbfr.HemlokBFR_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = hemlokbfr.HemlokBFR_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = hemlokbfr.HemlokBFR_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = hemlokbfr.HemlokBFR_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(hemlokbfr.HemlokBFR_cav[imagecheck].seeklength); } break; case "R101": Default.AssaultRifle.R101 r101 = new Default.AssaultRifle.R101(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = r101.R101_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r101.R101_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r101.R101_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r101.R101_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = r101.R101_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r101.R101_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r101.R101_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r101.R101_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = r101.R101_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r101.R101_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r101.R101_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r101.R101_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = r101.R101_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r101.R101_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r101.R101_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r101.R101_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = r101.R101_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r101.R101_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r101.R101_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r101.R101_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = r101.R101_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r101.R101_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r101.R101_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r101.R101_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = r101.R101_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r101.R101_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r101.R101_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r101.R101_cav[imagecheck].seeklength); } break; case "R201": Default.AssaultRifle.R201 r201 = new Default.AssaultRifle.R201(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = r201.R201_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r201.R201_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r201.R201_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r201.R201_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = r201.R201_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r201.R201_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r201.R201_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r201.R201_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = r201.R201_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r201.R201_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r201.R201_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r201.R201_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = r201.R201_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r201.R201_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r201.R201_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r201.R201_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = r201.R201_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r201.R201_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r201.R201_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r201.R201_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = r201.R201_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r201.R201_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r201.R201_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r201.R201_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = r201.R201_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(r201.R201_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(r201.R201_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(r201.R201_cav[imagecheck].seeklength); } break; case "V47Flatline": Default.AssaultRifle.V47Flatline v47flatline = new Default.AssaultRifle.V47Flatline(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = v47flatline.V47Flatline_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = v47flatline.V47Flatline_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = v47flatline.V47Flatline_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = v47flatline.V47Flatline_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = v47flatline.V47Flatline_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = v47flatline.V47Flatline_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = v47flatline.V47Flatline_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(v47flatline.V47Flatline_cav[imagecheck].seeklength); } break; //反泰坦武器 case "Archer": Default.AntiTitan.Archer archer = new Default.AntiTitan.Archer(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = archer.Archer_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(archer.Archer_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(archer.Archer_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(archer.Archer_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = archer.Archer_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(archer.Archer_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(archer.Archer_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(archer.Archer_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = archer.Archer_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(archer.Archer_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(archer.Archer_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(archer.Archer_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = archer.Archer_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(archer.Archer_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(archer.Archer_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(archer.Archer_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = archer.Archer_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(archer.Archer_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(archer.Archer_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(archer.Archer_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = archer.Archer_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(archer.Archer_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(archer.Archer_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(archer.Archer_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = archer.Archer_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(archer.Archer_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(archer.Archer_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(archer.Archer_cav[imagecheck].seeklength); } break; case "ChargeRifle": Default.AntiTitan.ChargeRifle chargerifle = new Default.AntiTitan.ChargeRifle(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = chargerifle.ChargeRifle_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = chargerifle.ChargeRifle_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = chargerifle.ChargeRifle_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = chargerifle.ChargeRifle_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = chargerifle.ChargeRifle_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = chargerifle.ChargeRifle_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = chargerifle.ChargeRifle_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(chargerifle.ChargeRifle_cav[imagecheck].seeklength); } break; case "MGL": Default.AntiTitan.MGL mgl = new Default.AntiTitan.MGL(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = mgl.MGL_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mgl.MGL_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mgl.MGL_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mgl.MGL_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = mgl.MGL_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mgl.MGL_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mgl.MGL_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mgl.MGL_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = mgl.MGL_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mgl.MGL_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mgl.MGL_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mgl.MGL_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = mgl.MGL_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mgl.MGL_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mgl.MGL_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mgl.MGL_spc[imagecheck].seeklength); } //磁能榴弹没有ilm if (str.Contains("ao")) { int i = 0; FilePath[0, i] = mgl.MGL_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mgl.MGL_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mgl.MGL_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mgl.MGL_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = mgl.MGL_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(mgl.MGL_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(mgl.MGL_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(mgl.MGL_cav[imagecheck].seeklength); } break; case "Thunderbolt": Default.AntiTitan.Thunderbolt thunderbolt = new Default.AntiTitan.Thunderbolt(); if (str.Contains("col")) { int i = 0; FilePath[0, i] = thunderbolt.Thunderbolt_col[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_col[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_col[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_col[imagecheck].seeklength); } if (str.Contains("nml")) { int i = 0; FilePath[0, i] = thunderbolt.Thunderbolt_nml[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_nml[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_nml[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_nml[imagecheck].seeklength); } if (str.Contains("gls")) { int i = 0; FilePath[0, i] = thunderbolt.Thunderbolt_gls[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_gls[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_gls[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_gls[imagecheck].seeklength); } if (str.Contains("spc")) { int i = 0; FilePath[0, i] = thunderbolt.Thunderbolt_spc[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_spc[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_spc[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_spc[imagecheck].seeklength); } if (str.Contains("ilm")) { int i = 0; FilePath[0, i] = thunderbolt.Thunderbolt_ilm[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_ilm[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_ilm[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_ilm[imagecheck].seeklength); } if (str.Contains("ao")) { int i = 0; FilePath[0, i] = thunderbolt.Thunderbolt_ao[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_ao[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_ao[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_ao[imagecheck].seeklength); } if (str.Contains("cav")) { int i = 0; FilePath[0, i] = thunderbolt.Thunderbolt_cav[imagecheck].name; i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_cav[imagecheck].seek); i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_cav[imagecheck].length); i++; FilePath[0, i] = Convert.ToString(thunderbolt.Thunderbolt_cav[imagecheck].seeklength); } break; default: break; } } else if (WeaponName.Contains("Skin31")) { //等待RPAK文件开发中... //To do... } } } }
56.249142
116
0.394427
[ "MIT" ]
BigSpice/NorthStar-Mod-Manager-Ext-1
LEGACY_NORTHSTAR_INSTALLER/Titanfall2_Requisite/WeaponData/WeaponDataControl.cs
147,683
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace MetroRadiance.UI.Controls { /// <summary> /// 未入力時にプロンプトを表示できる <see cref="ComboBox"/> を表します。 /// </summary> [TemplateVisualState(Name = "Empty", GroupName = "TextStates")] [TemplateVisualState(Name = "NotEmpty", GroupName = "TextStates")] public class PromptComboBox : ComboBox { static PromptComboBox() { DefaultStyleKeyProperty.OverrideMetadata(typeof(PromptComboBox), new FrameworkPropertyMetadata(typeof(PromptComboBox))); } public PromptComboBox() { this.UpdateTextStates(true); this.SelectionChanged += (sender, e) => this.UpdateTextStates(true); this.GotKeyboardFocus += (sender, e) => this.UpdateTextStates(true); //this.KeyDown += (sender, e) => this.UpdateTextStates(true); //this.KeyUp += (sender, e) => this.UpdateTextStates(true); } #region Prompt dependency property public static readonly DependencyProperty PromptProperty = DependencyProperty.Register( nameof(Prompt), typeof(string), typeof(PromptComboBox), new UIPropertyMetadata("")); public string Prompt { get => (string)this.GetValue(PromptProperty); set => this.SetValue(PromptProperty, value); } #endregion #region PromptBrush dependency property public static readonly DependencyProperty PromptBrushProperty = DependencyProperty.Register( nameof(PromptBrush), typeof(Brush), typeof(PromptComboBox), new UIPropertyMetadata(Brushes.Gray)); public Brush PromptBrush { get => (Brush)this.GetValue(PromptBrushProperty); set => this.SetValue(PromptBrushProperty, value); } #endregion #region EditableText dependency property public static readonly DependencyProperty EditableTextProperty = DependencyProperty.Register( nameof(EditableText), typeof(string), typeof(PromptComboBox), new UIPropertyMetadata("", EditableTextChangedCallback)); private static void EditableTextChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { var instance = (PromptComboBox)d; instance.UpdateTextStates(true); } public string EditableText { get => (string)this.GetValue(EditableTextProperty); set => this.SetValue(EditableTextProperty, value); } #endregion private void UpdateTextStates(bool useTransitions) { VisualStateManager.GoToState(this, string.IsNullOrEmpty(this.EditableText) ? "Empty" : "NotEmpty", useTransitions); } } }
31.876289
132
0.617723
[ "MIT" ]
Grabacr07/ResinTimer
src/MetroRadiance/MetroRadiance/UI/Controls/PromptComboBox.cs
3,138
C#
using System.Threading.Tasks; namespace Log73.ExtensionMethod { public static class DumpExtensionMethods { /// <summary> /// Logs the object to console using the <see cref="LogType"/> specified in <see cref="Log73Options.DumpLogType"/>. /// </summary> public static void Dump(this object obj) => Console.Log(Console.Options.DumpMessageType, obj); /// <summary> /// Logs the object to console using the <see cref="MessageTypes.Info"/> <see cref="MessageType"/>. /// </summary> public static void DumpInfo(this object obj) => Console.Log(MessageTypes.Info, obj); /// <summary> /// Logs the object to console using the <see cref="MessageTypes.Warn"/> <see cref="MessageType"/>. /// </summary> public static void DumpWarn(this object obj) => Console.Log(MessageTypes.Warn, obj); /// <summary> /// Logs the object to console using the <see cref="MessageTypes.Error"/> <see cref="MessageType"/>. /// </summary> public static void DumpError(this object obj) => Console.Log(MessageTypes.Error, obj); /// <summary> /// Logs the object to console using the <see cref="MessageTypes.Debug"/> <see cref="MessageType"/>. /// </summary> public static void DumpDebug(this object obj) => Console.Log(MessageTypes.Debug, obj); /// <inheritdoc cref="Log73.Console.Task(string, Task)"/> public static void DumpTask(this Task task, string name) => Console.Task(name, task); } }
43.756757
123
0.605312
[ "MIT" ]
Jan0660/Log73
src/Log73/ExtensionMethod/Dump.cs
1,621
C#
using System.Windows.Controls; namespace ArcGISSilverlightSDK { public partial class AddGraphicsXAML : UserControl { public AddGraphicsXAML() { InitializeComponent(); } } }
17.153846
54
0.623318
[ "Apache-2.0" ]
Esri/arcgis-samples-silverlight
src/ArcGISSilverlightSDK/Graphics/AddGraphicsXAML.xaml.cs
225
C#
using System; public static class SavingsAccount { public static float InterestRate(decimal balance) { if (balance < 0.0m) return -3.213f; if (balance < 1000.0m) return 0.5f; if (balance < 5000.0m) return 1.621f; return 2.475f; } private static decimal AnnualYield(decimal balance) { var multiplier = (decimal)InterestRate(balance) / 100; return Math.Abs(balance) * multiplier; } public static decimal AnnualBalanceUpdate(decimal balance) => balance + AnnualYield(balance); public static int YearsBeforeDesiredBalance(decimal balance, decimal targetBalance) { var accumulatingBalance = balance; var years = 0; while (accumulatingBalance < targetBalance) { accumulatingBalance = AnnualBalanceUpdate(accumulatingBalance); years++; } return years; } }
23.439024
87
0.608741
[ "MIT" ]
ErikSchierboomTest/v3
languages/csharp/exercises/concept/floating-point-numbers/.meta/Example.cs
961
C#
using System; using CompanyName.MyMeetings.Modules.Meetings.Application.Configuration.Processing.InternalCommands; using Newtonsoft.Json; namespace CompanyName.MyMeetings.Modules.Meetings.Application.MeetingGroupProposals.AcceptMeetingGroupProposal { internal class AcceptMeetingGroupProposalCommand : InternalCommandBase { public Guid MeetingGroupProposalId { get; } [JsonConstructor] internal AcceptMeetingGroupProposalCommand(Guid id, Guid meetingGroupProposalId) : base(id) { this.MeetingGroupProposalId = meetingGroupProposalId; } } }
35.647059
110
0.768977
[ "MIT" ]
Bardr/modular-monolith-with-ddd
src/Modules/Meetings/Application/MeetingGroupProposals/AcceptMeetingGroupProposal/AcceptMeetingGroupProposalCommand.cs
608
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; namespace Microsoft.AspNetCore.Mvc.DataAnnotations; public class DataTypeClientModelValidatorProviderTest { private readonly IModelMetadataProvider _metadataProvider = TestModelMetadataProvider.CreateDefaultProvider(); [Theory] [InlineData(typeof(float))] [InlineData(typeof(double))] [InlineData(typeof(decimal))] [InlineData(typeof(float?))] [InlineData(typeof(double?))] [InlineData(typeof(decimal?))] public void CreateValidators_GetsNumericValidator_ForNumericType(Type modelType) { // Arrange var provider = new NumericClientModelValidatorProvider(); var metadata = _metadataProvider.GetMetadataForType(modelType); var providerContext = new ClientValidatorProviderContext(metadata, GetValidatorItems(metadata)); // Act provider.CreateValidators(providerContext); // Assert var validatorItem = Assert.Single(providerContext.Results); Assert.IsType<NumericClientModelValidator>(validatorItem.Validator); } [Fact] public void CreateValidators_DoesNotAddDuplicateValidators() { // Arrange var provider = new NumericClientModelValidatorProvider(); var metadata = _metadataProvider.GetMetadataForType(typeof(float)); var items = GetValidatorItems(metadata); var expectedValidatorItem = new ClientValidatorItem { Validator = new NumericClientModelValidator(), IsReusable = true }; items.Add(expectedValidatorItem); var providerContext = new ClientValidatorProviderContext(metadata, items); // Act provider.CreateValidators(providerContext); // Assert var validatorItem = Assert.Single(providerContext.Results); Assert.Same(expectedValidatorItem.Validator, validatorItem.Validator); } [Theory] [InlineData(typeof(int))] [InlineData(typeof(short))] [InlineData(typeof(byte))] [InlineData(typeof(uint?))] [InlineData(typeof(long?))] [InlineData(typeof(string))] [InlineData(typeof(DateTime))] public void CreateValidators_DoesNotGetsNumericValidator_ForUnsupportedTypes(Type modelType) { // Arrange var provider = new NumericClientModelValidatorProvider(); var metadata = _metadataProvider.GetMetadataForType(modelType); var providerContext = new ClientValidatorProviderContext(metadata, GetValidatorItems(metadata)); // Act provider.CreateValidators(providerContext); // Assert Assert.Empty(providerContext.Results); } private IList<ClientValidatorItem> GetValidatorItems(ModelMetadata metadata) { return metadata.ValidatorMetadata.Select(v => new ClientValidatorItem(v)).ToList(); } }
34.465909
114
0.714144
[ "MIT" ]
3ejki/aspnetcore
src/Mvc/Mvc.DataAnnotations/test/DataTypeClientModelValidatorProviderTest.cs
3,033
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PIM_4_PERIODO.Model { class cadveiculos { } }
14.307692
33
0.741935
[ "Apache-2.0" ]
Caiocesar173/PIM_4_Periodo
PIM 4 PERIODO/Model/cadveiculos.cs
188
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.RecoveryServices.V20210201Preview.Outputs { [OutputType] public sealed class MabProtectionPolicyResponse { /// <summary> /// This property will be used as the discriminator for deciding the specific types in the polymorphic chain of types. /// Expected value is 'MAB'. /// </summary> public readonly string BackupManagementType; /// <summary> /// Number of items associated with this policy. /// </summary> public readonly int? ProtectedItemsCount; /// <summary> /// Retention policy details. /// </summary> public readonly Union<Outputs.LongTermRetentionPolicyResponse, Outputs.SimpleRetentionPolicyResponse>? RetentionPolicy; /// <summary> /// Backup schedule of backup policy. /// </summary> public readonly object? SchedulePolicy; [OutputConstructor] private MabProtectionPolicyResponse( string backupManagementType, int? protectedItemsCount, Union<Outputs.LongTermRetentionPolicyResponse, Outputs.SimpleRetentionPolicyResponse>? retentionPolicy, object? schedulePolicy) { BackupManagementType = backupManagementType; ProtectedItemsCount = protectedItemsCount; RetentionPolicy = retentionPolicy; SchedulePolicy = schedulePolicy; } } }
34.352941
127
0.666096
[ "Apache-2.0" ]
sebtelko/pulumi-azure-native
sdk/dotnet/RecoveryServices/V20210201Preview/Outputs/MabProtectionPolicyResponse.cs
1,752
C#
using System.Collections; using System; using System.Collections.Generic; using UnityEngine; namespace EzySlice { /** * TO/DO -> Rename this to Triangulator and deprecate the * older functionality */ public sealed class Triangulator { /** * Represents a 3D Vertex which has been mapped onto a 2D surface * and is mainly used in MonotoeChain to triangulate a set of vertices * against a flat plane. */ internal struct Mapped2D { private readonly Vector3 original; private readonly Vector2 mapped; public Mapped2D(Vector3 newOriginal, Vector3 u, Vector3 v) { this.original = newOriginal; this.mapped = new Vector2(Vector3.Dot(newOriginal, u), Vector3.Dot(newOriginal, v)); } public Vector2 mappedValue { get { return this.mapped; } } public Vector3 originalValue { get { return this.original; } } } /** * O(n log n) Convex Hull Algorithm. * Accepts a list of vertices as Vector3 and triangulates them according to a projection * plane defined as planeNormal. Algorithm will output vertices, indices and UV coordinates * as arrays */ public static bool MonotoneChain(List<Vector3> vertices, Vector3 normal, out Vector3[] verts, out int[] indices, out Vector2[] uv) { int count = vertices.Count; // we cannot triangulate less than 3 points. Use minimum of 3 points if (count < 3) { verts = null; indices = null; uv = null; return false; } // first, we map from 3D points into a 2D plane represented by the provided normal Vector3 r = Mathf.Abs(normal.x) > Mathf.Abs(normal.y) ? new Vector3(0, 1, 0) : new Vector3(1, 0, 0); Vector3 v = Vector3.Normalize(Vector3.Cross(r, normal)); Vector3 u = Vector3.Cross(normal, v); // generate an array of mapped values Mapped2D[] mapped = new Mapped2D[count]; // these values will be used to generate new UV coordinates later on float maxDivX = 0.0f; float maxDivY = 0.0f; // map the 3D vertices into the 2D mapped values for (int i = 0; i < count; i++) { Vector3 vertToAdd = vertices[i]; Mapped2D newMappedValue = new Mapped2D(vertToAdd, u, v); Vector2 mapVal = newMappedValue.mappedValue; // grab our maximal values so we can map UV's in a proper range maxDivX = Mathf.Max(maxDivX, mapVal.x); maxDivY = Mathf.Max(maxDivY, mapVal.y); mapped[i] = newMappedValue; } // sort our newly generated array values Array.Sort<Mapped2D>(mapped, (a, b) => { Vector2 x = a.mappedValue; Vector2 p = b.mappedValue; return (x.x < p.x || (x.x == p.x && x.y < p.y)) ? -1 : 1; }); // our final hull mappings will end up in here Mapped2D[] hulls = new Mapped2D[count+1]; int k = 0; // build the lower hull of the chain for (int i = 0; i < count; i++) { while (k >= 2) { Vector2 mA = hulls[k - 2].mappedValue; Vector2 mB = hulls[k - 1].mappedValue; Vector2 mC = mapped[i].mappedValue; if (Intersector.TriArea2D(mA.x, mA.y, mB.x, mB.y, mC.x, mC.y) > 0.0f) { break; } k--; } hulls[k++] = mapped[i]; } // build the upper hull of the chain for (int i = count - 2, t = k + 1; i >= 0; i--) { while (k >= t) { Vector2 mA = hulls[k - 2].mappedValue; Vector2 mB = hulls[k - 1].mappedValue; Vector2 mC = mapped[i].mappedValue; if (Intersector.TriArea2D(mA.x, mA.y, mB.x, mB.y, mC.x, mC.y) > 0.0f) { break; } k--; } hulls[k++] = mapped[i]; } // finally we can build our mesh, generate all the variables // and fill them up int vertCount = k - 1; // this should not happen, but here just in case if (vertCount < 3) { verts = null; indices = null; uv = null; return false; } int triCount = (vertCount - 2) * 3; verts = new Vector3[vertCount]; indices = new int[triCount]; uv = new Vector2[vertCount]; // generate both the vertices and uv's in this loop for (int i = 0; i < vertCount; i++) { Mapped2D val = hulls[i]; // place the vertex verts[i] = val.originalValue; // generate and place the UV Vector2 mappedValue = val.mappedValue; mappedValue.x = (mappedValue.x / maxDivX) * 0.5f; mappedValue.y = (mappedValue.y / maxDivY) * 0.5f; uv[i] = mappedValue; } int indexCount = 1; // generate the triangles/indices for (int i = 0; i < triCount; i+=3) { indices[i + 0] = 0; indices[i + 1] = indexCount; indices[i + 2] = indexCount + 1; indexCount ++; } return true; } } }
25.61236
134
0.622286
[ "MIT" ]
Alan-Baylis/EzySlice
EzySlice/Framework/Triangulator.cs
4,561
C#
using System; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Runtime.Serialization; using System.Globalization; using System.Security.Permissions; namespace WinKernelObjectsDotNet { /// <summary> /// This class wraps Handles of foreign processes, they have to be duplicated into the current process, to query information about them. /// If you forget to duplicate the handle, you often don't receive an error as query result - the Windows API just returns wrong data! /// </summary> /// <seealso cref="System.IDisposable" /> /// <remarks> /// The handle will only be duplicated when the processId provided to the constructor doesn't belong to the current process. /// </remarks> public class DuplicatedObjectHandle : IDisposable { private readonly Win32Exception _exception; private SafeObjectHandle _objectHandle = null; private readonly string _errorMessage; /// <summary> /// Gets the error message, if an error occurred during construction. /// </summary> /// <value> /// The error message - return null, if no error occurred. /// </value> public string ErrorMessage { get { if (_errorMessage == null && _exception == null) { return null; } return _errorMessage + ": " + _exception.Message; } } private IntPtr _duplicatedObjectHandle; internal IntPtr Handle { get { if (_exception != null) { throw _exception; } return _duplicatedObjectHandle; } } /// <summary> /// Initializes a new instance of the <see cref="DuplicatedObjectHandle"/> class. /// </summary> /// <param name="handle">The handle (will not be closed, when the DuplicatedObjectHandle-instance is disposed).</param> /// <param name="processId">The process ID.</param> public DuplicatedObjectHandle(IntPtr handle, int processId) { _duplicatedObjectHandle = handle; IntPtr currentProcess = NativeMethods.GetCurrentProcess(); bool remote = (processId != NativeMethods.GetProcessId(currentProcess)); SafeProcessHandle processHandle = null; try { if (remote) { processHandle = NativeMethods.OpenProcess(ProcessAccessRights.PROCESS_DUP_HANDLE, true, processId); if (processHandle.IsInvalid) { _exception = new Win32Exception(); _errorMessage = "OpenProcess"; return; } bool success = NativeMethods.DuplicateHandle(processHandle.DangerousGetHandle(), handle, currentProcess, out _objectHandle, 0, false, DuplicateHandleOptions.DUPLICATE_SAME_ACCESS); if (!success) { _exception = new Win32Exception(); _errorMessage = "DuplicateHandle"; return; } _duplicatedObjectHandle = _objectHandle.DangerousGetHandle(); } } finally { if (processHandle != null) { processHandle.Close(); } } } #region IDisposable Members and finalizer private bool _isDisposedFlag; //Compiler initializes this to false /// <summary> /// dispose managed and unmanaged resources /// </summary> /// <param name="isDisposing">true if called via IDisposable.Dispose, false if called via finalizer</param> protected virtual void Dispose(bool isDisposing) { if (_isDisposedFlag) { return; } if (isDisposing) { // free managed resources here if (_objectHandle != null) { _objectHandle.Close(); } } // free unmanaged resources here // set mark this object as disposed _isDisposedFlag = true; } /// <summary> /// /// </summary> public void Dispose() { // If you implement a Close-Method: use the same code Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Call this method in every public method of this class as first statement /// </summary> private void ThrowIfDisposed() { if (_isDisposedFlag) { throw (new ObjectDisposedException("DuplicatedObjectHandle", "Cannot access a disposed object.")); } } #endregion /// <summary> /// Gets the object name from the wrapped handle. /// </summary> /// <returns> /// For object-type 'File': the device path (serial-ports also have the type 'file') - starts always with '\Device\', if it doesn't the handle is invalid. /// For object-type 'Key': the registry Path - starts always with '\REGISTRY\', if it doesn't the handle is invalid. /// </returns> /// <exception cref="System.Exception"></exception> public string GetObjectNameFromHandle() { string name; NT_STATUS status = TryGetObjectNameFromHandle(out name); if (status != NT_STATUS.STATUS_SUCCESS) { throw new NtStatusException("TryGetObjectNameFromHandle failed", status); } return name; } /// <summary> /// Tries the get object name from the wrapped handle. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> /// <remarks> /// This method might hang infinitely in NtQueryObject, so it is safer to use the overload with the timeout parameter. /// The hangs have been observed for handles with GrantedAccess == 0x00120189 and 0x0012019f all of them were for type 'file' /// and process explorer showed that the handle names all were '\Device\NamedPipe' /// This was tested on win10 64bit 1511 and 1607. /// The problem seems only to appear when 'Prefer 32bit' is disabled /// </remarks> public NT_STATUS TryGetObjectNameFromHandle(out string name) { name = null; IntPtr ptr = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { int length = 0x200; // 512 bytes RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { // CER guarantees the assignment of the allocated memory address to ptr, if an asynchronous exception occurs. ptr = Marshal.AllocHGlobal(length); } NT_STATUS ret = NativeMethods.NtQueryObject(_duplicatedObjectHandle, OBJECT_INFORMATION_CLASS.ObjectNameInformation, ptr, length, out length); if (ret == NT_STATUS.STATUS_BUFFER_OVERFLOW) { RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { // CER guarantees that the previous allocation is freed, and that the newly allocated memory address is // assigned to ptr if an asynchronous exception occurs. Marshal.FreeHGlobal(ptr); ptr = Marshal.AllocHGlobal(length); } ret = NativeMethods.NtQueryObject(_duplicatedObjectHandle, OBJECT_INFORMATION_CLASS.ObjectNameInformation, ptr, length, out length); } if (ret == NT_STATUS.STATUS_SUCCESS) { OBJECT_NAME_INFORMATION nameInfo = Marshal.PtrToStructure<OBJECT_NAME_INFORMATION>(ptr); name = Helpers.MarshalUnicodeString(nameInfo.Name); } return ret; } finally { // CER guarantees that the allocated memory is freed, if an asynchronous exception occurs. Marshal.FreeHGlobal(ptr); } } /// <summary> /// Tries the get object name from the wrapped handle. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="timeout">The timeout.</param> /// <returns></returns> /// <remarks> /// Since the call to NtQueryObject might hang infinitely, this method uses a separate thread with a timeout to call the API /// If the timeout expires the status 'NT_STATUS.STATUS_TIMEOUT' will be returned. /// </remarks> public NT_STATUS TryGetObjectNameFromHandle(out string fileName, TimeSpan timeout) { string name = null; NT_STATUS result = NT_STATUS.STATUS_SUCCESS; AutoResetEvent signal = new AutoResetEvent(false); Thread workerThread = null; ThreadPool.QueueUserWorkItem((o) => { workerThread = Thread.CurrentThread; result = TryGetObjectNameFromHandle(out name); signal.Set(); }); bool waitres = signal.WaitOne(timeout); fileName = name; if (workerThread != null && workerThread.IsAlive && waitres == false) { workerThread.Abort(); return NT_STATUS.STATUS_TIMEOUT; } return result; } /// <summary> /// Gets the type-info for the handle. /// </summary> /// <returns></returns> /// <exception cref="NtStatusException"> /// NtQueryObject failed /// </exception> public ObjectTypeInfo GetHandleType() { int length; NT_STATUS res1 = NativeMethods.NtQueryObject(_duplicatedObjectHandle, OBJECT_INFORMATION_CLASS.ObjectTypeInformation, IntPtr.Zero, 0, out length); if (res1 != NT_STATUS.STATUS_SUCCESS && res1 != NT_STATUS.STATUS_INFO_LENGTH_MISMATCH) { throw new NtStatusException("NtQueryObject call1 failed", res1); } IntPtr ptr = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { ptr = Marshal.AllocHGlobal(length); } NT_STATUS res2 = NativeMethods.NtQueryObject(_duplicatedObjectHandle, OBJECT_INFORMATION_CLASS.ObjectTypeInformation, ptr, length, out length); if (res2 != NT_STATUS.STATUS_SUCCESS) { throw new NtStatusException("NtQueryObject call2 failed", res2); } OBJECT_TYPE_INFORMATION objectType = Marshal.PtrToStructure<OBJECT_TYPE_INFORMATION>(ptr); string typeName = Helpers.MarshalUnicodeString(objectType.TypeName); return new ObjectTypeInfo(objectType, typeName); } finally { Marshal.FreeHGlobal(ptr); } } } }
30.683007
185
0.695175
[ "MIT" ]
donid/WinKernelObjectsDotNet
src/WinKernelObjectsDotNet/DuplicatedObjectHandle.cs
9,391
C#
using LBCOnlineShoppingCart.Application.Interfaces; using LBCOnlineShoppingCart.Domain.Interfaces; using LBCOnlineShoppingCart.Domain.Models; using System; using System.Collections.Generic; using System.Text; namespace LBCOnlineShoppingCart.Application.Services { public class RoleService : IRoleService { public IRoleRepository _RoleRepository; public RoleService(IRoleRepository RoleRepository) { _RoleRepository = RoleRepository; } public string UpdateRole(Role Role) { return _RoleRepository.UpdateRole(Role); } public Role Detail(int? id) { return _RoleRepository.Detail(id); } public IEnumerable<Role> GetRole() { //Add this code snippet return _RoleRepository.GetRole(); } public string InsertRole(Role Role) { return _RoleRepository.InsertRole(Role); } } }
24.6
58
0.640244
[ "MIT" ]
Last-Bench-Coder/LBC.OnlineShoppingCart
LBCOnlineShoppingCart.Application/Services/RoleService.cs
986
C#
namespace Lykke.Service.PayInternal.Contract.PaymentRequest { /// <summary> /// Payment request statuses being used for public APIs /// </summary> public static class PaymentRequestPublicStatuses { /// <summary> /// Payment request has been created /// </summary> public const string PaymentRequestCreated = "PAYMENT_REQUEST_CREATED"; /// <summary> /// Payment has been confirmed /// </summary> public const string PaymentConfirmed = "PAYMENT_CONFIRMED"; /// <summary> /// Payment is in progress /// </summary> public const string PaymentInProgress = "PAYMENT_INPROGRESS"; /// <summary> /// Payment has been cancelled /// </summary> public const string PaymentCancelled = "PAYMENT_CANCELLED"; /// <summary> /// Payment error /// </summary> public const string PaymentError = "PAYMENT_ERROR"; /// <summary> /// Refund is in progress /// </summary> public const string RefundInProgress = "REFUND_INPROGRESS"; /// <summary> /// Refund has been confirmed /// </summary> public const string RefundConfirmed = "REFUND_CONFIRMED"; /// <summary> /// Refund error /// </summary> public const string RefundError = "REFUND_ERROR"; /// <summary> /// Payment request is accepted to settlement. /// </summary> public const string SettlementInProgress = "SETTLEMENT_INPROGRESS"; /// <summary> /// An error occurred during settlement processing. /// </summary> public const string SettlementError = "SETTLEMENT_ERROR"; /// <summary> /// Payment request is settled. /// </summary> public const string Settled = "SETTLEMENT_SETTLED"; } }
29.8125
78
0.580713
[ "MIT" ]
LykkeCity/Lykke.Service.PayInternal
src/Lykke.Service.PayInternal.Contract/PaymentRequest/PaymentRequestPublicStatuses.cs
1,910
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v5/services/customer_manager_link_service.proto // </auto-generated> // Original file comments: // Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. // #pragma warning disable 0414, 1591 #region Designer generated code using grpc = global::Grpc.Core; namespace Google.Ads.GoogleAds.V5.Services { /// <summary> /// Service to manage customer-manager links. /// </summary> public static partial class CustomerManagerLinkService { static readonly string __ServiceName = "google.ads.googleads.v5.services.CustomerManagerLinkService"; static void __Helper_SerializeMessage(global::Google.Protobuf.IMessage message, grpc::SerializationContext context) { #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION if (message is global::Google.Protobuf.IBufferMessage) { context.SetPayloadLength(message.CalculateSize()); global::Google.Protobuf.MessageExtensions.WriteTo(message, context.GetBufferWriter()); context.Complete(); return; } #endif context.Complete(global::Google.Protobuf.MessageExtensions.ToByteArray(message)); } static class __Helper_MessageCache<T> { public static readonly bool IsBufferMessage = global::System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(global::Google.Protobuf.IBufferMessage)).IsAssignableFrom(typeof(T)); } static T __Helper_DeserializeMessage<T>(grpc::DeserializationContext context, global::Google.Protobuf.MessageParser<T> parser) where T : global::Google.Protobuf.IMessage<T> { #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION if (__Helper_MessageCache<T>.IsBufferMessage) { return parser.ParseFrom(context.PayloadAsReadOnlySequence()); } #endif return parser.ParseFrom(context.PayloadAsNewBuffer()); } static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V5.Services.GetCustomerManagerLinkRequest> __Marshaller_google_ads_googleads_v5_services_GetCustomerManagerLinkRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V5.Services.GetCustomerManagerLinkRequest.Parser)); static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V5.Resources.CustomerManagerLink> __Marshaller_google_ads_googleads_v5_resources_CustomerManagerLink = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V5.Resources.CustomerManagerLink.Parser)); static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkRequest> __Marshaller_google_ads_googleads_v5_services_MutateCustomerManagerLinkRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkRequest.Parser)); static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkResponse> __Marshaller_google_ads_googleads_v5_services_MutateCustomerManagerLinkResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkResponse.Parser)); static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkRequest> __Marshaller_google_ads_googleads_v5_services_MoveManagerLinkRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkRequest.Parser)); static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkResponse> __Marshaller_google_ads_googleads_v5_services_MoveManagerLinkResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkResponse.Parser)); static readonly grpc::Method<global::Google.Ads.GoogleAds.V5.Services.GetCustomerManagerLinkRequest, global::Google.Ads.GoogleAds.V5.Resources.CustomerManagerLink> __Method_GetCustomerManagerLink = new grpc::Method<global::Google.Ads.GoogleAds.V5.Services.GetCustomerManagerLinkRequest, global::Google.Ads.GoogleAds.V5.Resources.CustomerManagerLink>( grpc::MethodType.Unary, __ServiceName, "GetCustomerManagerLink", __Marshaller_google_ads_googleads_v5_services_GetCustomerManagerLinkRequest, __Marshaller_google_ads_googleads_v5_resources_CustomerManagerLink); static readonly grpc::Method<global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkRequest, global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkResponse> __Method_MutateCustomerManagerLink = new grpc::Method<global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkRequest, global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkResponse>( grpc::MethodType.Unary, __ServiceName, "MutateCustomerManagerLink", __Marshaller_google_ads_googleads_v5_services_MutateCustomerManagerLinkRequest, __Marshaller_google_ads_googleads_v5_services_MutateCustomerManagerLinkResponse); static readonly grpc::Method<global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkRequest, global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkResponse> __Method_MoveManagerLink = new grpc::Method<global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkRequest, global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkResponse>( grpc::MethodType.Unary, __ServiceName, "MoveManagerLink", __Marshaller_google_ads_googleads_v5_services_MoveManagerLinkRequest, __Marshaller_google_ads_googleads_v5_services_MoveManagerLinkResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V5.Services.CustomerManagerLinkServiceReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of CustomerManagerLinkService</summary> [grpc::BindServiceMethod(typeof(CustomerManagerLinkService), "BindService")] public abstract partial class CustomerManagerLinkServiceBase { /// <summary> /// Returns the requested CustomerManagerLink in full detail. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Ads.GoogleAds.V5.Resources.CustomerManagerLink> GetCustomerManagerLink(global::Google.Ads.GoogleAds.V5.Services.GetCustomerManagerLinkRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Creates or updates customer manager links. Operation statuses are returned. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkResponse> MutateCustomerManagerLink(global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Moves a client customer to a new manager customer. /// This simplifies the complex request that requires two operations to move /// a client customer to a new manager. i.e: /// 1. Update operation with Status INACTIVE (previous manager) and, /// 2. Update operation with Status ACTIVE (new manager). /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkResponse> MoveManagerLink(global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for CustomerManagerLinkService</summary> public partial class CustomerManagerLinkServiceClient : grpc::ClientBase<CustomerManagerLinkServiceClient> { /// <summary>Creates a new client for CustomerManagerLinkService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public CustomerManagerLinkServiceClient(grpc::ChannelBase channel) : base(channel) { } /// <summary>Creates a new client for CustomerManagerLinkService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public CustomerManagerLinkServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected CustomerManagerLinkServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected CustomerManagerLinkServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Returns the requested CustomerManagerLink in full detail. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Ads.GoogleAds.V5.Resources.CustomerManagerLink GetCustomerManagerLink(global::Google.Ads.GoogleAds.V5.Services.GetCustomerManagerLinkRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetCustomerManagerLink(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Returns the requested CustomerManagerLink in full detail. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Ads.GoogleAds.V5.Resources.CustomerManagerLink GetCustomerManagerLink(global::Google.Ads.GoogleAds.V5.Services.GetCustomerManagerLinkRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetCustomerManagerLink, null, options, request); } /// <summary> /// Returns the requested CustomerManagerLink in full detail. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V5.Resources.CustomerManagerLink> GetCustomerManagerLinkAsync(global::Google.Ads.GoogleAds.V5.Services.GetCustomerManagerLinkRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetCustomerManagerLinkAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Returns the requested CustomerManagerLink in full detail. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V5.Resources.CustomerManagerLink> GetCustomerManagerLinkAsync(global::Google.Ads.GoogleAds.V5.Services.GetCustomerManagerLinkRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetCustomerManagerLink, null, options, request); } /// <summary> /// Creates or updates customer manager links. Operation statuses are returned. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkResponse MutateCustomerManagerLink(global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return MutateCustomerManagerLink(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates or updates customer manager links. Operation statuses are returned. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkResponse MutateCustomerManagerLink(global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_MutateCustomerManagerLink, null, options, request); } /// <summary> /// Creates or updates customer manager links. Operation statuses are returned. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkResponse> MutateCustomerManagerLinkAsync(global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return MutateCustomerManagerLinkAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates or updates customer manager links. Operation statuses are returned. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkResponse> MutateCustomerManagerLinkAsync(global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_MutateCustomerManagerLink, null, options, request); } /// <summary> /// Moves a client customer to a new manager customer. /// This simplifies the complex request that requires two operations to move /// a client customer to a new manager. i.e: /// 1. Update operation with Status INACTIVE (previous manager) and, /// 2. Update operation with Status ACTIVE (new manager). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkResponse MoveManagerLink(global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return MoveManagerLink(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Moves a client customer to a new manager customer. /// This simplifies the complex request that requires two operations to move /// a client customer to a new manager. i.e: /// 1. Update operation with Status INACTIVE (previous manager) and, /// 2. Update operation with Status ACTIVE (new manager). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkResponse MoveManagerLink(global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_MoveManagerLink, null, options, request); } /// <summary> /// Moves a client customer to a new manager customer. /// This simplifies the complex request that requires two operations to move /// a client customer to a new manager. i.e: /// 1. Update operation with Status INACTIVE (previous manager) and, /// 2. Update operation with Status ACTIVE (new manager). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkResponse> MoveManagerLinkAsync(global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return MoveManagerLinkAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Moves a client customer to a new manager customer. /// This simplifies the complex request that requires two operations to move /// a client customer to a new manager. i.e: /// 1. Update operation with Status INACTIVE (previous manager) and, /// 2. Update operation with Status ACTIVE (new manager). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkResponse> MoveManagerLinkAsync(global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_MoveManagerLink, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override CustomerManagerLinkServiceClient NewInstance(ClientBaseConfiguration configuration) { return new CustomerManagerLinkServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(CustomerManagerLinkServiceBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_GetCustomerManagerLink, serviceImpl.GetCustomerManagerLink) .AddMethod(__Method_MutateCustomerManagerLink, serviceImpl.MutateCustomerManagerLink) .AddMethod(__Method_MoveManagerLink, serviceImpl.MoveManagerLink).Build(); } /// <summary>Register service method with a service binder with or without implementation. Useful when customizing the service binding logic. /// Note: this method is part of an experimental API that can change or be removed without any prior notice.</summary> /// <param name="serviceBinder">Service methods will be bound by calling <c>AddMethod</c> on this object.</param> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static void BindService(grpc::ServiceBinderBase serviceBinder, CustomerManagerLinkServiceBase serviceImpl) { serviceBinder.AddMethod(__Method_GetCustomerManagerLink, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Ads.GoogleAds.V5.Services.GetCustomerManagerLinkRequest, global::Google.Ads.GoogleAds.V5.Resources.CustomerManagerLink>(serviceImpl.GetCustomerManagerLink)); serviceBinder.AddMethod(__Method_MutateCustomerManagerLink, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkRequest, global::Google.Ads.GoogleAds.V5.Services.MutateCustomerManagerLinkResponse>(serviceImpl.MutateCustomerManagerLink)); serviceBinder.AddMethod(__Method_MoveManagerLink, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkRequest, global::Google.Ads.GoogleAds.V5.Services.MoveManagerLinkResponse>(serviceImpl.MoveManagerLink)); } } } #endregion
72.435673
420
0.748274
[ "Apache-2.0" ]
GraphikaPS/google-ads-dotnet
src/V5/Services/CustomerManagerLinkServiceGrpc.cs
24,773
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 ec2-2016-11-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { /// <summary> /// Describes a VPC attachment. /// </summary> public partial class TransitGatewayVpcAttachment { private DateTime? _creationTime; private TransitGatewayVpcAttachmentOptions _options; private TransitGatewayAttachmentState _state; private List<string> _subnetIds = new List<string>(); private List<Tag> _tags = new List<Tag>(); private string _transitGatewayAttachmentId; private string _transitGatewayId; private string _vpcId; private string _vpcOwnerId; /// <summary> /// Gets and sets the property CreationTime. /// <para> /// The creation time. /// </para> /// </summary> public DateTime CreationTime { get { return this._creationTime.GetValueOrDefault(); } set { this._creationTime = value; } } // Check to see if CreationTime property is set internal bool IsSetCreationTime() { return this._creationTime.HasValue; } /// <summary> /// Gets and sets the property Options. /// <para> /// The VPC attachment options. /// </para> /// </summary> public TransitGatewayVpcAttachmentOptions Options { get { return this._options; } set { this._options = value; } } // Check to see if Options property is set internal bool IsSetOptions() { return this._options != null; } /// <summary> /// Gets and sets the property State. /// <para> /// The state of the VPC attachment. Note that the <code>initiating</code> state has been /// deprecated. /// </para> /// </summary> public TransitGatewayAttachmentState State { get { return this._state; } set { this._state = value; } } // Check to see if State property is set internal bool IsSetState() { return this._state != null; } /// <summary> /// Gets and sets the property SubnetIds. /// <para> /// The IDs of the subnets. /// </para> /// </summary> public List<string> SubnetIds { get { return this._subnetIds; } set { this._subnetIds = value; } } // Check to see if SubnetIds property is set internal bool IsSetSubnetIds() { return this._subnetIds != null && this._subnetIds.Count > 0; } /// <summary> /// Gets and sets the property Tags. /// <para> /// The tags for the VPC attachment. /// </para> /// </summary> public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } /// <summary> /// Gets and sets the property TransitGatewayAttachmentId. /// <para> /// The ID of the attachment. /// </para> /// </summary> public string TransitGatewayAttachmentId { get { return this._transitGatewayAttachmentId; } set { this._transitGatewayAttachmentId = value; } } // Check to see if TransitGatewayAttachmentId property is set internal bool IsSetTransitGatewayAttachmentId() { return this._transitGatewayAttachmentId != null; } /// <summary> /// Gets and sets the property TransitGatewayId. /// <para> /// The ID of the transit gateway. /// </para> /// </summary> public string TransitGatewayId { get { return this._transitGatewayId; } set { this._transitGatewayId = value; } } // Check to see if TransitGatewayId property is set internal bool IsSetTransitGatewayId() { return this._transitGatewayId != null; } /// <summary> /// Gets and sets the property VpcId. /// <para> /// The ID of the VPC. /// </para> /// </summary> public string VpcId { get { return this._vpcId; } set { this._vpcId = value; } } // Check to see if VpcId property is set internal bool IsSetVpcId() { return this._vpcId != null; } /// <summary> /// Gets and sets the property VpcOwnerId. /// <para> /// The ID of the Amazon Web Services account that owns the VPC. /// </para> /// </summary> public string VpcOwnerId { get { return this._vpcOwnerId; } set { this._vpcOwnerId = value; } } // Check to see if VpcOwnerId property is set internal bool IsSetVpcOwnerId() { return this._vpcOwnerId != null; } } }
28.909524
101
0.552463
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/TransitGatewayVpcAttachment.cs
6,071
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace timw255.Sitefinity.RestClient.Model { public class LayoutTransformationViewModel { public string AlternatLayoutElementName { get; set; } public string OriginalLayoutElementName { get; set; } public LayoutTransformationViewModel() { } } }
24.388889
61
0.747153
[ "MIT" ]
timw255/timw255.Sitefinity.RestClient
timw255.Sitefinity.RestClient/Model/LayoutTransformationViewModel.cs
441
C#
using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection; using System.Runtime.ExceptionServices; using System.Text; using System.Threading.Tasks; namespace Discord.Interactions { /// <summary> /// Represents a cached method execution delegate. /// </summary> /// <param name="context">Execution context that will be injected into the module class.</param> /// <param name="args">Method arguments array.</param> /// <param name="serviceProvider">Service collection for initializing the module.</param> /// <param name="commandInfo">Command info class of the executed method.</param> /// <returns> /// A task representing the execution operation. /// </returns> public delegate Task ExecuteCallback (IInteractionContext context, object[] args, IServiceProvider serviceProvider, ICommandInfo commandInfo); /// <summary> /// The base information class for <see cref="InteractionService"/> commands. /// </summary> /// <typeparam name="TParameter">The type of <see cref="IParameterInfo"/> that is used by this command type.</typeparam> public abstract class CommandInfo<TParameter> : ICommandInfo where TParameter : class, IParameterInfo { private readonly ExecuteCallback _action; private readonly ILookup<string, PreconditionAttribute> _groupedPreconditions; internal IReadOnlyDictionary<string, TParameter> _parameterDictionary { get; } /// <inheritdoc/> public ModuleInfo Module { get; } /// <inheritdoc/> public InteractionService CommandService { get; } /// <inheritdoc/> public string Name { get; } /// <inheritdoc/> public string MethodName { get; } /// <inheritdoc/> public virtual bool IgnoreGroupNames { get; } /// <inheritdoc/> public abstract bool SupportsWildCards { get; } /// <inheritdoc/> public bool IsTopLevelCommand { get; } /// <inheritdoc/> public RunMode RunMode { get; } /// <inheritdoc/> public IReadOnlyCollection<Attribute> Attributes { get; } /// <inheritdoc/> public IReadOnlyCollection<PreconditionAttribute> Preconditions { get; } /// <inheritdoc cref="ICommandInfo.Parameters"/> public abstract IReadOnlyCollection<TParameter> Parameters { get; } internal CommandInfo(Builders.ICommandBuilder builder, ModuleInfo module, InteractionService commandService) { CommandService = commandService; Module = module; Name = builder.Name; MethodName = builder.MethodName; IgnoreGroupNames = builder.IgnoreGroupNames; IsTopLevelCommand = IgnoreGroupNames || CheckTopLevel(Module); RunMode = builder.RunMode != RunMode.Default ? builder.RunMode : commandService._runMode; Attributes = builder.Attributes.ToImmutableArray(); Preconditions = builder.Preconditions.ToImmutableArray(); _action = builder.Callback; _groupedPreconditions = builder.Preconditions.ToLookup(x => x.Group, x => x, StringComparer.Ordinal); _parameterDictionary = Parameters?.ToDictionary(x => x.Name, x => x).ToImmutableDictionary(); } /// <inheritdoc/> public abstract Task<IResult> ExecuteAsync(IInteractionContext context, IServiceProvider services); protected abstract Task InvokeModuleEvent(IInteractionContext context, IResult result); protected abstract string GetLogString(IInteractionContext context); /// <inheritdoc/> public async Task<PreconditionResult> CheckPreconditionsAsync(IInteractionContext context, IServiceProvider services) { async Task<PreconditionResult> CheckGroups(ILookup<string, PreconditionAttribute> preconditions, string type) { foreach (IGrouping<string, PreconditionAttribute> preconditionGroup in preconditions) { if (preconditionGroup.Key == null) { foreach (PreconditionAttribute precondition in preconditionGroup) { var result = await precondition.CheckRequirementsAsync(context, this, services).ConfigureAwait(false); if (!result.IsSuccess) return result; } } else { var results = new List<PreconditionResult>(); foreach (PreconditionAttribute precondition in preconditionGroup) results.Add(await precondition.CheckRequirementsAsync(context, this, services).ConfigureAwait(false)); if (!results.Any(p => p.IsSuccess)) return PreconditionGroupResult.FromError($"{type} precondition group {preconditionGroup.Key} failed.", results); } } return PreconditionGroupResult.FromSuccess(); } var moduleResult = await CheckGroups(Module.GroupedPreconditions, "Module").ConfigureAwait(false); if (!moduleResult.IsSuccess) return moduleResult; var commandResult = await CheckGroups(_groupedPreconditions, "Command").ConfigureAwait(false); if (!commandResult.IsSuccess) return commandResult; return PreconditionResult.FromSuccess(); } protected async Task<IResult> RunAsync(IInteractionContext context, object[] args, IServiceProvider services) { switch (RunMode) { case RunMode.Sync: { if (CommandService._autoServiceScopes) { using var scope = services?.CreateScope(); return await ExecuteInternalAsync(context, args, scope?.ServiceProvider ?? EmptyServiceProvider.Instance).ConfigureAwait(false); } else return await ExecuteInternalAsync(context, args, services).ConfigureAwait(false); } case RunMode.Async: _ = Task.Run(async () => { if (CommandService._autoServiceScopes) { using var scope = services?.CreateScope(); await ExecuteInternalAsync(context, args, scope?.ServiceProvider ?? EmptyServiceProvider.Instance).ConfigureAwait(false); } else await ExecuteInternalAsync(context, args, services).ConfigureAwait(false); }); break; default: throw new InvalidOperationException($"RunMode {RunMode} is not supported."); } return ExecuteResult.FromSuccess(); } private async Task<IResult> ExecuteInternalAsync(IInteractionContext context, object[] args, IServiceProvider services) { await CommandService._cmdLogger.DebugAsync($"Executing {GetLogString(context)}").ConfigureAwait(false); try { var preconditionResult = await CheckPreconditionsAsync(context, services).ConfigureAwait(false); if (!preconditionResult.IsSuccess) { await InvokeModuleEvent(context, preconditionResult).ConfigureAwait(false); return preconditionResult; } var index = 0; foreach (var parameter in Parameters) { var result = await parameter.CheckPreconditionsAsync(context, args[index++], services).ConfigureAwait(false); if (!result.IsSuccess) { await InvokeModuleEvent(context, result).ConfigureAwait(false); return result; } } var task = _action(context, args, services, this); if (task is Task<IResult> resultTask) { var result = await resultTask.ConfigureAwait(false); await InvokeModuleEvent(context, result).ConfigureAwait(false); if (result is RuntimeResult || result is ExecuteResult) return result; } else { await task.ConfigureAwait(false); var result = ExecuteResult.FromSuccess(); await InvokeModuleEvent(context, result).ConfigureAwait(false); return result; } var failResult = ExecuteResult.FromError(InteractionCommandError.Unsuccessful, "Command execution failed for an unknown reason"); await InvokeModuleEvent(context, failResult).ConfigureAwait(false); return failResult; } catch (Exception ex) { var originalEx = ex; while (ex is TargetInvocationException) ex = ex.InnerException; await Module.CommandService._cmdLogger.ErrorAsync(ex).ConfigureAwait(false); var result = ExecuteResult.FromError(ex); await InvokeModuleEvent(context, result).ConfigureAwait(false); if (Module.CommandService._throwOnError) { if (ex == originalEx) throw; else ExceptionDispatchInfo.Capture(ex).Throw(); } return result; } finally { await CommandService._cmdLogger.VerboseAsync($"Executed {GetLogString(context)}").ConfigureAwait(false); } } private static bool CheckTopLevel(ModuleInfo parent) { var currentParent = parent; while (currentParent != null) { if (currentParent.IsSlashGroup) return false; currentParent = currentParent.Parent; } return true; } // ICommandInfo /// <inheritdoc/> IReadOnlyCollection<IParameterInfo> ICommandInfo.Parameters => Parameters; /// <inheritdoc/> public override string ToString() { List<string> builder = new(); var currentParent = Module; while (currentParent != null) { if (currentParent.IsSlashGroup) builder.Add(currentParent.SlashGroupName); currentParent = currentParent.Parent; } builder.Reverse(); builder.Add(Name); return string.Join(" ", builder); } } }
40.67509
156
0.572113
[ "MIT" ]
FeroxFoxxo/Discord.Net
src/Discord.Net.Interactions/Info/Commands/CommandInfo.cs
11,267
C#
#if UNITY_EDITOR using UnityEngine; using System.Collections; using UnityEditor; using UMA; namespace UMAEditor { [CustomEditor(typeof(DNARangeAsset))] public class DNARangeInspector : Editor { [MenuItem("Assets/Create/UMA DNA Range Asset")] public static void CreateOverlayMenuItem() { CustomAssetUtility.CreateAsset<DNARangeAsset>(); } private DNARangeAsset dnaRange; private UMADnaBase dnaSource; private int entryCount = 0; public void OnEnable() { dnaRange = target as DNARangeAsset; if (dnaRange.dnaConverter != null) { dnaSource = dnaRange.dnaConverter.DNAType.GetConstructor(System.Type.EmptyTypes).Invoke(null) as UMADnaBase; if (dnaSource != null) entryCount = dnaSource.Count; } } public override void OnInspectorGUI() { bool dirty = false; DnaConverterBehaviour newSource = EditorGUILayout.ObjectField("DNA Converter", dnaRange.dnaConverter, typeof(DnaConverterBehaviour), true) as DnaConverterBehaviour; if (newSource != dnaRange.dnaConverter) { dnaRange.dnaConverter = newSource; dnaSource = null; if (dnaRange.dnaConverter != null) { dnaSource = dnaRange.dnaConverter.DNAType.GetConstructor(System.Type.EmptyTypes).Invoke(null) as UMADnaBase; } if (dnaSource == null) { entryCount = 0; } else { entryCount = dnaSource.Count; } dnaRange.means = new float[entryCount]; dnaRange.deviations = new float[entryCount]; dnaRange.spreads = new float[entryCount]; for (int i = 0; i < entryCount; i++) { dnaRange.means[i] = 0.5f; dnaRange.deviations[i] = 0.16f; dnaRange.spreads[i] = 0.5f; } dirty = true; } GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.Height(1)); if (dnaRange.dnaConverter != null) { GUILayout.Space(2f); GUIStyle headerStyle = new GUIStyle(); headerStyle.alignment = TextAnchor.MiddleCenter; headerStyle.normal.textColor = Color.white; headerStyle.fontSize = 12; EditorGUILayout.LabelField(dnaRange.dnaConverter.DNAType.Name, headerStyle); string[] dnaNames = dnaSource.Names; for (int i = 0; i < entryCount; i++) { float currentMin = dnaRange.means[i] - dnaRange.spreads[i]; float currentMax = dnaRange.means[i] + dnaRange.spreads[i]; float min = currentMin; float max = currentMax; EditorGUILayout.PrefixLabel(dnaNames[i]); EditorGUILayout.MinMaxSlider(ref min, ref max, 0f, 1f); if ((min != currentMin) || (max != currentMax)) { dnaRange.means[i] = (min + max) / 2f; dnaRange.spreads[i] = (max - min) / 2f; dnaRange.deviations[i] = dnaRange.spreads[i] / 3f; dirty = true; } } } if (dirty) { EditorUtility.SetDirty(dnaRange); AssetDatabase.SaveAssets(); } } } } #endif
26.453704
167
0.665033
[ "MIT" ]
huika/UMA
UMAProject/Assets/Standard Assets/Editor/UMA/Core/DNARangeInspector.cs
2,859
C#
using System; using System.Threading.Tasks; using Android.Graphics.Drawables; namespace Microsoft.Maui { class ImageLoaderResultCallback : ImageLoaderCallbackBase<IImageSourceServiceResult<Drawable>> { protected override IImageSourceServiceResult<Drawable>? OnSuccess(Drawable? drawable, Action? dispose) => drawable is not null ? new ImageSourceServiceResult(drawable, dispose) : default; } class ImageLoaderCallback : ImageLoaderCallbackBase<IImageSourceServiceResult> { protected override IImageSourceServiceResult? OnSuccess(Drawable? drawable, Action? dispose) => new ImageSourceServiceLoadResult(dispose); } abstract class ImageLoaderCallbackBase<T> : Java.Lang.Object, IImageLoaderCallback where T : IImageSourceServiceResult { readonly TaskCompletionSource<T?> _tcsResult = new(); public Task<T?> Result => _tcsResult.Task; public void OnComplete(Java.Lang.Boolean? success, Drawable? drawable, Java.Lang.IRunnable? dispose) { try { Action? disposeWrapper = dispose != null ? dispose.Run : null; var result = success?.BooleanValue() == true ? OnSuccess(drawable, disposeWrapper) : OnFailure(drawable, disposeWrapper); _tcsResult.SetResult(result); } catch (Exception ex) { _tcsResult.SetException(ex); } } protected abstract T? OnSuccess(Drawable? drawable, Action? dispose); protected virtual T? OnFailure(Drawable? errorDrawable, Action? dispose) => default; } }
27.924528
107
0.745946
[ "MIT" ]
10088/maui
src/Core/src/ImageSources/Android/ImageLoaderCallback.cs
1,482
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("DbFirst")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("DbFirst")] [assembly: System.Reflection.AssemblyTitleAttribute("DbFirst")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.416667
81
0.628773
[ "MIT" ]
firatalcin/CSharp-.NetCore-Works
FullStackDotNetCore-Lessons/DbFirst/DbFirst/obj/Debug/net5.0/DbFirst.AssemblyInfo.cs
994
C#
using System; using DbUp; using DbUp.Engine; using Microsoft.Extensions.Configuration; using Serilog; namespace VND.CoolStore.DbMigration { class Program { private static IConfiguration _configuration; private enum ServiceName { ShoppingCart = 0, ProductCatalog = 1, Inventory = 2 } static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .Enrich.FromLogContext() .WriteTo.Console() .CreateLogger(); _configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddEnvironmentVariables() .Build(); for (var argIndex = 0; argIndex < args.Length; argIndex++) { if (IsArg(args[argIndex], "shoppingcart")) { Log.Information("Run migration for Shopping Cart Service"); Run(ServiceName.ShoppingCart); } else if (IsArg(args[argIndex], "productcatalog")) { Log.Information("Run migration for Product Catalog Service"); Run(ServiceName.ProductCatalog); } else if (IsArg(args[argIndex], "inventory")) { Log.Information("Run migration for Inventory Service"); Run(ServiceName.Inventory); } else { throw new ArgumentOutOfRangeException($"{args[argIndex]} not found."); } } } private static void Run(ServiceName dBName) { var connString = _configuration.GetConnectionString(dBName.ToString()); var scriptFolderPath = $"./Scripts/{dBName.ToString()}"; DropDatabase.For.SqlDatabase(connString); EnsureDatabase.For.SqlDatabase(connString); var upgrader = DeployChanges.To .SqlDatabase(connString, null) .WithScriptsFromFileSystem(scriptFolderPath, new SqlScriptOptions { RunGroupOrder = DbUpDefaults.DefaultRunGroupOrder + 1 }) .LogToAutodetectedLog() .Build(); upgrader.PerformUpgrade(); } private static bool IsArg(string candidate, string name) { return (name != null && candidate.Equals(name, StringComparison.OrdinalIgnoreCase)); } } }
31.951807
96
0.524887
[ "MIT" ]
tannguyent/coolstore-microservices
src/migrations/VND.CoolStore.DbMigration/Program.cs
2,652
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Collections.Generic; using UnityEngine; using UnityEngine.VR.WSA; namespace Academy.HoloToolkit.Unity { /// <summary> /// Spatial Mapping Observer states. /// </summary> public enum ObserverStates { /// <summary> /// The SurfaceObserver is currently running. /// </summary> Running = 0, /// <summary> /// The SurfaceObserver is currently idle. /// </summary> Stopped = 1 } /// <summary> /// The SpatialMappingObserver class encapsulates the SurfaceObserver into an easy to use /// object that handles managing the observed surfaces and the rendering of surface geometry. /// </summary> public class SpatialMappingObserver : SpatialMappingSource { [Tooltip("The number of triangles to calculate per cubic meter.")] public float TrianglesPerCubicMeter = 500f; [Tooltip("The extents of the observation volume.")] public Vector3 Extents = Vector3.one * 10.0f; [Tooltip("How long to wait (in sec) between Spatial Mapping updates.")] public float TimeBetweenUpdates = 3.5f; [Tooltip("Recalculates normals whenever a mesh is updated.")] public bool RecalculateNormals = false; /// <summary> /// Event for hooking when surfaces are changed. /// </summary> public event SurfaceObserver.SurfaceChangedDelegate SurfaceChanged; /// <summary> /// Event for hooking when the data for a surface is ready. /// </summary> public event SurfaceObserver.SurfaceDataReadyDelegate DataReady; /// <summary> /// Our Surface Observer object for generating/updating Spatial Mapping data. /// </summary> private SurfaceObserver observer; /// <summary> /// A dictionary of surfaces that our Surface Observer knows about. /// Key: surface id /// Value: GameObject containing a Mesh, a MeshRenderer and a Material /// </summary> private Dictionary<int, GameObject> surfaces = new Dictionary<int, GameObject>(); /// <summary> /// A dictionary of surfaces which need to be cleaned up and readded for reuse. /// Key: ID of the surface currently updating /// Value: A struct encapsulating Visual and Collider mesh to be cleaned up /// </summary> private Dictionary<int, GameObject> pendingCleanup = new Dictionary<int, GameObject>(); /// <summary> /// A queue of clean surface GameObjects ready to be reused. /// </summary> private Queue<GameObject> availableSurfaces = new Queue<GameObject>(); /// <summary> /// A queue of SurfaceData objects. SurfaceData objects are sent to the /// SurfaceObserver to generate meshes of the environment. /// </summary> private Queue<SurfaceData> surfaceWorkQueue = new Queue<SurfaceData>(); /// <summary> /// To prevent too many meshes from being generated at the same time, we will /// only request one mesh to be created at a time. This variable will track /// if a mesh creation request is in flight. /// </summary> private bool surfaceWorkOutstanding = false; /// <summary> /// Used to track when the Observer was last updated. /// </summary> private float updateTime; /// <summary> /// Indicates the current state of the Surface Observer. /// </summary> public ObserverStates ObserverState { get; private set; } protected override void Awake() { base.Awake(); ObserverState = ObserverStates.Stopped; } /// <summary> /// Called once per frame. /// </summary> private void Update() { // Only do processing if the observer is running. if (ObserverState == ObserverStates.Running) { // If we don't have mesh creation in flight, but we could schedule mesh creation, do so. if (surfaceWorkOutstanding == false && surfaceWorkQueue.Count > 0) { // Pop the SurfaceData off the queue. A more sophisticated algorithm could prioritize // the queue based on distance to the user or some other metric. SurfaceData surfaceData = surfaceWorkQueue.Dequeue(); // If RequestMeshAsync succeeds, then we have successfully scheduled mesh creation. surfaceWorkOutstanding = observer.RequestMeshAsync(surfaceData, SurfaceObserver_OnDataReady); } // If we don't have any other work to do, and enough time has passed since the previous // update request, request updates for the spatial mapping data. else if (surfaceWorkOutstanding == false && (Time.time - updateTime) >= TimeBetweenUpdates) { observer.Update(SurfaceObserver_OnSurfaceChanged); updateTime = Time.time; } } } /// <summary> /// Starts the Surface Observer. /// </summary> public void StartObserving() { if (observer == null) { observer = new SurfaceObserver(); observer.SetVolumeAsAxisAlignedBox(Vector3.zero, Extents); } if (ObserverState != ObserverStates.Running) { Debug.Log("Starting the observer."); ObserverState = ObserverStates.Running; // We want the first update immediately. updateTime = 0; } } /// <summary> /// Stops the Surface Observer. /// </summary> /// <remarks>Sets the Surface Observer state to ObserverStates.Stopped.</remarks> public void StopObserving() { if (ObserverState == ObserverStates.Running) { Debug.Log("Stopping the observer."); ObserverState = ObserverStates.Stopped; } } /// <summary> /// Cleans up all memory and objects associated with the observer. /// </summary> public void CleanupObserver() { if (observer != null) { StopObserving(); // Clear out all memory allocated the observer observer.Dispose(); observer = null; foreach (KeyValuePair<int, GameObject> surfaceRef in surfaces) { CleanupSurface(surfaceRef.Value); } // Get all valid mesh filters for observed surfaces and destroy them List<MeshFilter> meshFilters = GetMeshFilters(); for (int i = 0; i < meshFilters.Count; i++) { Destroy(meshFilters[i].sharedMesh); } meshFilters.Clear(); // Cleanup all available surfaces foreach (GameObject availableSurface in availableSurfaces) { Destroy(availableSurface); } availableSurfaces.Clear(); surfaces.Clear(); } } /// <summary> /// Can be called to override the default origin for the observed volume. Can only be called while observer has been started. /// </summary> public bool SetObserverOrigin(Vector3 origin) { bool originUpdated = false; if (observer != null) { observer.SetVolumeAsAxisAlignedBox(origin, Extents); originUpdated = true; } return originUpdated; } /// <summary> /// Handles the SurfaceObserver's OnDataReady event. /// </summary> /// <param name="cookedData">Struct containing output data.</param> /// <param name="outputWritten">Set to true if output has been written.</param> /// <param name="elapsedCookTimeSeconds">Seconds between mesh cook request and propagation of this event.</param> private void SurfaceObserver_OnDataReady(SurfaceData cookedData, bool outputWritten, float elapsedCookTimeSeconds) { //We have new visuals, so we can disable and cleanup the older surface GameObject surfaceToCleanup; if (pendingCleanup.TryGetValue(cookedData.id.handle, out surfaceToCleanup)) { CleanupSurface(surfaceToCleanup); pendingCleanup.Remove(cookedData.id.handle); } GameObject surface; if (surfaces.TryGetValue(cookedData.id.handle, out surface)) { // Set the draw material for the renderer. MeshRenderer renderer = surface.GetComponent<MeshRenderer>(); renderer.sharedMaterial = SpatialMappingManager.Instance.SurfaceMaterial; renderer.enabled = SpatialMappingManager.Instance.DrawVisualMeshes; if (RecalculateNormals) { MeshFilter filter = surface.GetComponent<MeshFilter>(); if(filter != null && filter.sharedMesh != null) { filter.sharedMesh.RecalculateNormals(); } } if (SpatialMappingManager.Instance.CastShadows == false) { renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; } } surfaceWorkOutstanding = false; SurfaceObserver.SurfaceDataReadyDelegate dataReady = DataReady; if (dataReady != null) { dataReady(cookedData, outputWritten, elapsedCookTimeSeconds); } } private void CleanupSurface(GameObject surface) { // Destroy the meshes, and add the surface back for reuse CleanupMeshes(surface.GetComponent<MeshFilter>().sharedMesh, surface.GetComponent<MeshCollider>().sharedMesh); availableSurfaces.Enqueue(surface); surface.name = "Unused Surface"; surface.SetActive(false); } private void CleanupMeshes(Mesh visualMesh, Mesh colliderMesh) { if (colliderMesh != null && colliderMesh != visualMesh) { Destroy(colliderMesh); } if (visualMesh != null) { Destroy(visualMesh); } } private GameObject GetSurfaceObject(int surfaceID, Transform parentObject) { //If we have surfaces ready for reuse, use those first if (availableSurfaces.Count > 1) { GameObject existingSurface = availableSurfaces.Dequeue(); existingSurface.SetActive(true); existingSurface.name = string.Format("Surface-{0}", surfaceID); UpdateSurfaceObject(existingSurface, surfaceID); return existingSurface; } // If we are adding a new surface, construct a GameObject // to represent its state and attach some Mesh-related // components to it. GameObject toReturn = AddSurfaceObject(null, string.Format("Surface-{0}", surfaceID), transform, surfaceID); toReturn.AddComponent<WorldAnchor>(); return toReturn; } /// <summary> /// Handles the SurfaceObserver's OnSurfaceChanged event. /// </summary> /// <param name="id">The identifier assigned to the surface which has changed.</param> /// <param name="changeType">The type of change that occurred on the surface.</param> /// <param name="bounds">The bounds of the surface.</param> /// <param name="updateTime">The date and time at which the change occurred.</param> private void SurfaceObserver_OnSurfaceChanged(SurfaceId id, SurfaceChange changeType, Bounds bounds, System.DateTime updateTime) { // Verify that the client of the Surface Observer is expecting updates. if (ObserverState != ObserverStates.Running) { return; } GameObject surface; switch (changeType) { // Adding and updating are nearly identical. The only difference is if a new gameobject to contain // the surface needs to be created. case SurfaceChange.Added: case SurfaceChange.Updated: // Check to see if the surface is known to the observer. // If so, we want to add it for cleanup after we get new meshes // We do this because Unity doesn't properly cleanup baked collision data if (surfaces.TryGetValue(id.handle, out surface)) { pendingCleanup.Add(id.handle, surface); surfaces.Remove(id.handle); } // Get an available surface object ready to be used surface = GetSurfaceObject(id.handle, transform); // Add the surface to our dictionary of known surfaces so // we can interact with it later. surfaces.Add(id.handle, surface); // Add the request to create the mesh for this surface to our work queue. QueueSurfaceDataRequest(id, surface); break; case SurfaceChange.Removed: // Always process surface removal events. // This code can be made more thread safe if (surfaces.TryGetValue(id.handle, out surface)) { surfaces.Remove(id.handle); CleanupSurface(surface); RemoveSurfaceObject(surface, false); } break; } // Event if (SurfaceChanged != null) { SurfaceChanged(id, changeType, bounds, updateTime); } } /// <summary> /// Calls GetMeshAsync to update the SurfaceData and re-activate the surface object when ready. /// </summary> /// <param name="id">Identifier of the SurfaceData object to update.</param> /// <param name="surface">The SurfaceData object to update.</param> private void QueueSurfaceDataRequest(SurfaceId id, GameObject surface) { SurfaceData surfaceData = new SurfaceData(id, surface.GetComponent<MeshFilter>(), surface.GetComponent<WorldAnchor>(), surface.GetComponent<MeshCollider>(), TrianglesPerCubicMeter, true); surfaceWorkQueue.Enqueue(surfaceData); } /// <summary> /// Called when the GameObject is unloaded. /// </summary> private void OnDestroy() { // Stop the observer and clean it up. StopObserving(); CleanupObserver(); } } }
39.14321
136
0.557812
[ "MIT" ]
PaulDixon/VuforiaQR
Assets/HoloToolkit-SpatialMapping-230/SpatialMapping/Scripts/SpatialMappingObserver.cs
15,855
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("SampleSite")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SampleSite")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("2994ba69-cd5e-40f8-8942-e4c21dd514b7")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.444444
84
0.750742
[ "Apache-2.0" ]
RedoxEngine/.NET-Sample-App
SampleSite/Properties/AssemblyInfo.cs
1,351
C#
using System.Linq; using System.Threading.Tasks; using HotChocolate.Language; using StrawberryShake.CodeGeneration.Analyzers.Models; using StrawberryShake.CodeGeneration.Extensions; using Xunit; using static StrawberryShake.CodeGeneration.Mappers.TestDataHelper; namespace StrawberryShake.CodeGeneration.Mappers { public class DataTypeMapperTests { [Fact] public async Task MapDataTypeDescriptors_SimpleCase() { // arrange ClientModel clientModel = await CreateClientModelAsync( @" query GetHeroNodes { hero(episode: NEW_HOPE) { friends { nodes { name } } } } query GetHeroEdges { hero(episode: NEW_HOPE) { friends { edges { cursor } } } }"); // act var context = new MapperContext( "Foo.Bar", "FooClient", new Sha1DocumentHashProvider(), Descriptors.Operations.RequestStrategy.Default, new[] { TransportProfile.Default }); TypeDescriptorMapper.Map( clientModel, context); DataTypeDescriptorMapper.Map( clientModel, context); // assert Assert.Collection( context.DataTypes.OrderBy(t => t.RuntimeType.ToString()), type => { Assert.Equal( "CharacterConnectionData", type.RuntimeType.Name); Assert.Equal( "Foo.Bar.State", type.RuntimeType.NamespaceWithoutGlobal); Assert.Collection( type.Properties, property => { Assert.Equal( "Nodes", property.Name); Assert.Equal( "IGetHeroNodes_Hero_Friends_Nodes", property.Type.GetRuntimeType().Name); }, property => { Assert.Equal( "Edges", property.Name); Assert.Equal( "IGetHeroEdges_Hero_Friends_Edges", property.Type.GetRuntimeType().Name); }); }, type => { Assert.Equal( "CharacterEdgeData", type.RuntimeType.Name); Assert.Equal( "Foo.Bar.State", type.RuntimeType.NamespaceWithoutGlobal); Assert.Collection( type.Properties, property => { Assert.Equal( "Cursor", property.Name); Assert.Equal( "String", property.Type.GetRuntimeType().Name); }); }); } [Fact] public void MapDataTypeDescriptors_DataUnionType() { // arrange var clientModel = CreateClientModelAsync("union.query3.graphql", "union.schema.graphql"); // act var context = new MapperContext( "Foo.Bar", "FooClient", new Sha1DocumentHashProvider(), Descriptors.Operations.RequestStrategy.Default, new[] { TransportProfile.Default }); TypeDescriptorMapper.Map( clientModel, context); EntityTypeDescriptorMapper.Map( clientModel, context); DataTypeDescriptorMapper.Map( clientModel, context); // assert Assert.Collection( context.DataTypes.OrderBy(t => t.RuntimeType.ToString()), type => { Assert.Equal( "AuthorData", type.RuntimeType.Name); Assert.Equal( "Foo.Bar.State", type.RuntimeType.NamespaceWithoutGlobal); Assert.Collection( type.Properties.OrderBy(p => p.Name), property => { Assert.Equal( "Genres", property.Name); }, property => { Assert.Equal( "Name", property.Name); }); }, type => { Assert.Equal( "BookData", type.RuntimeType.Name); Assert.Equal( "Foo.Bar.State", type.RuntimeType.NamespaceWithoutGlobal); Assert.Collection( type.Properties.OrderBy(p => p.Name), property => { Assert.Equal( "Isbn", property.Name); }, property => { Assert.Equal( "Title", property.Name); }); }, type => { Assert.Equal( "ISearchResultData", type.RuntimeType.Name); Assert.Equal( "Foo.Bar.State", type.RuntimeType.NamespaceWithoutGlobal); Assert.Empty(type.Properties); }); } [Fact] public void MapDataTypeDescriptors_DataInterfaceType() { // arrange var clientModel = CreateClientModelAsync( "interface.query.graphql", "interface.schema.graphql"); // act var context = new MapperContext( "Foo.Bar", "FooClient", new Sha1DocumentHashProvider(), Descriptors.Operations.RequestStrategy.Default, new[] { TransportProfile.Default }); TypeDescriptorMapper.Map( clientModel, context); EntityTypeDescriptorMapper.Map( clientModel, context); DataTypeDescriptorMapper.Map( clientModel, context); // assert Assert.Collection( context.DataTypes.OrderBy(t => t.RuntimeType.ToString()), type => { Assert.Equal( "BookData", type.RuntimeType.Name); Assert.Equal( "Foo.Bar.State", type.RuntimeType.NamespaceWithoutGlobal); Assert.Collection( type.Properties.OrderBy(p => p.Name), property => { Assert.Equal( "Isbn", property.Name); }, property => { Assert.Equal( "Title", property.Name); }); }, type => { Assert.Equal( "IPrintData", type.RuntimeType.Name); Assert.Equal( "Foo.Bar.State", type.RuntimeType.NamespaceWithoutGlobal); Assert.Empty(type.Properties); }, type => { Assert.Equal( "ISearchResultData", type.RuntimeType.Name); Assert.Equal( "Foo.Bar.State", type.RuntimeType.NamespaceWithoutGlobal); Assert.Empty(type.Properties); }, type => { Assert.Equal( "MagazineData", type.RuntimeType.Name); Assert.Equal( "Foo.Bar.State", type.RuntimeType.NamespaceWithoutGlobal); Assert.Collection( type.Properties.OrderBy(p => p.Name), property => { Assert.Equal( "CoverImageUrl", property.Name); }, property => { Assert.Equal( "Isbn", property.Name); }); }); } } }
33.654839
87
0.346784
[ "MIT" ]
Megasware128/hotchocolate
src/StrawberryShake/CodeGeneration/test/CodeGeneration.Tests/Mappers/DataTypeMapperTests.cs
10,433
C#
//Released under the MIT License. // //Copyright (c) 2018 Ntreev Soft co., Ltd. // //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 Newtonsoft.Json.Converters; using Newtonsoft.Json.Schema; using Ntreev.Crema.Data; using Ntreev.Crema.ServiceModel; using Ntreev.Library; using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using System.Text; namespace Ntreev.Crema.Commands.Consoles.Serializations { struct JsonTableInfo { private string comment; private string tags; private JsonTableColumnInfo[] members; [JsonProperty(Required = Required.Always)] [RegularExpression(IdentifierValidator.IdentiFierPattern)] public string TableName { get; set; } [JsonProperty(Required = Required.DisallowNull, DefaultValueHandling = DefaultValueHandling.Ignore)] [DefaultValue("All")] public string Tags { get => this.tags ?? "All"; set => this.tags = value; } [JsonProperty(Required = Required.DisallowNull, DefaultValueHandling = DefaultValueHandling.Ignore)] [DefaultValue("")] public string Comment { get => this.comment ?? string.Empty; set => this.comment = value; } [JsonProperty] public JsonTableColumnInfo[] Columns { get => this.members ?? new JsonTableColumnInfo[] { }; set => this.members = value; } public static readonly JsonTableInfo Default = new JsonTableInfo() { TableName = string.Empty, Tags = $"{TagInfoUtility.All}", Comment = string.Empty, Columns = new JsonTableColumnInfo[] { new JsonTableColumnInfo() { Name = "Key", IsKey = true, IsUnique = true, Comment = string.Empty }, new JsonTableColumnInfo() { Name = "Value", Comment = string.Empty } }, }; public struct JsonTableColumnInfo { private string comment; private string dataType; private string tags; [JsonProperty(Required = Required.Always)] public string Name { get; set; } [JsonProperty(Required = Required.DisallowNull, DefaultValueHandling = DefaultValueHandling.Ignore)] [DefaultValue(false)] public bool IsKey { get; set; } [JsonProperty(Required = Required.DisallowNull, DefaultValueHandling = DefaultValueHandling.Ignore)] [DefaultValue("string")] public string DataType { get => this.dataType ?? "string"; set => this.dataType = value; } [JsonProperty(Required = Required.DisallowNull, DefaultValueHandling = DefaultValueHandling.Ignore)] [DefaultValue("")] public string Comment { get => this.comment ?? string.Empty; set => this.comment = value; } [JsonProperty(Required = Required.DisallowNull, DefaultValueHandling = DefaultValueHandling.Ignore)] [DefaultValue(false)] public bool IsUnique { get; set; } [JsonProperty(Required = Required.DisallowNull, DefaultValueHandling = DefaultValueHandling.Ignore)] [DefaultValue(false)] public bool AutoIncrement { get; set; } [JsonProperty(Required = Required.DisallowNull, DefaultValueHandling = DefaultValueHandling.Ignore)] [DefaultValue(null)] public string DefaultValue { get; set; } [JsonProperty(Required = Required.DisallowNull, DefaultValueHandling = DefaultValueHandling.Ignore)] [DefaultValue("All")] public string Tags { get => this.tags ?? "All"; set => this.tags = value; } [JsonProperty(Required = Required.DisallowNull, DefaultValueHandling = DefaultValueHandling.Ignore)] [DefaultValue(false)] public bool IsReadOnly { get; set; } } } }
39.134328
121
0.639016
[ "MIT" ]
NtreevSoft/Crema
common/Ntreev.Crema.Commands.Sharing/Consoles/Serializations/JsonTableInfo.cs
5,246
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Wollo.Entities.ViewModels; using Wollo.Web; using Wollo.Web.Helper; using Wollo.Web.Models; using Wollo.Web.Controllers.Helper; namespace Wollo.Web.Controllers { public class HomeController : BaseController { //[AuthorizeRole(Module = "Home", Permission = "View")] public ActionResult Index() { LandingPageViewModel model = new LandingPageViewModel(); ViewBag.UserName = User.Identity.Name; return View(model); } public ActionResult About() { ViewBag.Message = "Your application description page."; //HttpClient client = new HttpClient(); //string domain = ConfigurationManager.AppSettings["AppLocalUrl"]; //string url = domain + "api/Master/GetAllTransactionHistory"; //client.BaseAddress = new Uri(url); //client.DefaultRequestHeaders.Accept.Clear(); //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //HttpResponseMessage responseMessage = await client.GetAsync(url); //List<Stock_Code> resultObj = new List<Stock_Code>(); //if (responseMessage.IsSuccessStatusCode) //{ // var responseData = responseMessage.Content.ReadAsStringAsync().Result; // resultObj = JsonConvert.DeserializeObject<List<Stock_Code>>(responseData); //} //else //{ // // Api failed //} //return View(resultObj); return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } public ActionResult Facebook() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult UserAgreement() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Twitter() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult ChangeCurrentCulture(int id) { // // Change the current culture for this user. // CultureHelper.CurrentCulture = id; // // Cache the new current culture into the user HTTP session. // Session["CurrentCulture"] = id; // // Redirect to the same page from where the request was made! // return Redirect(Request.UrlReferrer.ToString()); } } }
31.092784
111
0.577586
[ "MIT" ]
umangsunarc/OTH
Wollo.Web/Controllers/HomeController.cs
3,018
C#
namespace Endahl.CSharpedSql { using Endahl.CSharpedSql.Base; using System.Collections.Generic; /// <summary> /// JOIN clause in SQL /// </summary> public class Join { public virtual IList<Join> Joins { get; } public virtual string TableName { get; } public virtual string TableName2 { get; } public virtual JoinType JoinType { get; } public virtual string Column { get; } public virtual string Column2 { get; } protected Join(JoinType join, string table, string column, string table2, string column2) { Joins = new List<Join>(); TableName = table; TableName2 = table2; JoinType = join; Column = column; Column2 = column2; } public static Join operator +(Join join, Join join1) { join.Joins.Add(join1); return join; } /// <summary> /// Return the <see cref="Join"/> clause as a string. the string will be missing a table name. /// </summary> public override string ToString() { return ToString(new SqlOptions()); } /// <summary> /// Return the <see cref="Join"/> clause as a string /// </summary> public virtual string ToString(SqlOptions sql) { return sql.SqlBase.Join(this, sql); } /// <summary> /// The INNER JOIN keyword selects records that have matching values in both tables. /// </summary> /// <param name="table">the table to join with</param> /// <param name="table2">the table to join with</param> /// <param name="column">the column from the table to join on</param> /// <param name="column2">the column from the table to join with</param> public static Join Inner(string table, string column, string table2, string column2) { return new Join(JoinType.Inner, table, column, table2, column2); } /// <summary> /// The LEFT JOIN keyword returns all records from the left table (table1), /// and the matched records from the right table (table2). /// The result is NULL from the right side, if there is no match. /// </summary> /// <param name="table">the table to join with</param> /// <param name="table2">the table to join with</param> /// <param name="column">the column from the table to join on</param> /// <param name="column2">the column from the table to join with</param> public static Join Left(string table, string column, string table2, string column2) { return new Join(JoinType.Left, table, column, table2, column2); } /// <summary> /// The RIGHT JOIN keyword returns all records from the right table (table2), /// and the matched records from the left table (table1). /// The result is NULL from the left side, when there is no match. /// </summary> /// <param name="table">the table to join with</param> /// <param name="table2">the table to join with</param> /// <param name="column">the column from the table to join on</param> /// <param name="column2">the column from the table to join with</param> public static Join Right(string table, string column, string table2, string column2) { return new Join(JoinType.Right, table, column, table2, column2); } /// <summary> /// he FULL OUTER JOIN keyword return all records when there is a match in either left (table1) or right (table2) table records. /// <para>Note: FULL OUTER JOIN can potentially return very large result-sets!</para> /// </summary> /// <param name="table">the table to join with</param> /// <param name="table2">the table to join with</param> /// <param name="column">the column from the table to join on</param> /// <param name="column2">the column from the table to join with</param> public static Join Full(string table, string column, string table2, string column2) { return new Join(JoinType.FullOuter, table, column, table2, column2); } } }
41.375
136
0.59168
[ "MIT" ]
Endahl/CSharpedSql
Endahl.CSharpedSql/Join.cs
4,305
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/winnt.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop { public unsafe partial struct XSAVE_AREA_HEADER { [NativeTypeName("DWORD64")] public ulong Mask; [NativeTypeName("DWORD64")] public ulong CompactionMask; [NativeTypeName("DWORD64 [6]")] public fixed ulong Reserved2[6]; } }
29.8
145
0.692953
[ "MIT" ]
Ethereal77/terrafx.interop.windows
sources/Interop/Windows/um/winnt/XSAVE_AREA_HEADER.cs
598
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using BenchmarkDotNet.Environments; using BenchmarkDotNet.Portability; using JetBrains.Annotations; using Microsoft.DotNet.PlatformAbstractions; namespace BenchmarkDotNet.Toolchains.DotNetCli { [SuppressMessage("ReSharper", "InconsistentNaming")] public abstract class CustomDotNetCliToolchainBuilder { protected readonly Dictionary<string, string> Feeds = new Dictionary<string, string>(); protected string runtimeIdentifier, customDotNetCliPath; protected string displayName; protected string runtimeFrameworkVersion; protected bool useNuGetClearTag, useTempFolderForRestore; private string targetFrameworkMoniker; public abstract IToolchain ToToolchain(); /// <summary>it allows you to define an additional NuGet feed, you can seal the feeds list by using the UseNuGetClearTag() method</summary> /// <param name="feedName">the name of the feed, will be used in the auto-generated NuGet.config file</param> /// <param name="feedAddress">the address of the feed, will be used in the auto-generated NuGet.config file</param> [PublicAPI] public CustomDotNetCliToolchainBuilder AdditionalNuGetFeed(string feedName, string feedAddress) { if (string.IsNullOrEmpty(feedName)) throw new ArgumentException("Value cannot be null or empty.", nameof(feedName)); if (string.IsNullOrEmpty(feedAddress)) throw new ArgumentException("Value cannot be null or empty.", nameof(feedAddress)); Feeds[feedName] = feedAddress; return this; } /// <summary> /// emits clear tag in the auto-generated NuGet.config file /// </summary> public CustomDotNetCliToolchainBuilder UseNuGetClearTag(bool value) { useNuGetClearTag = value; return this; } /// <param name="targetFrameworkMoniker">TFM, example: netcoreapp2.1</param> [PublicAPI] [SuppressMessage("ReSharper", "ParameterHidesMember")] public CustomDotNetCliToolchainBuilder TargetFrameworkMoniker(string targetFrameworkMoniker) { this.targetFrameworkMoniker = targetFrameworkMoniker ?? throw new ArgumentNullException(nameof(targetFrameworkMoniker)); return this; } protected string GetTargetFrameworkMoniker() { if (!string.IsNullOrEmpty(targetFrameworkMoniker)) return targetFrameworkMoniker; if (!RuntimeInformation.IsNetCore) throw new NotSupportedException("You must specify the target framework moniker in explicit way using builder.TargetFrameworkMoniker(tfm) method"); return CoreRuntime.GetCurrentVersion().MsBuildMoniker; } /// <param name="newCustomDotNetCliPath">if not provided, the one from PATH will be used</param> [PublicAPI] public CustomDotNetCliToolchainBuilder DotNetCli(string newCustomDotNetCliPath) { if (!string.IsNullOrEmpty(newCustomDotNetCliPath) && !File.Exists(newCustomDotNetCliPath)) throw new FileNotFoundException("Given file does not exist", newCustomDotNetCliPath); customDotNetCliPath = newCustomDotNetCliPath; return this; } /// <param name="newRuntimeIdentifier">if not provided, portable OS-arch will be used (example: "win-x64", "linux-x86")</param> [PublicAPI] public CustomDotNetCliToolchainBuilder RuntimeIdentifier(string newRuntimeIdentifier) { runtimeIdentifier = newRuntimeIdentifier; return this; } /// <param name="newRuntimeFrameworkVersion">optional, when set it's copied to the generated .csproj file</param> [PublicAPI] public CustomDotNetCliToolchainBuilder RuntimeFrameworkVersion(string newRuntimeFrameworkVersion) { runtimeFrameworkVersion = newRuntimeFrameworkVersion; return this; } /// <param name="newDisplayName">the name of the toolchain to be displayed in results</param> [PublicAPI] public CustomDotNetCliToolchainBuilder DisplayName(string newDisplayName) { if (string.IsNullOrEmpty(newDisplayName)) throw new ArgumentException("Value cannot be null or empty.", nameof(newDisplayName)); displayName = newDisplayName; return this; } /// <summary> /// restore to temp folder to keep your CI clean or install same package many times (perhaps with different content but same version number), by default true for local builds /// https://github.com/dotnet/corefx/blob/master/Documentation/project-docs/dogfooding.md#3---consuming-subsequent-code-changes-by-rebuilding-the-package-alternative-2 /// </summary> [PublicAPI] public CustomDotNetCliToolchainBuilder UseTempFolderForRestore(bool value) { useTempFolderForRestore = value; return this; } internal static string GetPortableRuntimeIdentifier() { // Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment.GetRuntimeIdentifier() // returns win10-x64, we want the simpler form win-x64 // the values taken from https://docs.microsoft.com/en-us/dotnet/core/rid-catalog#macos-rids string osPart = RuntimeInformation.IsWindows() ? "win" : (RuntimeInformation.IsMacOSX() ? "osx" : "linux"); return $"{osPart}-{RuntimeEnvironment.RuntimeArchitecture}"; } } }
42.93985
182
0.684994
[ "MIT" ]
AndyAyersMS/BenchmarkDotNet
src/BenchmarkDotNet/Toolchains/DotNetCli/CustomDotNetCliToolchainBuilder.cs
5,713
C#
using System; namespace Structr.Abstractions.Extensions { public static class LongExtensions { public static string ToFileSizeString(this long value) { string[] sizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" }; if (value < 0) { return "-" + (-value).ToFileSizeString(); } if (value == 0) { return "0.0 bytes"; } int mag = (int)Math.Log(value, 1024); decimal adjustedSize = (decimal)value / (1L << (mag * 10)); return string.Format("{0:n1} {1}", adjustedSize, sizeSuffixes[mag]); } } }
31.1
96
0.536977
[ "MIT" ]
askalione/Structr
src/Structr.Abstractions/Extensions/LongExtensions.cs
622
C#
using System; namespace Computers { class Program { static void Main(string[] args) { } } }
10.846154
39
0.460993
[ "MIT" ]
Anzzhhela98/CSharp-Advanced
C# OOP/Exam Preparation/C# OOP Exam - 16 August 2020/Unit-Test/Computers-Skeleton/Computers/Program.cs
143
C#
using UnityEngine; public class Cube : MonoBehaviour { private Vector3 toPosition = new Vector3(0f, 3f, 0f); void Update () { if (this.toPosition.y - transform.position.y <= 0.1f) { this.toPosition = new Vector3(0f, -3f, 0f); } else if (transform.position.y - this.toPosition.y <= 0.1f) { this.toPosition = new Vector3(0f, 3f, 0f); } transform.position = transform.position + this.toPosition * 1f * Time.deltaTime; transform.Rotate (new Vector3 (Time.deltaTime * 30f, 10f, 5f)); } }
29.764706
82
0.677866
[ "MIT" ]
tkyaji/UnityRecShare
RecShare/Assets/RecShare/Sample/Cube.cs
508
C#
using OC.DiscordBotServer.Common; using OC.DiscordBotServer.Helpers; using OC.DiscordBotServer.Models; using OC.DiscordBotServer.Repositories; using System.Collections.Concurrent; using System.Net; namespace OC.DiscordBotServer { public class ApplicationContext { private readonly IRepository<OCUser> _repositoryOCUser; private readonly IRepository<Chanel2Server> _repositoryChanel2Server; /// <summary> /// Id DiscordChannel => Chanel2Server /// </summary> public ConcurrentDictionary<ulong, SessionClientWrapper> DiscrordToOCServer { get; set; } = new ConcurrentDictionary<ulong, SessionClientWrapper>(); /// <summary> /// Online City Server => Discord Server /// </summary> public ConcurrentDictionary<IPEndPoint, ulong> OCServerToDiscrord { get; set; } = new ConcurrentDictionary<IPEndPoint, ulong>(); /// <summary> /// Each row contains Users per server /// </summary> public ConcurrentDictionary<ulong, ConcurrentDictionary<ulong, OCUser>> UserOnServers = new ConcurrentDictionary<ulong, ConcurrentDictionary<ulong, OCUser>>(); public ApplicationContext(IRepository<OCUser> userRepository, IRepository<Chanel2Server> serversRepository) { _repositoryOCUser = userRepository; _repositoryChanel2Server = serversRepository; foreach (var server in serversRepository.GetAll()) { RegisterNewServer(server, new SessionClientWrapper(server)); } foreach (var user in userRepository.GetAll()) { UserOnServers[user.DiscordIdChanel][user.UserId] = user; } } public OCUser TryGetOCUser(ulong idChannel, ulong idUser) { if (!UserOnServers.TryGetValue(idChannel, out ConcurrentDictionary<ulong, OCUser> OCUsers)) { return null; } if (!OCUsers.TryGetValue(idUser, out OCUser OCUser)) { return null; } return OCUser; } internal bool RegisterNewServer(Chanel2Server server, SessionClientWrapper sessionClient) { var apadr = IPAddress.Parse(server.IP); var endPoint = new IPEndPoint(apadr, server.Port); var result = OCServerToDiscrord.TryAdd(endPoint, server.Id) && UserOnServers.TryAdd(server.Id, new ConcurrentDictionary<ulong, OCUser>()); result &= DiscrordToOCServer.TryAdd(server.Id, sessionClient); // if sessionClient.IsLogined then must be registred in DataBase if (sessionClient.IsLogined) { result &= _repositoryChanel2Server.AddNewItem(server); } else { result &= sessionClient.ConnectAndLogin(); } return result; } public SessionClientWrapper TryGetSessionClientByIP(string ip) { var ipPont = Helper.TryParseStringToIp(ip); if (ipPont == null) { return null; } if (!OCServerToDiscrord.TryGetValue(ipPont, out ulong discordID)) { return null; } DiscrordToOCServer.TryGetValue(discordID, out SessionClientWrapper result); return result; } } }
35.40404
167
0.601427
[ "Apache-2.0" ]
Husky333/CityOfXIAOSU
Source/DiscordChatBotServer/ApplicationContext.cs
3,507
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Handelabra.Sentinels.Engine.Controller; using Handelabra.Sentinels.Engine.Model; namespace Cauldron.CatchwaterHarbor { public class ToOverbrookCardController : CatchwaterHarborUtilityCardController { public ToOverbrookCardController(Card card, TurnTakerController turnTakerController) : base(card, turnTakerController) { } } }
25.833333
126
0.778495
[ "MIT" ]
qoala/CauldronMods
Controller/Environments/CatchwaterHarbor/Cards/ToOverbrookCardController.cs
467
C#
using Microsoft.EntityFrameworkCore.Migrations.Operations; using System; using System.Collections.Generic; using System.DirectoryServices; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; namespace api_netCore { public class Utilz { public class Criptografia { private const int Keysize = 128; private const int DerivationIterations = 1000; public static string Criptografar(string plainText, string chave) { // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text // so that the same Salt and IV values can be used when decrypting. var saltStringBytes = Generate256BitsOfRandomEntropy(); var ivStringBytes = Generate256BitsOfRandomEntropy(); var plainTextBytes = Encoding.UTF8.GetBytes(plainText); using (var password = new Rfc2898DeriveBytes(chave, saltStringBytes, DerivationIterations)) { var keyBytes = password.GetBytes(Keysize / 8); using (var symmetricKey = new RijndaelManaged()) { symmetricKey.BlockSize = 128; symmetricKey.Mode = CipherMode.CBC; symmetricKey.Padding = PaddingMode.PKCS7; using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes)) { using (var memoryStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes. var cipherTextBytes = saltStringBytes; cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray(); cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray(); memoryStream.Close(); cryptoStream.Close(); return Convert.ToBase64String(cipherTextBytes); } } } } } } public static string Descriptografar(string cipherText, string chave) { try { var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText); var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray(); var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray(); var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray(); using (var password = new Rfc2898DeriveBytes(chave, saltStringBytes, DerivationIterations)) { var keyBytes = password.GetBytes(Keysize / 8); using (var symmetricKey = new RijndaelManaged()) { symmetricKey.BlockSize = 128; symmetricKey.Mode = CipherMode.CBC; symmetricKey.Padding = PaddingMode.PKCS7; using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes)) { using (var memoryStream = new MemoryStream(cipherTextBytes)) { using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) { var plainTextBytes = new byte[cipherTextBytes.Length]; var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); memoryStream.Close(); cryptoStream.Close(); return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount); } } } } } } catch (Exception ex) { return ""; } } private static byte[] Generate256BitsOfRandomEntropy() { var randomBytes = new byte[16]; using (var rngCsp = new RNGCryptoServiceProvider()) { rngCsp.GetBytes(randomBytes); } return randomBytes; } } public static int GetId(string ma) { if(ma.Length>=6) { var db = new Banco(); Registro rg = new Registro(); rg.Tabela = Vars.TabelaUsers; rg.Filtros.Add(new Celula("user", ma)); rg.Banco = Vars.BancoUsers; var users = db.Consulta(rg,new Tabela()); if(users.Linhas.Count>0) { return users.Linhas[0].Get("id").Int(); } } return -1; } public static Registro GetUser(string ma, string s) { if (ma.Length >= 6) { var db = new Banco(); Registro rg = new Registro(); rg.Tabela = Vars.TabelaUsers; rg.Filtros.Add(new Celula("user", ma)); rg.Banco = Vars.BancoUsers; var users = db.Consulta(rg, new Tabela()); if (users.Linhas.Count > 0) { var user = users.Linhas[0]; if(user.Get("s").ToString() == "") { if(s.Length<6) { user.Status = "Senha deve conter pelo menos 6 caracteres"; } var senha = Utilz.Criptografia.Criptografar(s, Vars.Chave_Criptografia); user.Set("s", senha); Registro pp = new Registro(); pp.Tabela = Vars.TabelaUsers; pp.Banco = Vars.BancoUsers; pp.Filtros.Add(new Celula("user", ma)); pp.Valores.Add(new Celula("s",senha)); string mensagem; db.Atualizar(pp, out mensagem); } return user; } } return new Registro() { Status = "Usuário não encontrado"}; } public static Tabela Logar(Tabela retorno) { try { var regexItem = new Regex(@"^\w+$"); if (retorno.Status != "OK") { return retorno; } if (retorno.user == null | retorno.user == "" | retorno.s == "" | retorno.s == null) { retorno.Status = "Faltam dados de login."; return retorno; } else if(!regexItem.IsMatch(retorno.user)) { retorno.Status = "USER não pode conter caracteres especiais."; return retorno; } else if (retorno.user.Length < 6) { retorno.Status = "USER deve conter pelo menos 6 caracteres."; return retorno; } if (Banco.Tipo == Tipo_Conexao.SemActiveDirectory) { retorno.Status = "OK"; var s = GetUser(retorno.user, retorno.s); retorno.id_user = s.Get("id").Int(); retorno.Nome = s.Get("nome").ToString(); retorno.Email = s.Get("email").ToString(); var ss = s.Get("s").ToString(); var senha = Utilz.Criptografia.Descriptografar(ss,"sdaqwer123"); if (senha.ToUpper().Replace(" ","") == retorno.s.ToUpper().Replace(" ","")) { retorno.Status = "OK"; } else { retorno.Status = "Senha Incorreta. Se tem certeza que sua senha está correta, solicite para resetar a senha para o administrador."; } if(retorno.id_user<=0) { retorno.Status = "Usuário não cadastrado."; } return retorno; } else { System.DirectoryServices.DirectoryEntry directoryEntry = new System.DirectoryServices.DirectoryEntry(Vars.LDAP, retorno.user, retorno.s); DirectorySearcher busca = new DirectorySearcher(directoryEntry); busca.PageSize = 1000; busca.SearchScope = SearchScope.Subtree; busca.Filter = "(&(samAccountType=805306368)(sAMAccountName=" + retorno.user + "))"; busca.PropertiesToLoad.Add("givenName"); // nome busca.PropertiesToLoad.Add("sn"); // sobrenome busca.PropertiesToLoad.Add("mail"); // email SearchResult resultados = null; resultados = busca.FindOne(); if (resultados != null) { retorno.id_user = GetId(retorno.user); string nome = resultados.Properties["givenName"][0].ToString(); string sobrenome = resultados.Properties["sn"][0].ToString(); string email = resultados.Properties["mail"][0].ToString(); retorno.Nome = $"{nome} {sobrenome}"; retorno.Email = email; if (retorno.id_user < 0) { Registro rg = new Registro(); rg.Tabela = Vars.TabelaUsers; rg.Banco = Vars.BancoUsers; rg.Valores.Add(new Celula("user", retorno.user)); rg.Valores.Add(new Celula("nome", $"{nome} {sobrenome}".ToUpper())); rg.Valores.Add(new Celula("email", email)); var db = new Banco(); string msg; retorno.id_user = (int)db.Cadastro(rg, out msg); if (retorno.id_user > 0) { retorno.Mensagem = "Novo usuário cadastrado no sistema. Solicite para que seja categorizado."; } else { retorno.Status = "Erro ao tentar criar usuário " + msg; return retorno; } } retorno.Status = "OK"; return retorno; } else if (resultados == null) { retorno.Status = "Usuário não encontrado."; return retorno; } } } catch (Exception ex) { retorno.Status = "Erro ao tentar logar na rede Medabil: " + ex.Message; return retorno; } retorno.Status = "OK"; return retorno; } public static string aspas { get; set; } = "\""; public static DateTime Data(string Data) { try { return Convert.ToDateTime(Data); } catch (Exception) { } return new DateTime(1, 1, 1); } private static System.Globalization.CultureInfo US { get; set; } = new System.Globalization.CultureInfo("en-US"); private static System.Globalization.CultureInfo BR { get; set; } = new System.Globalization.CultureInfo("pt-BR"); public static double Double(object comp, int Decimais = 4) { try { double val; if (double.TryParse(comp.ToString(), System.Globalization.NumberStyles.Float, BR, out val)) { try { return Math.Round(val, Decimais); } catch (Exception) { return val; } } else if (double.TryParse(comp.ToString(), System.Globalization.NumberStyles.Float, US, out val)) { try { return Math.Round(val, Decimais); } catch (Exception) { return val; } } else return 0; } catch (Exception) { return 0; } } public static int Int(object comp) { string comps = comp.ToString(); if (comps == "") { comps = "0"; } try { return Convert.ToInt32(Math.Ceiling(Double(comps.Replace(".", ",")))); } catch (Exception) { return 0; } } public static bool Boolean(object obj) { try { return Convert.ToBoolean(obj); } catch (Exception) { return false; } } } }
39.256614
169
0.434126
[ "MIT" ]
xaotix/Api_NetCore
WEBAPI_MySQL/Util/Utilz.cs
14,851
C#
using UnityEngine; namespace Playcraft { public interface IMoveAndRotate { float moveSpeed { get; } float turnSpeed { get; } } public class Footsteps : MonoBehaviour { #pragma warning disable 0649 [SerializeField] float stepsPerMeter = 2f; [SerializeField] float stepsPerAngle = 0.02f; [SerializeField] float maxStepCheckTime = .5f; [SerializeField] GameObject movementContainer; #pragma warning restore 0649 IMoveAndRotate movement; MultiSound sound; bool grounded; public void SetGrounded(bool value) { grounded = value; } bool isMoving; public void SetMovement(bool value) { isMoving = value; } bool isTurning; public void SetTurning(bool value) { isTurning = value; } float nextStepDelay = 0.5f; void Start() { sound = GetComponent<MultiSound>(); movement = movementContainer.GetComponent<IMoveAndRotate>(); Invoke(nameof(RequestStep), nextStepDelay); } void RequestStep() { if (grounded) { if (isMoving) { nextStepDelay = 1 / (movement.moveSpeed * stepsPerMeter); sound.PlayRandom(); } else if (isTurning) { nextStepDelay = 1 / (movement.turnSpeed * stepsPerAngle); sound.PlayRandom(); } else nextStepDelay = 0.5f; } if (nextStepDelay > maxStepCheckTime) nextStepDelay = maxStepCheckTime; Invoke(nameof(RequestStep), nextStepDelay); } } }
27.298507
77
0.523237
[ "MIT" ]
Will9371/Character-Template
Assets/Playcraft/Quality of Life/Sound/Footsteps.cs
1,831
C#
using System; using System.ComponentModel; using Foundation; using Plugin.MaterialDesignControls.Implementations; using Plugin.MaterialDesignControls.iOS; using Plugin.MaterialDesignControls.iOS.Utils; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof(CustomDatePicker), typeof(MaterialDatePickerRenderer))] namespace Plugin.MaterialDesignControls.iOS { public class MaterialDatePickerRenderer : DatePickerRenderer { public static void Init() { } protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.DatePicker> e) { base.OnElementChanged(e); if (this.Control != null) { this.Control.BorderStyle = UITextBorderStyle.None; if (this.Element is CustomDatePicker customDatePicker) { this.Control.TextAlignment = TextAlignmentHelper.Convert(customDatePicker.HorizontalTextAlignment); if (!customDatePicker.Date.HasValue && !string.IsNullOrEmpty(customDatePicker.Placeholder)) { this.Control.Text = null; this.Control.AttributedPlaceholder = new NSAttributedString(customDatePicker.Placeholder, foregroundColor: customDatePicker.PlaceholderColor.ToUIColor()); } if (UIDevice.CurrentDevice.CheckSystemVersion(13, 2)) { try { UIDatePicker picker = (UIDatePicker)Control.InputView; picker.PreferredDatePickerStyle = UIDatePickerStyle.Wheels; } catch (Exception) { } } } } } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); // Set the default date if the user doesn't select anything var customDatePicker = (CustomDatePicker)Element; if (e.PropertyName == "IsFocused" && !customDatePicker.IsFocused && !customDatePicker.Date.HasValue) Control.Text = customDatePicker.InternalDateTime.ToString(customDatePicker.Format); } } }
40.183333
178
0.608876
[ "MIT" ]
ClayAchahui/MaterialDesignControlsPlugin-1
src/MaterialDesignControls.iOS/Renderers/MaterialDatePickerRenderer.cs
2,413
C#
using UnityEngine; namespace UnityEditor.Timeline { enum TrimEdge { Start, End } interface ITrimItemMode { void OnBeforeTrim(ITrimmable item, TrimEdge trimDirection); void TrimStart(ITrimmable item, double time); void TrimEnd(ITrimmable item, double time, bool affectTimeScale); } interface ITrimItemDrawer { void DrawGUI(WindowState state, Rect bounds, Color color, TrimEdge edge); } }
20.75
82
0.624498
[ "Apache-2.0" ]
yeliheng/BasketballVR
Library/PackageCache/com.unity.timeline@1.1.0/Editor/Manipulators/Trim/ITrimItemMode.cs
498
C#
using agorartc; using ClubHouse.Common; using ClubHouse.Domain.Models; using ClubHouse.Domain.Models.Request; using ClubHouse.Domain.Models.Response; using ClubHouse.Domain.Services; using ClubHouse.Domain.Services.Common; using ClubHouse.UI.DesktopApp.Models; using ClubHouse.UI.DesktopApp.ViewModels; using ClubHouse.UI.DesktopApp.Views; using MaterialDesignThemes.Wpf; using PubnubApi; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Unity; namespace ClubHouse.UI.DesktopApp.Handler { public class RoomManagerService : BaseViewModel, IDisposable { private readonly IChannelService _channelService; private readonly IAccountService _accountService; private readonly IMessageService _messageService; private readonly AgoraRtcEngine _rtcEngine; private readonly ISerializer _serializer; private readonly IUnityContainer _unityContainer; private readonly ClubHouseEventHandler eventHandler; private CancellationTokenSource _cancelationTokenSource; private CancellationTokenSource _raiseHandCancelationTokenSource; private BaseChannelResponse channelInfo; private bool raisingHand; private RoomUserCollections joinedUsers; private bool speakerMuted; private bool microphoneMuted; private BindableChannelUser currentUserInfo; private Pubnub pubnub; public delegate void Join(BaseChannelResponse channel); public event Join OnJoined; public event Join OnLeave; public RoomManagerService(IChannelService channelService, IAccountService accountService, IMessageService messageService, AgoraRtcEngine rtcEngine, ISerializer serializer, IUnityContainer unityContainer) { _channelService = channelService; _accountService = accountService; _messageService = messageService; _serializer = serializer; _unityContainer = unityContainer; JoinedUsers = new RoomUserCollections(); eventHandler = new ClubHouseEventHandler(JoinedUsers); //eventHandler.OnRefereshRoom += GetDetail; _rtcEngine = rtcEngine; _rtcEngine.Initialize(APIConsts.AGORA_KEY, AREA_CODE.AREA_CODE_GLOBAL); _rtcEngine.InitEventHandler(eventHandler); _cancelationTokenSource = new CancellationTokenSource(); _raiseHandCancelationTokenSource = new CancellationTokenSource(); } public void Dispose() { DisposeRoom(); _cancelationTokenSource.Dispose(); _raiseHandCancelationTokenSource.Dispose(); } public BaseChannelResponse ChannelInfo { get => channelInfo; set => SetProperty(ref channelInfo, value); } public RoomUserCollections JoinedUsers { get => joinedUsers; set => SetProperty(ref joinedUsers, value); } public BindableChannelUser CurrentUserInfo { get => currentUserInfo; set => SetProperty(ref currentUserInfo, value); } public bool RaisingHand { get => raisingHand; set => SetProperty(ref raisingHand, value); } public bool SpeakerMuted { get => speakerMuted; set => SetProperty(ref speakerMuted, value); } public bool MicrophoneMuted { get => microphoneMuted; set => SetProperty(ref microphoneMuted, value); } public bool Joined { get; private set; } public IEnumerable<BindableChannelUser> Speakers { get => JoinedUsers.Where(u => u.Is_speaker); } public async Task<InitChannelResponse> JoinRoom(string channel) { if (ChannelInfo != null && (string.IsNullOrEmpty(channel) || channel != ChannelInfo.Channel)) await LeaveRoom(); JoinChannelResponse apiResult = await _channelService.Join(new JoinChannelRequest { Channel = channel }); if (string.IsNullOrEmpty(apiResult?.Token) || !apiResult.Success) { _messageService.Show(apiResult?.Error_message ?? "Failed to join room"); } return apiResult; } public void InitRoom(InitChannelResponse channelInfo) { if (string.IsNullOrEmpty(channelInfo?.Token) || !channelInfo.Success) { _messageService.Show("Failed To open room."); return; } var joinResult = _rtcEngine.JoinChannel(channelInfo.Token, channelInfo.Channel, "", (uint)_accountService.CurrentConfig.UserId.Value); if (joinResult != ERROR_CODE.ERR_OK) { _messageService.Show($"Failed to join RTCEngine. Error code is {joinResult}"); return; } ChannelInfo = channelInfo; JoinedUsers.Clear(); JoinedUsers.AddRange(channelInfo.Users.Select(u => new BindableChannelUser(u))); JoinedUsers.RefereshView(); CurrentUserInfo = JoinedUsers.Find(_accountService.CurrentConfig.UserId ?? 0); InitPubNub(channelInfo); _cancelationTokenSource.Dispose(); _cancelationTokenSource = new CancellationTokenSource(); _ = Task.Run(ActivePing); Joined = true; OnJoined?.Invoke(channelInfo); } private void InitPubNub(InitChannelResponse channelInfo) { if (!channelInfo.Pubnub_enable) { return; } PNConfiguration pnConfiguration = new() { SubscribeKey = channelInfo.Pubnub_sub_key ?? APIConsts.PUBNUB_SUB_KEY, PublishKey = channelInfo.Pubnub_pub_key ?? APIConsts.PUBNUB_PUB_KEY, Uuid = _accountService.CurrentConfig.UserId.ToString(), Origin = channelInfo.Pubnub_origin, AuthKey = channelInfo.Pubnub_token, PresenceTimeout = channelInfo.Pubnub_heartbeat_value }; pnConfiguration.SetPresenceTimeoutWithCustomInterval(channelInfo.Pubnub_heartbeat_value, channelInfo.Pubnub_heartbeat_interval); pubnub = new Pubnub(pnConfiguration); pubnub.AddListener(new SubscribeCallbackExt( PubNubMessageActions, delegate (Pubnub pnObj, PNPresenceEventResult presenceEvnt) { if (presenceEvnt != null) { Debug.WriteLine("Pubnub subscribeCallback received PNPresenceEventResult: " + presenceEvnt.Channel + " " + presenceEvnt.Occupancy + " " + presenceEvnt.Event); } }, delegate (Pubnub pnObj, PNStatus pnStatus) { if (pnStatus.Category != PNStatusCategory.PNConnectedCategory) { Debug.WriteLine($"Pubnub Error: {pnStatus.Category}, {pnStatus.ErrorData?.Information}"); } })); List<string> pubnubChannels = new() { "users." + CurrentUserInfo.User_id, "channel_user." + channelInfo.Channel + "." + CurrentUserInfo.User_id, "channel_all." + channelInfo.Channel, }; if (CurrentUserInfo.Is_moderator) { pubnubChannels.Add("channel_speakers." + channelInfo.Channel); } pubnub.Subscribe<string>() .Channels(pubnubChannels.ToArray()) .Execute(); } public async void ChangeRaiseHand() { var apiResult = await _channelService.RaiseHands(new RaiseHandsRequest { Channel = ChannelInfo.Channel, Raise_hands = !RaisingHand, Unraise_hands = RaisingHand }); if (apiResult == null || !apiResult.Success) { _messageService.Show($"Failed to raise hand. errorMessage is {apiResult.Error_message}"); return; } RaisingHand = !RaisingHand; if (RaisingHand) { _raiseHandCancelationTokenSource.Dispose(); _raiseHandCancelationTokenSource = new CancellationTokenSource(); _ = Task.Run(CheckAcceptSpeakerInvition); } else { _raiseHandCancelationTokenSource.Cancel(); } } public void ChangeSpeakerMute() { if (ChannelInfo == null) return; var result = _rtcEngine.MuteAllRemoteAudioStreams(!SpeakerMuted); if (result != ERROR_CODE.ERR_OK) { _messageService.Show($"Failed to mute the speaker. RTC engine returned {result} code"); return; } SpeakerMuted = !SpeakerMuted; } public void ChangeMicrophoneMute() { if (ChannelInfo == null) return; var result = _rtcEngine.MuteLocalAudioStream(!MicrophoneMuted); if (result != ERROR_CODE.ERR_OK) { _messageService.Show($"Failed to mute the Mic. RTC engine returned {result} Code"); return; } MicrophoneMuted = !MicrophoneMuted; var userInfo = JoinedUsers.Find(_accountService.CurrentConfig.UserId ?? 0); if (userInfo != null) { userInfo.Is_muted = MicrophoneMuted; } } public async void ChangeUserMicrophoneMuted(BindableChannelUser user) { if (ChannelInfo == null || user == null || CurrentUserInfo?.Is_moderator != true) return; var apiResult = await _channelService.MuteSpeaker(new ChannelUserRequest() { Channel = ChannelInfo.Channel, User_id = user.User_id }); if (!apiResult.Success) { _messageService.Show($"{apiResult.Error_message}"); } //var result = _rtcEngine.MuteRemoteAudioStream((uint)user.User_id, !user.Is_muted); //if (result != ERROR_CODE.ERR_OK) { // _messageService.Show($"Failed to mute {user.Username}. RTC engine returned {result} code"); //} } public async void InviteUserToSpeak(BindableChannelUser user) { if (ChannelInfo == null || user == null || !CurrentUserInfo?.Is_moderator != true) return; var apiResult = await _channelService.InviteSpeaker(new ChannelUserRequest() { Channel = ChannelInfo.Channel, User_id = user.User_id }); if (!apiResult.Success) { _messageService.Show($"{apiResult.Error_message}"); } } public async void MakeUserModerator(BindableChannelUser user) { if (ChannelInfo == null || user == null || !CurrentUserInfo?.Is_moderator != true) return; var apiResult = await _channelService.AddModerator(new ChannelUserRequest() { Channel = ChannelInfo.Channel, User_id = user.User_id }); if (!apiResult.Success) { _messageService.Show($"{apiResult.Error_message}"); } //GetDetail(); } public async void MoveToAudiance(BindableChannelUser user) { if (ChannelInfo == null || user == null || CurrentUserInfo?.Is_moderator != true) return; var apiResult = await _channelService.UninviteSpeaker(new ChannelUserRequest() { Channel = ChannelInfo.Channel, User_id = user.User_id }); if (!apiResult.Success) { _messageService.Show($"{apiResult.Error_message}"); } //GetDetail(); } public async Task<bool> LeaveRoom() { if (channelInfo == null) { return true; } var apiResult = await _channelService.Leave(channelInfo.Channel); if (apiResult == null || !apiResult.Success) { _messageService.Show($"Failed to leave channel. error message is {apiResult.Error_message}"); return false; } DisposeRoom(); Joined = false; OnLeave?.Invoke(channelInfo); return true; } private void DisposeRoom() { if (raisingHand) { _raiseHandCancelationTokenSource.Cancel(); } LeavePubnub(); _rtcEngine.LeaveChannel(); _cancelationTokenSource.Cancel(); ThreadManagerUtil.RunInUI(() => { ChannelInfo = null; JoinedUsers.Clear(); }); } private void LeavePubnub() { try { if (pubnub != null) { pubnub.UnsubscribeAll<string>(); } } catch (Exception ex) { Debug.WriteLine(ex.Message); } pubnub = null; } private async Task ActivePing() { while (!_cancelationTokenSource.Token.IsCancellationRequested) { var pingResult = await _channelService.ActivePing(ChannelInfo.Channel); //if (pingResult != null && pingResult.Should_leave) { // Console.WriteLine("[-] Should leave channel"); // await LeaveRoom(); // break; //} await Task.Delay(30000, _cancelationTokenSource.Token); } } public async void AcceptRaiseHand(BindableChannelUser user) { var apiResult = await _channelService.AcceptSpeakerInvite(new ChannelUserRequest { Channel = ChannelInfo.Channel, User_id = user.User_id }); if (apiResult?.Success != true) { _messageService.Show(apiResult?.Error_message ?? "Accept raise hand error"); } } public async void RejectRaiseHand(BindableChannelUser user) { var apiResult = await _channelService.RejectSpeakerInvite(new ChannelUserRequest { Channel = ChannelInfo.Channel, User_id = user.User_id }); if (apiResult?.Success != true) { _messageService.Show(apiResult?.Error_message ?? "Accept raise hand error"); } } private async Task CheckAcceptSpeakerInvition() { int tryCount = 0; while (tryCount < 10 && !_cancelationTokenSource.IsCancellationRequested && !_raiseHandCancelationTokenSource.Token.IsCancellationRequested) { var channelResult = await _channelService.Get(ChannelInfo.Channel); var acceptResult = await _channelService.AcceptSpeakerInvite(new ChannelUserRequest() { Channel = ChannelInfo.Channel, User_id = channelResult.Users.Select((Func<ChannelUser, long>)(u => (long)u.User_id)).FirstOrDefault(u => u != _accountService.CurrentConfig.UserId.Value) }); if (acceptResult?.Success == true) { Rejoin(); break; } await Task.Delay(10000, _raiseHandCancelationTokenSource.Token); tryCount++; } ThreadManagerUtil.RunInUI(() => { RaisingHand = false; }); } public async void Rejoin() { var channel = ChannelInfo; _rtcEngine.LeaveChannel(); JoinChannelResponse apiResult = await _channelService.Join(new JoinChannelRequest { Channel = channelInfo.Channel }); if (string.IsNullOrEmpty(apiResult?.Token) || !apiResult.Success) { _messageService.Show("Failed To join channel."); return; } var joinResult = _rtcEngine.JoinChannel(apiResult.Token, apiResult.Channel, "", (uint)_accountService.CurrentConfig.UserId.Value); if (joinResult != ERROR_CODE.ERR_OK) { _messageService.Show($"Failed to join RTCEngine. Error code is {joinResult}"); return; } RefereshUserView(apiResult.Users); ThreadManagerUtil.RunInUI(() => { ChannelInfo = apiResult; }); } public async void GetDetail() { if (ChannelInfo == null) return; GetChannelResponse apiResult = await _channelService.Get(ChannelInfo.Channel); if (apiResult?.Users == null) { return; } RefereshUserView(apiResult.Users); ThreadManagerUtil.RunInUI(() => { ChannelInfo = apiResult; }); } private void RefereshUserView(IEnumerable<ChannelUser> apiUsers) { for (int i = 0; i < apiUsers.Count(); i++) { var item = apiUsers.ElementAt(i); BindableChannelUser user = JoinedUsers.Count > i ? JoinedUsers.ElementAt(i) : null; if (user == null || user.User_id != item.User_id) { user = JoinedUsers.Find(item.User_id); } if (user != null) { if (user.Is_speaker != item.Is_speaker || (!item.Is_speaker && user.Is_followed_by_speaker != item.Is_followed_by_speaker)) ThreadManagerUtil.RunInUI(() => { JoinedUsers.Remove(user); JoinedUsers.Insert(i, new BindableChannelUser(item)); }); else if (!user.Equals(item)) ThreadManagerUtil.RunInUI(() => user.SetProperties(item)); } else { ThreadManagerUtil.RunInUI(() => JoinedUsers.Insert(i, new BindableChannelUser(item))); } } for (int i = 0; i < JoinedUsers.Count; i++) { var item = JoinedUsers[i]; if (!apiUsers.Any(u => u.User_id == item.User_id)) { ThreadManagerUtil.RunInUI(() => { JoinedUsers.Remove(item); }); i--; } } var userInfo = JoinedUsers.Find(_accountService.CurrentConfig.UserId ?? 0); ThreadManagerUtil.RunInUI(() => { CurrentUserInfo = userInfo; }); } private void PubNubMessageActions(Pubnub pnObj, PNMessageResult<object> pubMsg) { var message = pubMsg?.Message?.ToString(); if (string.IsNullOrEmpty(message)) { return; } var data = _serializer.Deserialize<PubnubResponse>(message); if (string.IsNullOrEmpty(data?.Channel) || data.Channel != ChannelInfo?.Channel) { return; } switch (data.Action) { case "join_channel": if (data.User_profile == null) { Debug.WriteLine($"Pubnub error: {message}"); } else { var user = JoinedUsers.Find(data.User_profile.User_id); if (user == null) { ThreadManagerUtil.RunInUI(() => { JoinedUsers.Add(new BindableChannelUser(data.User_profile)); }); } else { ThreadManagerUtil.RunInUI(() => { JoinedUsers.Remove(user); user.SetProperties(data.User_profile); JoinedUsers.Add(user); }); } } break; case "leave_channel": if (data.User_id <= 0) { Debug.WriteLine($"Pubnub error: {message}"); } else { var user = JoinedUsers.Find(data.User_id); if (user != null) { ThreadManagerUtil.RunInUI(() => { JoinedUsers.Remove(user); }); } else { Debug.WriteLine($"User Offline: User {data.User_id} not found"); } } break; case "add_speaker": if (data.User_profile == null) { Debug.WriteLine($"Pubnub error: {message}"); } else { var user = JoinedUsers.Find(data.User_profile.User_id); if (user != null) { ThreadManagerUtil.RunInUI(() => { JoinedUsers.Remove(user); user.SetProperties(data.User_profile); JoinedUsers.Add(user); }); } else { ThreadManagerUtil.RunInUI(() => { JoinedUsers.Add(new BindableChannelUser(data.User_profile)); }); } } break; case "make_moderator": if (data.User_id <= 0) { Debug.WriteLine($"Pubnub error: {message}"); } else { var user = JoinedUsers.Find(data.User_id); if (user != null) { ThreadManagerUtil.RunInUI(() => { user.Is_moderator = true; }); } else { Debug.WriteLine($"Pubnub user not found: {message}"); } } break; case "remove_speaker": if (data.User_id <= 0) { Debug.WriteLine($"Pubnub error: {message}"); } else { var user = JoinedUsers.Find(data.User_id); if (user != null) { ThreadManagerUtil.RunInUI(() => { JoinedUsers.Remove(user); user.Is_speaker = false; JoinedUsers.Add(user); }); } else { Debug.WriteLine($"Pubnub user not found: {message}"); } } break; case "update_speaker_call_status": if (data.User_id <= 0) { Debug.WriteLine($"Pubnub error: {message}"); } else { var user = JoinedUsers.Find(data.User_id); if (user != null) { ThreadManagerUtil.RunInUI(() => { JoinedUsers.Remove(user); user.Is_on_call = data.Is_on_call; JoinedUsers.Add(user); }); } else { Debug.WriteLine($"Pubnub user not found: {message}"); } } break; case "raise_hands": if (data.User_profile == null) { Debug.WriteLine($"Pubnub error: {message}"); } else { var user = JoinedUsers.Find(data.User_profile.User_id); if (user == null) { user = new BindableChannelUser(data.User_profile); ThreadManagerUtil.RunInUI(() => { JoinedUsers.Add(user); }); } ThreadManagerUtil.RunInUI(() => { user.Raise_hands = true; }); } break; case "unraise_hands": if (data.User_id <= 0) { Debug.WriteLine($"Pubnub error: {message}"); } else { var user = JoinedUsers.Find(data.User_id); if (user != null) { ThreadManagerUtil.RunInUI(() => { user.Raise_hands = false; }); } } break; case "invite_speaker": if (data.From_user_id <= 0) { Debug.WriteLine($"Pubnub error: {message}"); } else { ThreadManagerUtil.RunInUI(async () => { var view = _unityContainer.Resolve<JoinAsSpeakerView>(); if (view.DataContext is JoinAsSpeakerViewModel viewModel) { viewModel.FromName = data.From_name; viewModel.FromUserId = data.From_user_id; } var res = await DialogHost.Show(view); if (res == null) { await _channelService.RejectSpeakerInvite(new ChannelUserRequest { Channel = ChannelInfo.Channel, User_id = data.From_user_id }); } }); } break; case "uninvite_speaker": if (data.From_user_id <= 0) { Debug.WriteLine($"Pubnub error: {message}"); } else { _messageService.Show($"{data.From_name} moved you to audiance"); ThreadManagerUtil.RunInUI(() => { if (CurrentUserInfo != null) CurrentUserInfo.Is_speaker = false; }); } break; case "mute_speaker": _messageService.Show($"{data.From_name} muted you"); ThreadManagerUtil.RunInUI(() => { if (!this.MicrophoneMuted) ChangeMicrophoneMute(); }); break; case "end_channel": ThreadManagerUtil.RunInUI(async () => { await LeaveRoom(); }); break; case "remove_from_channel": default: Debug.WriteLine(message); break; } } } }
41.343797
182
0.500018
[ "MIT" ]
aliprogrammer69/ClubHouse-Windows
UI/ClubHouse.UI.DesktopApp/Handler/RoomManagerService.cs
27,661
C#
namespace Packer.Test { using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Poker; [TestClass] public class CardTest { [TestMethod] public void Card_CreatedCardShouldNotBeNullabe() { // Arrange Card card = new Card(CardFace.Ace, CardSuit.Spades); // Act and Assert Assert.IsNotNull(card); //// Asserts } [TestMethod] public void ToString_ShouldReturnStringValueWithValidCardPresention() { // Arrange Card card = new Card(CardFace.Ace, CardSuit.Spades); // Act string cardStringPresentation = card.ToString(); string cardAceSpades = "Ace♠"; // Assert Assert.AreEqual(cardAceSpades.GetType(), cardStringPresentation.GetType()); Assert.AreEqual(cardAceSpades, cardStringPresentation); } [TestMethod] public void ToString_ShouldAllaysReturnValidCard() { // Arrange Card card = new Card(CardFace.King, CardSuit.Diamonds); // Act // TODO how to do it // Assert // TODO how to do it } } }
24.326923
87
0.552569
[ "MIT" ]
shopOFF/Telerik-Academy-Courses
Unit-Testing/TelerikUnitTestingg/UnitTestingHomeworks/TDDHomework/HW_Test-Driven-Development (1)/PokerHomework/Poker.Test/CardTest.cs
1,269
C#
using System; using System.Linq; using System.Reactive.Linq; using RxDivideAggregate; namespace MainApplication { class Program { private const int FiresCount = 1; private const int ReportSize = 1; private static readonly FireId[] FireIds = Enumerable.Range(0, FiresCount) .Select(x => new FireId(x + 1)) .ToArray(); private static readonly TimeSpan EventRaisingInterval = TimeSpan.FromSeconds(1); static void Main(string[] args) { var rand = new Random(); var inputRawDataSource = Observable.Interval(EventRaisingInterval) .Select(x => { var fireStates = Enumerable.Range(0, ReportSize) .Select(i => rand.Next(1, FiresCount)) .Distinct() .Select(fireId => new FireId(fireId)) .ToDictionary(id => id, id => new FireState(DateTime.UtcNow, (State)rand.Next(1, 3))); return new FireStates(fireStates); }); inputRawDataSource = inputRawDataSource.Take(30).Publish().RefCount(); var validFireStream = inputRawDataSource .DivideAggregate( splitFunc: fireStates => fireStates.States.Select(fs => new { FireId = fs.Key, FireState = fs.Value }).ToArray(), groupSelector: simpleInput => simpleInput.FireId, predicateFunc: fireStream => fireStream.Buffer(2, 1).Where(arr => arr.Count == 2).Select(fs => fs.First().FireState.State == fs.Last().FireState.State), unionFunc: states => new FireStates(states.ToDictionary(x => x.FireId, x => x.FireState)) ); inputRawDataSource.Subscribe(Console.WriteLine); validFireStream.Subscribe(@event => Console.WriteLine("\t" + @event)); Console.ReadLine(); } } }
39.54902
147
0.553793
[ "MIT" ]
tvvister/RxDivideAggregate
MainApplication/Program.cs
2,019
C#
using SeeGui.Components; using System; using System.Collections.Generic; using System.Text; namespace SeeGui.Composer { public enum SgTheme { Modern, Classic } public static class SgComposer { public static void CreateButton(Button button) { // Draw the box of button Draw.Box(button.Left, button.Top, button.Left + button.Width, button.Top + button.Height); // Calculate the size available for inner text // -2 for two borders sum // -2 for spaces before and after text if (button?.Text.Length <= button.Width - 2) { var padText = $" {button?.Text} "; var startPosition = (button.Width / 2) - (padText.Length / 2) + 1; Draw.SetCursorAndWrite(startPosition + button.Left, button.Top + 1, button?.Text); return; } // -4 (sum of spaces and borders) Draw.SetCursorAndWrite(button.Left + 2, button.Top + 1, button?.Text.Substring(0, button.Width - 4)); } } }
28.461538
113
0.561261
[ "MIT" ]
radixi0/seegui
SeeGui/Composer/SgComposer.cs
1,112
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace TypeEdgeModule3 { public sealed class SingleThreadTaskScheduler : TaskScheduler { [ThreadStatic] private static bool _isExecuting; private readonly CancellationToken _cancellationToken; private readonly BlockingCollection<Task> _taskQueue; public SingleThreadTaskScheduler(CancellationToken cancellationToken) { _cancellationToken = cancellationToken; _taskQueue = new BlockingCollection<Task>(); } public void Start() { new Thread(RunOnCurrentThread) {Name = "STTS Thread"}.Start(); } // Just a helper for the sample code public Task Schedule(Action action) { return Task.Factory.StartNew ( action, CancellationToken.None, TaskCreationOptions.None, this ); } // You can have this public if you want - just make sure to hide it private void RunOnCurrentThread() { _isExecuting = true; try { foreach (var task in _taskQueue.GetConsumingEnumerable(_cancellationToken)) TryExecuteTask(task); } catch (OperationCanceledException) { } finally { _isExecuting = false; } } // Signaling this allows the task scheduler to finish after all tasks complete public void Complete() { _taskQueue.CompleteAdding(); } protected override IEnumerable<Task> GetScheduledTasks() { return null; } protected override void QueueTask(Task task) { try { _taskQueue.Add(task, _cancellationToken); } catch (OperationCanceledException) { } } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { // We'd need to remove the task from queue if it was already queued. // That would be too hard. if (taskWasPreviouslyQueued) return false; return _isExecuting && TryExecuteTask(task); } } }
28.011236
113
0.557962
[ "MIT" ]
ChristianEder/TypeEdge
Templates/TypeEdgeML/Modules/TypeEdgeModule3/SingleThreadTaskScheduler.cs
2,495
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using Autofac; using Autofac.Core; using Module = Autofac.Module; namespace YF.Utility.Logging { public class LoggingModule : Module { private readonly ConcurrentDictionary<string, ILogger> _loggerCache; public LoggingModule() { _loggerCache = new ConcurrentDictionary<string, ILogger>(); } protected override void Load(ContainerBuilder moduleBuilder) { moduleBuilder.RegisterType<CastleLoggerFactory>().As<ILoggerFactory>().InstancePerLifetimeScope(); moduleBuilder.RegisterType<IQCLog4netFactory>().As<Castle.Core.Logging.ILoggerFactory>().InstancePerLifetimeScope(); // call CreateLogger in response to the request for an ILogger implementation moduleBuilder.Register(CreateLogger).As<ILogger>().InstancePerDependency(); } protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { var implementationType = registration.Activator.LimitType; // build an array of actions on this type to assign loggers to member properties var injectors = BuildLoggerInjectors(implementationType).ToArray(); // if there are no logger properties, there's no reason to hook the activated event if (!injectors.Any()) return; // otherwise, whan an instance of this component is activated, inject the loggers on the instance registration.Activated += (s, e) => { foreach (var injector in injectors) injector(e.Context, e.Instance); }; } private IEnumerable<Action<IComponentContext, object>> BuildLoggerInjectors(Type componentType) { // Look for settable properties of type "ILogger" var loggerProperties = componentType .GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance) .Select(p => new { PropertyInfo = p, p.PropertyType, IndexParameters = p.GetIndexParameters(), Accessors = p.GetAccessors(false) }) .Where(x => x.PropertyType == typeof(ILogger)) // must be a logger .Where(x => x.IndexParameters.Count() == 0) // must not be an indexer .Where(x => x.Accessors.Length != 1 || x.Accessors[0].ReturnType == typeof(void)); //must have get/set, or only set // Return an array of actions that resolve a logger and assign the property foreach (var entry in loggerProperties) { var propertyInfo = entry.PropertyInfo; yield return (ctx, instance) => { string component = componentType.ToString(); if (component != instance.GetType().ToString()) { return; } var logger = _loggerCache.GetOrAdd(component, key => ctx.Resolve<ILogger>(new TypedParameter(typeof(Type), componentType))); propertyInfo.SetValue(instance, logger, null); }; } } private static ILogger CreateLogger(IComponentContext context, IEnumerable<Parameter> parameters) { // return an ILogger in response to Resolve<ILogger>(componentTypeParameter) var loggerFactory = context.Resolve<ILoggerFactory>(); var containingType = parameters.TypedAs<Type>(); return loggerFactory.CreateLogger(containingType); } } }
47.025
144
0.628655
[ "MIT" ]
kensen/YFLib
YF.Utility/Logging/LoggingModule.cs
3,764
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans; using Squidex.Domain.Apps.Entities.Schemas.Commands; using Squidex.Infrastructure; using Squidex.Infrastructure.Commands; using Squidex.Infrastructure.Log; using Squidex.Infrastructure.Validation; namespace Squidex.Domain.Apps.Entities.Schemas.Indexes { public sealed class SchemasIndex : ICommandMiddleware, ISchemasIndex { private readonly IGrainFactory grainFactory; public SchemasIndex(IGrainFactory grainFactory) { Guard.NotNull(grainFactory, nameof(grainFactory)); this.grainFactory = grainFactory; } public Task RebuildAsync(Guid appId, Dictionary<string, Guid> schemas) { return Index(appId).RebuildAsync(schemas); } public async Task<List<ISchemaEntity>> GetSchemasAsync(Guid appId, bool allowDeleted = false) { using (Profiler.TraceMethod<SchemasIndex>()) { var ids = await GetSchemaIdsAsync(appId); var schemas = await Task.WhenAll( ids.Select(id => GetSchemaAsync(appId, id, allowDeleted))); return schemas.Where(x => x != null).ToList(); } } public async Task<ISchemaEntity> GetSchemaAsync(Guid appId, string name, bool allowDeleted = false) { using (Profiler.TraceMethod<SchemasIndex>()) { var id = await GetSchemaIdAsync(appId, name); if (id == default) { return null; } return await GetSchemaAsync(appId, id, allowDeleted); } } public async Task<ISchemaEntity> GetSchemaAsync(Guid appId, Guid id, bool allowDeleted = false) { using (Profiler.TraceMethod<SchemasIndex>()) { var schema = await grainFactory.GetGrain<ISchemaGrain>(id).GetStateAsync(); if (IsFound(schema.Value, allowDeleted)) { return schema.Value; } return null; } } private async Task<Guid> GetSchemaIdAsync(Guid appId, string name) { using (Profiler.TraceMethod<SchemasIndex>()) { return await Index(appId).GetIdAsync(name); } } private async Task<List<Guid>> GetSchemaIdsAsync(Guid appId) { using (Profiler.TraceMethod<SchemasIndex>()) { return await Index(appId).GetIdsAsync(); } } public async Task HandleAsync(CommandContext context, Func<Task> next) { if (context.Command is CreateSchema createSchema) { var index = Index(createSchema.AppId.Id); string token = await CheckSchemaAsync(index, createSchema); try { await next(); } finally { if (token != null) { if (context.IsCompleted) { await index.AddAsync(token); } else { await index.RemoveReservationAsync(token); } } } } else { await next(); if (context.IsCompleted) { if (context.Command is DeleteSchema deleteSchema) { await DeleteSchemaAsync(deleteSchema); } } } } private async Task<string> CheckSchemaAsync(ISchemasByAppIndexGrain index, CreateSchema command) { var name = command.Name; if (name.IsSlug()) { var token = await index.ReserveAsync(command.SchemaId, name); if (token == null) { var error = new ValidationError("A schema with this name already exists."); throw new ValidationException("Cannot create schema.", error); } return token; } return null; } private async Task DeleteSchemaAsync(DeleteSchema commmand) { var schemaId = commmand.SchemaId; var schema = await grainFactory.GetGrain<ISchemaGrain>(schemaId).GetStateAsync(); if (IsFound(schema.Value, true)) { await Index(schema.Value.AppId.Id).RemoveAsync(schemaId); } } private ISchemasByAppIndexGrain Index(Guid appId) { return grainFactory.GetGrain<ISchemasByAppIndexGrain>(appId); } private static bool IsFound(ISchemaEntity entity, bool allowDeleted) { return entity.Version > EtagVersion.Empty && (!entity.IsDeleted || allowDeleted); } } }
30.923077
107
0.498045
[ "MIT" ]
alweish/squidex
src/Squidex.Domain.Apps.Entities/Schemas/Indexes/SchemasIndex.cs
5,630
C#
// <copyright filename="XmlRecordsetReader.cs" project="Framework"> // This file is licensed to you under the MIT License. // Full license in the project root. // </copyright> namespace B1PP.Data { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Xml; using System.Xml.XPath; using SAPbobsCOM; /// <summary> /// Allows you to read the data in the recordset. /// </summary> internal class XmlRecordsetReader : IRecordsetReader { private const string SapNamespace = "xmlns=\"http://www.sap.com/SBO/SDK/DI\""; private readonly XmlDocument xmlDoc; private List<Column> columns = new List<Column>(); private XmlNode currentRow; private IEnumerator rowEnumerator; public IEnumerable<IColumn> Columns { get { return columns; } } /// <summary> /// Initializes a new instance of the <see cref="XmlRecordsetReader" /> class. /// </summary> private XmlRecordsetReader() { xmlDoc = new XmlDocument(); rowEnumerator = xmlDoc.GetEnumerator(); } public DateTime? GetDateTime(string columnName) { string value = GetString(columnName); if (string.IsNullOrEmpty(value)) { return null; } return DateTime.ParseExact(value, GlobalConstants.BusinessOneDateTimeFormat, CultureInfo.InvariantCulture); } public DateTime GetDateTimeOrDefault(string columnName) { return GetDateTime(columnName) ?? default(DateTime); } public double? GetDouble(string columnName) { string value = GetString(columnName); if (string.IsNullOrEmpty(value)) { return null; } return double.Parse(value, CultureInfo.InvariantCulture); } public double GetDoubleOrDefault(string columnName) { return GetDouble(columnName) ?? default(double); } public int? GetInt(string columnName) { string value = GetString(columnName); if (string.IsNullOrEmpty(value)) { return null; } return int.Parse(value, CultureInfo.InvariantCulture); } public int GetIntOrDefault(string columnName) { return GetInt(columnName) ?? default(int); } public bool GetBoolOrDefault(string columnName) { return GetBool(columnName) ?? default(bool); } public bool? GetBool(string columnName) { string value = GetString(columnName); if (string.IsNullOrEmpty(value)) { return null; } return bool.Parse(value); } public string GetString(string columnName) { if (string.IsNullOrEmpty(columnName)) { throw new ArgumentException($"Parameter {nameof(columnName)} cannot be null or empty"); } var valueNode = GetItemXmlNode(columnName); if (valueNode != null) { return valueNode.InnerText; } throw new ArgumentException($"No column with name {columnName} was found."); } public string GetStringOrEmpty(string columnName) { return GetString(columnName) ?? string.Empty; } public bool MoveNext() { if (rowEnumerator == null) { return false; } bool retVal = rowEnumerator.MoveNext(); currentRow = (XmlNode) rowEnumerator.Current; return retVal; } public static XmlRecordsetReader CreateNew(IRecordset data) { if (data == null) { throw new ArgumentNullException(nameof(data)); } var reader = new XmlRecordsetReader(); reader.Load(data); return reader; } private string ExtractXmlFromRecordset(IRecordset data) { string fixedXml = data.GetFixedXML(RecordsetXMLModeEnum.rxmData); if (string.IsNullOrEmpty(fixedXml)) { return string.Empty; } return fixedXml.Replace(SapNamespace, string.Empty); } private XmlNode GetItemXmlNode(string columnName) { XmlNode valueNode; try { string xpath = $"Fields/Field/Value[../Alias = '{columnName}']"; valueNode = currentRow.SelectSingleNode(xpath); } catch (XPathException) { valueNode = null; } return valueNode; } private void Load(IRecordset data) { // get data string xmlData = ExtractXmlFromRecordset(data); if (string.IsNullOrEmpty(xmlData)) { return; } xmlDoc.LoadXml(xmlData); var rows = xmlDoc.SelectNodes(@"//Row"); if (rows == null || rows.Count == 0) { return; } rowEnumerator = rows.GetEnumerator(); var firstNode = rows[0]; var aliases = firstNode.SelectNodes(@"descendant::Alias"); if (aliases == null) { return; } var fields = data.Fields; foreach (XmlNode alias in aliases) { string name = alias.InnerXml; var type = fields.Item(name).Type; columns.Add(new Column(name, type)); } // TODO: why is this here? columns = columns.ToList(); } } }
26.60262
119
0.523309
[ "MIT" ]
laukiet78/SAPB1-C-SHARP
Framework/Data/XmlRecordsetReader.cs
6,092
C#
using Solnet.Programs; using Solnet.Rpc; using Solnet.Rpc.Builders; using Solnet.Rpc.Core.Http; using Solnet.Rpc.Messages; using Solnet.Rpc.Models; using Solnet.Rpc.Types; using Solnet.Wallet; using System; using System.Collections.Generic; using System.Threading; namespace Solnet.Examples { public class AssociatedTokenAccountsExample : IExample { private static readonly IRpcClient RpcClient = ClientFactory.GetClient(Cluster.TestNet); private const string MnemonicWords = "route clerk disease box emerge airport loud waste attitude film army tray " + "forward deal onion eight catalog surface unit card window walnut wealth medal"; public void Run() { Wallet.Wallet wallet = new Wallet.Wallet(MnemonicWords); /* * The following region creates and initializes a mint account, it also creates a token account * that is initialized with the same mint account and then mints tokens to this newly created token account. */ #region Create and Initialize a token Mint Account RequestResult<ResponseValue<BlockHash>> blockHash = RpcClient.GetRecentBlockHash(); ulong minBalanceForExemptionAcc = RpcClient.GetMinimumBalanceForRentExemption(TokenProgram.TokenAccountDataSize).Result; ulong minBalanceForExemptionMint = RpcClient.GetMinimumBalanceForRentExemption(TokenProgram.MintAccountDataSize).Result; Console.WriteLine($"MinBalanceForRentExemption Account >> {minBalanceForExemptionAcc}"); Console.WriteLine($"MinBalanceForRentExemption Mint Account >> {minBalanceForExemptionMint}"); Account ownerAccount = wallet.GetAccount(10); Account mintAccount = wallet.GetAccount(1004); Account initialAccount = wallet.GetAccount(1104); Console.WriteLine($"OwnerAccount: {ownerAccount}"); Console.WriteLine($"MintAccount: {mintAccount}"); Console.WriteLine($"InitialAccount: {initialAccount}"); byte[] createAndInitializeMintToTx = new TransactionBuilder(). SetRecentBlockHash(blockHash.Result.Value.Blockhash). SetFeePayer(ownerAccount). AddInstruction(SystemProgram.CreateAccount( ownerAccount, mintAccount, minBalanceForExemptionMint, TokenProgram.MintAccountDataSize, TokenProgram.ProgramIdKey)). AddInstruction(TokenProgram.InitializeMint( mintAccount.PublicKey, 2, ownerAccount.PublicKey, ownerAccount.PublicKey)). AddInstruction(SystemProgram.CreateAccount( ownerAccount, initialAccount, minBalanceForExemptionAcc, TokenProgram.TokenAccountDataSize, TokenProgram.ProgramIdKey)). AddInstruction(TokenProgram.InitializeAccount( initialAccount.PublicKey, mintAccount.PublicKey, ownerAccount.PublicKey)). AddInstruction(TokenProgram.MintTo( mintAccount.PublicKey, initialAccount.PublicKey, 1_000_000, ownerAccount)). AddInstruction(MemoProgram.NewMemo(initialAccount, "Hello from Sol.Net")). Build(new List<Account> { ownerAccount, mintAccount, initialAccount }); string createAndInitializeMintToTxSignature = Examples.SubmitTxSendAndLog(createAndInitializeMintToTx); Examples.PollConfirmedTx(createAndInitializeMintToTxSignature); #endregion /* * The following region creates an associated token account (ATA) for a random account and a certain token mint * (in this case it's the previously created token mintAccount) and transfers tokens from the previously created * token account to the newly created ATA. */ #region Create Associated Token Account // this public key is from a random account created via www.sollet.io // to test this locally I recommend creating a wallet on sollet and deriving this PublicKey associatedTokenAccountOwner = new("65EoWs57dkMEWbK4TJkPDM76rnbumq7r3fiZJnxggj2G"); PublicKey associatedTokenAccount = AssociatedTokenAccountProgram.DeriveAssociatedTokenAccount(associatedTokenAccountOwner, mintAccount); Console.WriteLine($"AssociatedTokenAccountOwner: {associatedTokenAccountOwner}"); Console.WriteLine($"AssociatedTokenAccount: {associatedTokenAccount}"); byte[] createAssociatedTokenAccountTx = new TransactionBuilder(). SetRecentBlockHash(blockHash.Result.Value.Blockhash). SetFeePayer(ownerAccount). AddInstruction(AssociatedTokenAccountProgram.CreateAssociatedTokenAccount( ownerAccount, associatedTokenAccountOwner, mintAccount)). AddInstruction(TokenProgram.Transfer( initialAccount, associatedTokenAccount, 25000, ownerAccount)).// the ownerAccount was set as the mint authority AddInstruction(MemoProgram.NewMemo(ownerAccount, "Hello from Sol.Net")). Build(new List<Account> { ownerAccount }); string createAssociatedTokenAccountTxSignature = Examples.SubmitTxSendAndLog(createAssociatedTokenAccountTx); Examples.PollConfirmedTx(createAssociatedTokenAccountTxSignature); #endregion } } }
47.574803
125
0.629924
[ "MIT" ]
BTCTrader/Solnet
src/Solnet.Examples/AssociatedTokenAccountsExample.cs
6,042
C#
using Newtonsoft.Json.Linq; using ReactNative.Bridge; using ReactNative.Modules.Core; using ReactNative.Modules.Network; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.Storage; namespace RNFS { class RNFSManager : ReactContextNativeModuleBase { private const int FileType = 0; private const int DirectoryType = 1; private static readonly IReadOnlyDictionary<string, Func<HashAlgorithm>> s_hashAlgorithms = new Dictionary<string, Func<HashAlgorithm>> { { "md5", () => MD5.Create() }, { "sha1", () => SHA1.Create() }, { "sha256", () => SHA256.Create() }, { "sha384", () => SHA384.Create() }, { "sha512", () => SHA512.Create() }, }; private readonly TaskCancellationManager<int> _tasks = new TaskCancellationManager<int>(); private readonly HttpClient _httpClient = new HttpClient(); private RCTNativeAppEventEmitter _emitter; public RNFSManager(ReactContext reactContext) : base(reactContext) { } public override string Name { get { return "RNFSManager"; } } internal RCTNativeAppEventEmitter Emitter { get { if (_emitter == null) { return Context.GetJavaScriptModule<RCTNativeAppEventEmitter>(); } return _emitter; } set { _emitter = value; } } public override IReadOnlyDictionary<string, object> Constants { get { var constants = new Dictionary<string, object> { { "RNFSMainBundlePath", Package.Current.InstalledLocation.Path }, { "RNFSCachesDirectoryPath", ApplicationData.Current.LocalCacheFolder.Path }, { "RNFSRoamingDirectoryPath", ApplicationData.Current.RoamingFolder.Path }, { "RNFSDocumentDirectoryPath", ApplicationData.Current.LocalFolder.Path }, { "RNFSTemporaryDirectoryPath", ApplicationData.Current.TemporaryFolder.Path }, { "RNFSFileTypeRegular", 0 }, { "RNFSFileTypeDirectory", 1 }, }; var external = GetFolderPathSafe(() => KnownFolders.RemovableDevices); if (external != null) { var externalItems = KnownFolders.RemovableDevices.GetItemsAsync().AsTask().Result; if (externalItems.Count > 0) { constants.Add("RNFSExternalDirectoryPath", externalItems[0].Path); } constants.Add("RNFSExternalDirectoryPaths", externalItems.Select(i => i.Path).ToArray()); } var pictures = GetFolderPathSafe(() => KnownFolders.PicturesLibrary); if (pictures != null) { constants.Add("RNFSPicturesDirectoryPath", pictures); } return constants; } } [ReactMethod] public async void writeFile(string filepath, string base64Content, IPromise promise) { try { // TODO: open file on background thread? using (var file = File.OpenWrite(filepath)) { var data = Convert.FromBase64String(base64Content); await file.WriteAsync(data, 0, data.Length).ConfigureAwait(false); } promise.Resolve(null); } catch (Exception ex) { Reject(promise, filepath, ex); } } [ReactMethod] public async void appendFile(string filepath, string base64Content, IPromise promise) { try { // TODO: open file on background thread? using (var file = File.Open(filepath, FileMode.Append)) { var data = Convert.FromBase64String(base64Content); await file.WriteAsync(data, 0, data.Length).ConfigureAwait(false); } promise.Resolve(null); } catch (Exception ex) { Reject(promise, filepath, ex); } } [ReactMethod] public async void write(string filepath, string base64Content, int position, IPromise promise) { try { // TODO: open file on background thread? using (var file = File.OpenWrite(filepath)) { if (position >= 0) { file.Position = position; } var data = Convert.FromBase64String(base64Content); await file.WriteAsync(data, 0, data.Length).ConfigureAwait(false); } promise.Resolve(null); } catch (Exception ex) { Reject(promise, filepath, ex); } } [ReactMethod] public void exists(string filepath, IPromise promise) { try { promise.Resolve(File.Exists(filepath) || Directory.Exists(filepath)); } catch (Exception ex) { Reject(promise, filepath, ex); } } [ReactMethod] public async void readFile(string filepath, IPromise promise) { try { if (!File.Exists(filepath)) { RejectFileNotFound(promise, filepath); return; } // TODO: open file on background thread? string base64Content; using (var file = File.OpenRead(filepath)) { var length = (int)file.Length; var buffer = new byte[length]; await file.ReadAsync(buffer, 0, length).ConfigureAwait(false); base64Content = Convert.ToBase64String(buffer); } promise.Resolve(base64Content); } catch (Exception ex) { Reject(promise, filepath, ex); } } [ReactMethod] public async void read(string filepath, int length, int position, IPromise promise) { try { if (!File.Exists(filepath)) { RejectFileNotFound(promise, filepath); return; } // TODO: open file on background thread? string base64Content; using (var file = File.OpenRead(filepath)) { file.Position = position; var buffer = new byte[length]; await file.ReadAsync(buffer, 0, length).ConfigureAwait(false); base64Content = Convert.ToBase64String(buffer); } promise.Resolve(base64Content); } catch (Exception ex) { Reject(promise, filepath, ex); } } [ReactMethod] public async void hash(string filepath, string algorithm, IPromise promise) { var hashAlgorithmFactory = default(Func<HashAlgorithm>); if (!s_hashAlgorithms.TryGetValue(algorithm, out hashAlgorithmFactory)) { promise.Reject(null, "Invalid hash algorithm."); return; } try { if (!File.Exists(filepath)) { RejectFileNotFound(promise, filepath); return; } await Task.Run(() => { var hexBuilder = new StringBuilder(); using (var hashAlgorithm = hashAlgorithmFactory()) { hashAlgorithm.Initialize(); var hash = default(byte[]); using (var file = File.OpenRead(filepath)) { hash = hashAlgorithm.ComputeHash(file); } foreach (var b in hash) { hexBuilder.Append(string.Format("{0:x2}", b)); } } promise.Resolve(hexBuilder.ToString()); }).ConfigureAwait(false); } catch (Exception ex) { Reject(promise, filepath, ex); } } [ReactMethod] public void moveFile(string filepath, string destPath, IPromise promise) { try { // TODO: move file on background thread? File.Move(filepath, destPath); promise.Resolve(true); } catch (Exception ex) { Reject(promise, filepath, ex); } } [ReactMethod] public async void copyFile(string filepath, string destPath, IPromise promise) { try { await Task.Run(() => File.Copy(filepath, destPath)).ConfigureAwait(false); promise.Resolve(null); } catch (Exception ex) { Reject(promise, filepath, ex); } } [ReactMethod] public async void readDir(string directory, IPromise promise) { try { await Task.Run(() => { var info = new DirectoryInfo(directory); if (!info.Exists) { promise.Reject(null, "Folder does not exist"); return; } var fileMaps = new JArray(); foreach (var item in info.EnumerateFileSystemInfos()) { var fileMap = new JObject { { "mtime", ConvertToUnixTimestamp(item.LastWriteTime) }, { "name", item.Name }, { "path", item.FullName }, }; var fileItem = item as FileInfo; if (fileItem != null) { fileMap.Add("type", FileType); fileMap.Add("size", fileItem.Length); } else { fileMap.Add("type", DirectoryType); fileMap.Add("size", 0); } fileMaps.Add(fileMap); } promise.Resolve(fileMaps); }); } catch (Exception ex) { Reject(promise, directory, ex); } } [ReactMethod] public void stat(string filepath, IPromise promise) { try { FileSystemInfo fileSystemInfo = new FileInfo(filepath); if (!fileSystemInfo.Exists) { fileSystemInfo = new DirectoryInfo(filepath); if (!fileSystemInfo.Exists) { promise.Reject(null, "File does not exist."); return; } } var fileInfo = fileSystemInfo as FileInfo; var statMap = new JObject { { "ctime", ConvertToUnixTimestamp(fileSystemInfo.CreationTime) }, { "mtime", ConvertToUnixTimestamp(fileSystemInfo.LastWriteTime) }, { "size", fileInfo?.Length ?? 0 }, { "type", fileInfo != null ? FileType: DirectoryType }, }; promise.Resolve(statMap); } catch (Exception ex) { Reject(promise, filepath, ex); } } [ReactMethod] public async void unlink(string filepath, IPromise promise) { try { var directoryInfo = new DirectoryInfo(filepath); var fileInfo = default(FileInfo); if (directoryInfo.Exists) { await Task.Run(() => Directory.Delete(filepath, true)).ConfigureAwait(false); } else if ((fileInfo = new FileInfo(filepath)).Exists) { await Task.Run(() => File.Delete(filepath)).ConfigureAwait(false); } else { promise.Reject(null, "File does not exist."); return; } promise.Resolve(null); } catch (Exception ex) { Reject(promise, filepath, ex); } } [ReactMethod] public async void mkdir(string filepath, JObject options, IPromise promise) { try { await Task.Run(() => Directory.CreateDirectory(filepath)).ConfigureAwait(false); promise.Resolve(null); } catch (Exception ex) { Reject(promise, filepath, ex); } } [ReactMethod] public async void downloadFile(JObject options, IPromise promise) { var filepath = options.Value<string>("toFile"); try { var url = new Uri(options.Value<string>("fromUrl")); var jobId = options.Value<int>("jobId"); var headers = (JObject)options["headers"]; var progressDivider = options.Value<int>("progressDivider"); var request = new HttpRequestMessage(HttpMethod.Get, url); foreach (var header in headers) { request.Headers.Add(header.Key, header.Value.Value<string>()); } await _tasks.AddAndInvokeAsync(jobId, token => ProcessRequestAsync(promise, request, filepath, jobId, progressDivider, token)); } catch (Exception ex) { Reject(promise, filepath, ex); } } [ReactMethod] public void stopDownload(int jobId) { _tasks.Cancel(jobId); } [ReactMethod] public async void getFSInfo(IPromise promise) { try { var properties = await ApplicationData.Current.LocalFolder.Properties.RetrievePropertiesAsync( new[] { "System.FreeSpace", "System.Capacity", }) .AsTask() .ConfigureAwait(false); promise.Resolve(new JObject { { "freeSpace", (ulong)properties["System.FreeSpace"] }, { "totalSpace", (ulong)properties["System.Capacity"] }, }); } catch (Exception ex) { promise.Reject(null, "getFSInfo is not available"); } } [ReactMethod] public async void touch(string filepath, double mtime, double ctime, IPromise promise) { try { await Task.Run(() => { var fileInfo = new FileInfo(filepath); if (!fileInfo.Exists) { using (File.Create(filepath)) { } } fileInfo.CreationTimeUtc = ConvertFromUnixTimestamp(ctime); fileInfo.LastWriteTimeUtc = ConvertFromUnixTimestamp(mtime); promise.Resolve(fileInfo.FullName); }); } catch (Exception ex) { Reject(promise, filepath, ex); } } public override void OnReactInstanceDispose() { _tasks.CancelAllTasks(); _httpClient.Dispose(); } private async Task ProcessRequestAsync(IPromise promise, HttpRequestMessage request, string filepath, int jobId, int progressIncrement, CancellationToken token) { try { using (var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token)) { var headersMap = new JObject(); foreach (var header in response.Headers) { headersMap.Add(header.Key, string.Join(",", header.Value)); } var contentLength = response.Content.Headers.ContentLength; SendEvent($"DownloadBegin-{jobId}", new JObject { { "jobId", jobId }, { "statusCode", (int)response.StatusCode }, { "contentLength", contentLength }, { "headers", headersMap }, }); // TODO: open file on background thread? var totalRead = 0; using (var fileStream = File.OpenWrite(filepath)) using (var stream = await response.Content.ReadAsStreamAsync()) { var contentLengthForProgress = contentLength ?? -1; var nextProgressIncrement = progressIncrement; var buffer = new byte[8 * 1024]; var read = 0; while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0) { token.ThrowIfCancellationRequested(); await fileStream.WriteAsync(buffer, 0, read); if (contentLengthForProgress >= 0) { totalRead += read; if (totalRead * 100 / contentLengthForProgress >= nextProgressIncrement || totalRead == contentLengthForProgress) { SendEvent("DownloadProgress-" + jobId, new JObject { { "jobId", jobId }, { "contentLength", contentLength }, { "bytesWritten", totalRead }, }); nextProgressIncrement += progressIncrement; } } } } promise.Resolve(new JObject { { "jobId", jobId }, { "statusCode", (int)response.StatusCode }, { "bytesWritten", totalRead }, }); } } finally { request.Dispose(); } } private void Reject(IPromise promise, String filepath, Exception ex) { if (ex is FileNotFoundException) { RejectFileNotFound(promise, filepath); return; } promise.Reject(null, ex.Message, ex); } private void RejectFileNotFound(IPromise promise, String filepath) { promise.Reject("ENOENT", "ENOENT: no such file or directory, open '" + filepath + "'"); } private void SendEvent(string eventName, JObject eventData) { Emitter.emit(eventName, eventData); } private static string GetFolderPathSafe(Func<StorageFolder> getFolder) { try { return getFolder().Path; } catch (UnauthorizedAccessException) { return null; } } public static double ConvertToUnixTimestamp(DateTime date) { var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var diff = date.ToUniversalTime() - origin; return Math.Floor(diff.TotalSeconds); } public static DateTime ConvertFromUnixTimestamp(double timestamp) { var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var diff = TimeSpan.FromSeconds(timestamp); var dateTimeUtc = origin + diff; return dateTimeUtc.ToLocalTime(); } } }
33.726006
168
0.452472
[ "MIT" ]
Akkroo/react-native-fs
windows/RNFS/RNFSManager.cs
21,787
C#
using System.Collections.Generic; using System.Text; using Essensoft.AspNetCore.Payment.Security; namespace Essensoft.AspNetCore.Payment.WeChatPay.Utility { public static class WeChatPaySignature { public static string SignWithKey(WeChatPayDictionary dictionary, string key, WeChatPaySignType signType) { var sb = new StringBuilder(); foreach (var iter in dictionary) { if (!string.IsNullOrEmpty(iter.Value) && iter.Key != "sign") { sb.Append(iter.Key).Append('=').Append(iter.Value).Append("&"); } } var signContent = sb.Append("key=").Append(key).ToString(); return signType switch { WeChatPaySignType.MD5 => MD5.Compute(signContent).ToUpperInvariant(), WeChatPaySignType.HMAC_SHA256 => HMACSHA256.Compute(signContent, key).ToUpperInvariant(), _ => throw new WeChatPayException("Unknown sign type!"), }; } public static string SignWithSecret(WeChatPayDictionary dictionary, string secret, List<string> include) { var sb = new StringBuilder(); foreach (var iter in dictionary) { if (!string.IsNullOrEmpty(iter.Value) && include.Contains(iter.Key)) { sb.Append(iter.Key).Append('=').Append(iter.Value).Append("&"); } } var signContent = sb.Append("secret=").Append(secret).ToString(); return MD5.Compute(signContent).ToUpperInvariant(); } } }
36.108696
112
0.571343
[ "MIT" ]
ekolios/payment
src/Essensoft.AspNetCore.Payment.WeChatPay/Utility/WeChatPaySignature.cs
1,663
C#
using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using NBitcoin; using Stratis.Bitcoin.Controllers; using Stratis.Bitcoin.Features.Miner.Interfaces; using Stratis.Bitcoin.Features.RPC; using Stratis.Bitcoin.Features.RPC.Exceptions; using Stratis.Bitcoin.Features.Wallet; using Stratis.Bitcoin.Features.Wallet.Interfaces; using Stratis.Bitcoin.Utilities; namespace Stratis.Bitcoin.Features.Miner.Controllers { /// <summary> /// RPC controller for calls related to PoW mining and PoS minting. /// </summary> [ApiVersion("1")] [Route("api/[controller]")] [Controller] public class MiningRpcController : FeatureController { /// <summary>Instance logger.</summary> private readonly ILogger logger; /// <summary>PoW miner.</summary> private readonly IPowMining powMining; /// <summary>Full node.</summary> private readonly IFullNode fullNode; /// <summary>Wallet manager.</summary> private readonly IWalletManager walletManager; /// <summary> /// Initializes a new instance of the object. /// </summary> /// <param name="powMining">PoW miner.</param> /// <param name="fullNode">Full node to offer mining RPC.</param> /// <param name="loggerFactory">Factory to be used to create logger for the node.</param> /// <param name="walletManager">The wallet manager.</param> public MiningRpcController(IPowMining powMining, IFullNode fullNode, ILoggerFactory loggerFactory, IWalletManager walletManager) : base(fullNode: fullNode) { Guard.NotNull(powMining, nameof(powMining)); Guard.NotNull(fullNode, nameof(fullNode)); Guard.NotNull(loggerFactory, nameof(loggerFactory)); Guard.NotNull(walletManager, nameof(walletManager)); this.fullNode = fullNode; this.logger = loggerFactory.CreateLogger(this.GetType().FullName); this.walletManager = walletManager; this.powMining = powMining; } /// <summary> /// Tries to mine one or more blocks. /// </summary> /// <param name="blockCount">Number of blocks to mine.</param> /// <returns>List of block header hashes of newly mined blocks.</returns> /// <remarks>It is possible that less than the required number of blocks will be mined because the generating function only /// tries all possible header nonces values.</remarks> [ActionName("generate")] [ActionDescription("Tries to mine a given number of blocks and returns a list of block header hashes.")] public List<uint256> Generate(int blockCount) { if (blockCount <= 0) { throw new RPCServerException(RPCErrorCode.RPC_INVALID_REQUEST, "The number of blocks to mine must be higher than zero."); } WalletAccountReference accountReference = this.GetAccount(); HdAddress address = this.walletManager.GetUnusedAddress(accountReference); List<uint256> res = this.powMining.GenerateBlocks(new ReserveScript(address.Pubkey), (ulong)blockCount, int.MaxValue); return res; } /// <summary> /// Finds first available wallet and its account. /// </summary> /// <returns>Reference to wallet account.</returns> private WalletAccountReference GetAccount() { string walletName = this.walletManager.GetWalletsNames().FirstOrDefault(); if (walletName == null) throw new RPCServerException(RPCErrorCode.RPC_INVALID_REQUEST, "No wallet found"); HdAccount account = this.walletManager.GetAccounts(walletName).FirstOrDefault(); if (account == null) throw new RPCServerException(RPCErrorCode.RPC_INVALID_REQUEST, "No account found on wallet"); var res = new WalletAccountReference(walletName, account.Name); return res; } } }
41.444444
163
0.657568
[ "MIT" ]
AYCHPay/AYCHPayGenesisFullnode
src/Stratis.Bitcoin.Features.Miner/Controllers/MiningRPCController.cs
4,105
C#
using Elmah.Io.Client; using System; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Umbraco.Core.Logging; using Umbraco.Web.HealthCheck; using Umbraco.Web.HealthCheck.NotificationMethods; namespace Elmah.Io.Umbraco { [HealthCheckNotificationMethod("elmah.io")] public class ElmahIoNotificationMethod : NotificationMethodBase { internal static string _assemblyVersion = typeof(ElmahIoNotificationMethod).Assembly.GetName().Version.ToString(); internal static string _umbracoAssemblyVersion = typeof(NotificationMethodBase).Assembly.GetName().Version.ToString(); private IHeartbeatsClient heartbeats; private readonly ILogger logger; public ElmahIoNotificationMethod(ILogger logger) { if (Settings == null) { Enabled = false; return; } var apiKey = Settings["apiKey"]?.Value; var logId = Settings["logId"]?.Value; var heartbeatId = Settings["heartbeatId"]?.Value; if (string.IsNullOrWhiteSpace(apiKey) || string.IsNullOrWhiteSpace(logId) || string.IsNullOrWhiteSpace(heartbeatId)) { Enabled = false; return; } ApiKey = apiKey; LogId = logId; HeartbeatId = heartbeatId; this.logger = logger; } public string ApiKey { get; private set; } public string LogId { get; set; } public string HeartbeatId { get; set; } public override async Task SendAsync(HealthCheckResults results, CancellationToken token) { if (ShouldSend(results) == false) { return; } if (string.IsNullOrWhiteSpace(ApiKey) || string.IsNullOrWhiteSpace(LogId) || string.IsNullOrWhiteSpace(HeartbeatId)) { return; } if (heartbeats == null) { var api = (ElmahioAPI)ElmahioAPI.Create(ApiKey, new ElmahIoOptions { Timeout = new TimeSpan(0, 0, 30), UserAgent = UserAgent(), }); heartbeats = api.Heartbeats; } string result = results.AllChecksSuccessful ? "Healthy" : "Unhealthy"; var reason = $"Results of the scheduled Umbraco Health Checks run on {DateTime.Now.ToShortDateString()} at {DateTime.Now.ToShortTimeString()} are as follows:\n\n{results.ResultsAsMarkDown(Verbosity)}"; try { await heartbeats.CreateAsync(HeartbeatId, LogId, new CreateHeartbeat { Result = result, Reason = reason, }); } catch (Exception e) { logger.Error(GetType(), e); throw; } } private string UserAgent() { return new StringBuilder() .Append(new ProductInfoHeaderValue(new ProductHeaderValue("Elmah.Io.Umbraco", _assemblyVersion)).ToString()) .Append(" ") .Append(new ProductInfoHeaderValue(new ProductHeaderValue("UmbracoCms.Web", _umbracoAssemblyVersion)).ToString()) .ToString(); } } }
33.382353
213
0.569163
[ "Apache-2.0" ]
elmahio/elmah.io.umbraco
src/elmah.io.umbraco/ElmahIoNotificationMethod.cs
3,407
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Runtime.InteropServices { [Flags] public enum TypeLibFuncFlags { FRestricted = 0x0001, FSource = 0x0002, FBindable = 0x0004, FRequestEdit = 0x0008, FDisplayBind = 0x0010, FDefaultBind = 0x0020, FHidden = 0x0040, FUsesGetLastError = 0x0080, FDefaultCollelem = 0x0100, FUiDefault = 0x0200, FNonBrowsable = 0x0400, FReplaceable = 0x0800, FImmediateBind = 0x1000, } }
26.625
71
0.630673
[ "MIT" ]
belav/runtime
src/libraries/System.Runtime.InteropServices/src/System/Runtime/InteropServices/TypeLibFuncFlags.cs
639
C#
namespace BaristaLabs.ChromeDevTools.Runtime.ServiceWorker { using Newtonsoft.Json; /// <summary> /// DeliverPushMessage /// </summary> public sealed class DeliverPushMessageCommand : ICommand { private const string ChromeRemoteInterface_CommandName = "ServiceWorker.deliverPushMessage"; [JsonIgnore] public string CommandName { get { return ChromeRemoteInterface_CommandName; } } /// <summary> /// Gets or sets the origin /// </summary> [JsonProperty("origin")] public string Origin { get; set; } /// <summary> /// Gets or sets the registrationId /// </summary> [JsonProperty("registrationId")] public string RegistrationId { get; set; } /// <summary> /// Gets or sets the data /// </summary> [JsonProperty("data")] public string Data { get; set; } } public sealed class DeliverPushMessageCommandResponse : ICommandResponse<DeliverPushMessageCommand> { } }
24.02
103
0.537885
[ "MIT" ]
BaristaLabs/chrome-dev-tools-runtime
BaristaLabs.ChromeDevTools.Runtime/ServiceWorker/DeliverPushMessageCommand.cs
1,201
C#
using System.Data.Entity; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; namespace GestionDeCV.Models { // Puede agregar datos del perfil del usuario agregando más propiedades a la clase ApplicationUser. Para más información, visite http://go.microsoft.com/fwlink/?LinkID=317594. public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Tenga en cuenta que el valor de authenticationType debe coincidir con el definido en CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Agregar aquí notificaciones personalizadas de usuario return userIdentity; } } public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnectionString", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } } }
38.515152
179
0.718332
[ "Apache-2.0" ]
franml32/GitHubTest
src/GestionDeCV/GestionDeCV/Models/IdentityModels.cs
1,277
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; namespace CefSharp.MinimalExample.WinForms { public partial class frmSettings : Form { public frmSettings() { InitializeComponent(); } private void ReadSettings() { txtUserXenzuu.Text = Properties.Settings.Default.UserXen; txtPassXenzuu.Text = Properties.Settings.Default.PassXen; txtKey.Text = Properties.Settings.Default.key; } private void SaveSettings() { Properties.Settings.Default.UserXen = this.txtUserXenzuu.Text; Properties.Settings.Default.PassXen = this.txtPassXenzuu.Text; Properties.Settings.Default.key = this.txtKey.Text; Properties.Settings.Default.Save(); } void dangnhap() { bool isOK = false; isOK = Class_Login.ProcessLogin(txtKey.Text, txtUserXenzuu.Text, txtPassXenzuu.Text); if (isOK) { SaveSettings(); this.Hide(); } else { MessageBox.Show("Sai key"); } } private void cmdSave_Click(object sender, EventArgs e) { dangnhap(); } private void frmSettings_Load(object sender, EventArgs e) { ReadSettings(); } private void cmdExit_Click(object sender, EventArgs e) { Environment.Exit(1); } private void frmSettings_FormClosed(object sender, FormClosedEventArgs e) { Environment.Exit(1); } } }
22.9625
97
0.569951
[ "MIT" ]
mrkienls/FBtoOther1
CefSharp.MinimalExample.WinForms/frmSettings.cs
1,839
C#
using System; namespace WorQLess.Attributes { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public class ExposeAttribute : Attribute { } }
23
110
0.78744
[ "MIT" ]
fabiohvp/WorQLess.Net
Attributes/ExposeAttribute.cs
207
C#
/******************************************************* * UndirectedGraph.cs * Created by Stephen Hall on 11/17/17. * Copyright (c) 2017 Stephen Hall. All rights reserved. * Undirected Graph implementation in C# ********************************************************/ using System; using System.Collections.Generic; namespace DataStructures.Graphs.UndirecetedGraph { /// <summary> /// Undirected Graph class /// </summary> public class UndirectedGraph { /// <summary> /// private members /// </summary> private int _edges; private readonly Dictionary<Int32, Dictionary<Int32, Double>> _map = new Dictionary<Int32, Dictionary<Int32, Double>>(); /// <summary> /// Gets the size of teh graph /// </summary> /// <returns>size of the graph</returns> public int Size() => _map.Count; /// <summary> /// gets the number of edges /// </summary> /// <returns>number of edges</returns> public int GetNumberOfEdges() => _edges; /// <summary> /// adds a node into the graph /// </summary> /// <param name="nodeId">id to add</param> /// <returns>success|fail</returns> public bool AddNode(int nodeId) { if (_map.ContainsKey(nodeId)) return false; _map.Add(nodeId, new Dictionary<Int32, Double>()); return true; } /// <summary> /// Adds an edge to the graph /// </summary> /// <param name="tailNodeId">tail node</param> /// <param name="headNodeId">head node</param> /// <returns>success|fail</returns> public bool AddEdge(int tailNodeId, int headNodeId) => AddEdge(tailNodeId, headNodeId, 1.0); /// <summary> /// test to see if the node exisits /// </summary> /// <param name="nodeId">id to find</param> /// <returns>true|false</returns> public bool HasNode(int nodeId) => _map.ContainsKey(nodeId); /// <summary> /// clears a node from the graph /// </summary> /// <param name="nodeId">id to clear</param> /// <returns> success|fail</returns> public bool ClearNode(int nodeId) { if (!HasNode(nodeId)) return false; Dictionary<Int32, Double> neighbors = _map[nodeId]; if (neighbors.Count == 0) return false; foreach (Int32 neighborId in neighbors.Keys) _map[neighborId].Remove(nodeId); _edges -= neighbors.Count; neighbors.Clear(); return true; } /// <summary> /// removes a node from the graph /// </summary> /// <param name="nodeId">id to remove</param> /// <returns>success|fail</returns> public bool RemoveNode(int nodeId) { if (HasNode(nodeId)) { ClearNode(nodeId); _map.Remove(nodeId); return true; } return false; } /// <summary> /// helper function to add an edge to the graph /// </summary> /// <param name="tailNodeId">tail node</param> /// <param name="headNodeId">head node</param> /// <param name="weight">weight of the edge</param> /// <returns>success|fail</returns> public bool AddEdge(int tailNodeId, int headNodeId, double weight) { if (tailNodeId != headNodeId) { AddNode(tailNodeId); AddNode(headNodeId); if (!_map[tailNodeId].ContainsKey(headNodeId)) { _map[tailNodeId].Add(headNodeId,weight); _map[headNodeId].Add(tailNodeId, weight); ++_edges; return true; } double oldWeight = _map[tailNodeId][headNodeId]; _map[tailNodeId][headNodeId] = weight; _map[headNodeId][tailNodeId] = weight; return oldWeight != weight; } // Undirected graph are not allowed to contain self-loops. return false; } /// <summary> /// tests to see if an edge exisit /// </summary> /// <param name="tailNodeId">tail node</param> /// <param name="headNodeId">head node</param> /// <returns>true|false</returns> public bool HasEdge(int tailNodeId, int headNodeId) => _map.ContainsKey(tailNodeId) && _map[tailNodeId].ContainsKey(headNodeId); /// <summary> /// gets the weight of an edge /// </summary> /// <param name="tailNodeId">tail node</param> /// <param name="headNodeId">head node</param> /// <returns>weight of the edge</returns> public double GetEdgeWeight(int tailNodeId, int headNodeId) => !HasEdge(tailNodeId, headNodeId) ? Double.NaN : _map[tailNodeId][headNodeId]; /// <summary> /// removes an edge from the graph /// </summary> /// <param name="tailNodeId">tail node</param> /// <param name="headNodeId">head node</param> /// <returns>success|fail</returns> public bool RemoveEdge(int tailNodeId, int headNodeId) { if (!(_map.ContainsKey(tailNodeId) || (!_map[tailNodeId].ContainsKey(headNodeId)))) return false; _map[tailNodeId].Remove(headNodeId); _map[headNodeId].Remove(tailNodeId); --_edges; return true; } /// <summary> /// gets the children of the given node /// </summary> /// <param name="nodeId">node to test</param> /// <returns>set of child nodes</returns> public HashSet<Int32> GetChildrenOf(int nodeId) => _map.ContainsKey(nodeId) ? new HashSet<Int32>(_map[nodeId].Keys) : new HashSet<Int32>(); /// <summary> /// gets the parents of a node /// </summary> /// <param name="nodeId">node to test</param> /// <returns>set of parents</returns> public HashSet<Int32> GetParentsOf(int nodeId) => _map.ContainsKey(nodeId) ? new HashSet<Int32>(_map[nodeId].Keys) : new HashSet<Int32>(); /// <summary> /// Returns all nodes of a graph /// </summary> /// <returns>set of the nodes in the graph</returns> public HashSet<Int32> GetAllNodes() => new HashSet<Int32>(_map.Keys); /// <summary> /// Clears the graph of all nodes and edges /// </summary> public void Clear() { _map.Clear(); _edges = 0; } } }
35.789744
149
0.514257
[ "MIT" ]
halls7588/Data_Structures
C#/Graphs/UndirecetedGraph/UndirectedGraph.cs
6,979
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.IO; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Logging; namespace live.asp.net.Services { public class DeploymentEnvironment : IDeploymentEnvironment { private readonly string _contentRoot; private readonly ILogger<DeploymentEnvironment> _logger; private string _commitSha; public DeploymentEnvironment(IHostingEnvironment hostingEnv, ILogger<DeploymentEnvironment> logger) { _contentRoot = hostingEnv.ContentRootPath; _logger = logger; } public string DeploymentId { get { if (_commitSha == null) { LoadCommitSha(); } return _commitSha; } } private void LoadCommitSha() { var kuduActiveDeploymentPath = Path.GetFullPath(Path.Combine(_contentRoot, "..", "deployments", "active")); try { if (File.Exists(kuduActiveDeploymentPath)) { _logger.LogDebug("Kudu active deployment file found, using it to set DeploymentID"); _commitSha = File.ReadAllText(kuduActiveDeploymentPath) + "(kudu)"; } else { _logger.LogDebug("Kudu active deployment file not found, using git to set DeploymentID"); var git = Process.Start(new ProcessStartInfo { FileName = "git", Arguments = "rev-parse HEAD", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true }); var gitOut = ""; while (!git.StandardOutput.EndOfStream) { gitOut += git.StandardOutput.ReadLine(); } gitOut += " (local)"; git.WaitForExit(); if (git.ExitCode != 0) { _logger.LogDebug("Problem using git to set deployment ID:\r\n git exit code: {0}\r\n git output: {1}", git.ExitCode, _commitSha); _commitSha = "(Could not determine deployment ID)"; } else { _commitSha = gitOut; } } } catch (Exception ex) { _logger.LogError(0, ex, "Error determining deployment ID"); _commitSha = "(Error determining deployment ID)"; } } } }
35.035294
154
0.495299
[ "MIT" ]
mohitkapoorind/ASP.NET
src/live.asp.net/Services/DeploymentEnvironment.cs
2,980
C#
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using DotSpatial.Data; using DotSpatial.Modeling.Forms; using DotSpatial.Modeling.Forms.Parameters; namespace DotSpatial.Tools { /// <summary> /// This tool calculates the euclidean distance from each raster cell to the nearest target cell. /// </summary> public class RasterDistance : Tool { #region Fields private Parameter[] _inputParam; private Parameter[] _outputParam; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="RasterDistance"/> class. /// </summary> public RasterDistance() { Name = TextStrings.RasterDistanceproximity; Category = TextStrings.RasterOverlay; Description = TextStrings.Calculateseuclideandistance; ToolTip = TextStrings.RasterDistanceproximity; } #endregion #region Properties /// <summary> /// Gets the input paramater array. /// </summary> public override Parameter[] InputParameters => _inputParam; /// <summary> /// Gets the output paramater array. /// </summary> public override Parameter[] OutputParameters => _outputParam; #endregion #region Methods /// <summary> /// Once the Parameter have been configured the Execute command can be called, it returns true if successful. /// </summary> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns>Boolean, true if the execute was successful.</returns> public override bool Execute(ICancelProgressHandler cancelProgressHandler) { IRaster inputRaster = _inputParam[0].Value as IRaster; IRaster outputRaster = _outputParam[0].Value as IRaster; double maximumDistance = (double)_inputParam[1].Value; return Execute(inputRaster, outputRaster, maximumDistance, cancelProgressHandler); } /// <summary> /// Executes the Raster distance calculation /// Ping Yang deleted static for external testing 10/2010. /// </summary> /// <param name="input">The input raster.</param> /// <param name="output">The output raster.</param> /// <param name="maxDistance">The maximum distance value. Cells with a larger distance to nearest /// target cell than maxDistance will be assigned 'no data' value.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns>true if execution was successful, false otherwise.</returns> public bool Execute(IRaster input, IRaster output, double maxDistance, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input == null || output == null) { return false; } // Creates the output raster with the same bounds as the input RasterBounds bounds = (RasterBounds)input.Bounds.Copy(); output = Raster.CreateRaster(output.Filename, string.Empty, bounds.NumColumns, bounds.NumRows, 1, typeof(int), new[] { string.Empty }); output.Bounds = bounds; // internally we reference output as an integer type raster. if (output is Raster<int> outRaster) { int numColumns = outRaster.NumColumns; int numRows = outRaster.NumRows; int lastUpdate = 0; // declare two jagged arrays for storing the (Rx, Ry) vectors. // rX is distance from current cell to nearest target cell measured in the x-direction // rY is distance from current cell to nearest target cell measured in the y-direction // the actual distance can be calculated as sqrt(rX^2 + rY^2). // in the resulting distance raster we store the squared distance as well as the rX, rY relative coordinates // to improve computation speed int[][] aRx = new int[numRows][]; int[][] aRy = new int[numRows][]; int[][] aSqDist = new int[numRows][]; const int InfD = int.MaxValue; const int TargetVal = 0; // initialize the arrays for (int i = 0; i < numRows; i++) { aRx[i] = new int[numColumns]; aRy[i] = new int[numColumns]; aSqDist[i] = new int[numColumns]; ReadInputRow(input, i, aSqDist[i], TargetVal, InfD); } // ******************************************************************* // raster distance calculation pass one - top to bottom, left to right // ******************************************************************* // int[] row1 = new int[numColumns]; // int[] row2 = new int[numColumns]; int[] aNcels = new int[4]; // the values of four neighbouring cells (W, NW, N, NE) int[] aDiff = new int[4]; // the | y coordinate distances to nearest target cell for (int row = 1; row < numRows; row++) { //// read the row from input raster // ReadInputRow(input, rowIndex, row2, targetVal, infD); for (int col = 1; col < numColumns - 1; col++) { int val = aSqDist[row][col]; // Continue processing only if the current cell is not a target if (val == TargetVal) { continue; } // read the values of the cell's neighbours aNcels[0] = aSqDist[row][col - 1]; // W aNcels[1] = aSqDist[row - 1][col - 1]; // NW aNcels[2] = aSqDist[row - 1][col]; // N aNcels[3] = aSqDist[row - 1][col + 1]; // NE // calculate the squared euclidean distances to each neighbouring cell and to the nearest target cell aDiff[0] = (aNcels[0] < InfD) ? aNcels[0] + (2 * aRx[row][col - 1]) + 1 : InfD; aDiff[1] = (aNcels[1] < InfD) ? aNcels[1] + (2 * (aRx[row - 1][col - 1] + aRy[row - 1][col - 1] + 1)) : InfD; aDiff[2] = (aNcels[2] < InfD) ? aNcels[2] + (2 * aRy[row - 1][col]) + 1 : InfD; aDiff[3] = (aNcels[3] < InfD) ? aNcels[3] + (2 * (aRx[row - 1][col + 1] + aRy[row - 1][col + 1] + 1)) : InfD; // find neighbouring cell with minimum distance difference int minDiff = aDiff[0]; int minDiffCell = 0; for (int i = 1; i < 4; i++) { if (aDiff[i] < minDiff) { minDiff = aDiff[i]; minDiffCell = i; } } // if a neighbouring cell with known distance was found: if (minDiff < InfD) { // assign the minimum euclidean distance aSqDist[row][col] = minDiff; // update the (rX, rY) cell-to-nearest-target vector switch (minDiffCell) { case 0: // W aRx[row][col] = aRx[row][col - 1] + 1; aRy[row][col] = aRy[row][col - 1]; break; case 1: // NW aRx[row][col] = aRx[row - 1][col - 1] + 1; aRy[row][col] = aRy[row - 1][col - 1] + 1; break; case 2: // N aRx[row][col] = aRx[row - 1][col]; aRy[row][col] = aRy[row - 1][col] + 1; break; case 3: // NE aRx[row][col] = aRx[row - 1][col + 1] + 1; aRy[row][col] = aRy[row - 1][col + 1] + 1; break; } } // end of update (rX, rY) cell-to-nearest-target vector } // end or current row processing - report progress int percent = (int)(row / (double)numRows * 100f); if (percent > lastUpdate) { lastUpdate += 1; cancelProgressHandler.Progress(lastUpdate, TextStrings.Pass1 + lastUpdate + TextStrings.progresscompleted); if (cancelProgressHandler.Cancel) { return false; } } } // ******************************************************************* // end of first pass for loop // ******************************************************************* // ******************************************************************* // raster distance calculation PASS TWO - bottom to top, right to left // ******************************************************************* lastUpdate = 0; for (int row = numRows - 2; row > 0; row--) { for (int col = numColumns - 2; col > 0; col--) { int val = aSqDist[row][col]; // Continue processing only if the current cell is not a target if (val == TargetVal) { continue; } // read the values of the cell's neighbours aNcels[0] = aSqDist[row][col + 1]; // E aNcels[1] = aSqDist[row + 1][col + 1]; // SE aNcels[2] = aSqDist[row + 1][col]; // S aNcels[3] = aSqDist[row + 1][col - 1]; // SW // calculate the squared euclidean distances to each neighbouring cell and to the nearest target cell aDiff[0] = (aNcels[0] < InfD) ? aNcels[0] + (2 * aRx[row][col + 1]) + 1 : InfD; aDiff[1] = (aNcels[1] < InfD) ? aNcels[1] + (2 * (aRx[row + 1][col + 1] + aRy[row + 1][col + 1] + 1)) : InfD; aDiff[2] = (aNcels[2] < InfD) ? aNcels[2] + (2 * aRy[row + 1][col]) + 1 : InfD; aDiff[3] = (aNcels[3] < InfD) ? aNcels[3] + (2 * (aRx[row + 1][col - 1] + aRy[row + 1][col - 1] + 1)) : InfD; // find neighbouring cell with minimum distance difference int minDiff = aDiff[0]; int minDiffCell = 0; for (int i = 1; i < 4; i++) { if (aDiff[i] < minDiff) { minDiff = aDiff[i]; minDiffCell = i; } } // if a neighbouring cell with known distance smaller than current known distance was found: if (minDiff < val) { // assign the minimum euclidean distance aSqDist[row][col] = minDiff; // update the (rX, rY) cell-to-nearest-target vector switch (minDiffCell) { case 0: // E aRx[row][col] = aRx[row][col + 1] + 1; aRy[row][col] = aRy[row][col + 1]; break; case 1: // SE aRx[row][col] = aRx[row + 1][col + 1] + 1; aRy[row][col] = aRy[row + 1][col + 1] + 1; break; case 2: // S aRx[row][col] = aRx[row + 1][col]; aRy[row][col] = aRy[row + 1][col] + 1; break; case 3: // SW aRx[row][col] = aRx[row + 1][col - 1] + 1; aRy[row][col] = aRy[row + 1][col - 1] + 1; break; } } // end of update (rX, rY) cell-to-nearest-target vector } // Write row to output raster WriteOutputRow(outRaster, row, aSqDist[row]); // Report progress int percent = (int)(row / (double)numRows * 100f); if (percent > lastUpdate) { lastUpdate += 1; cancelProgressHandler.Progress(lastUpdate, TextStrings.Pass2 + lastUpdate + TextStrings.progresscompleted); if (cancelProgressHandler.Cancel) { return false; } } } } // ******************************************************************* // end of second pass proximity calculation loop // ******************************************************************* // save output raster output.Save(); return true; } /// <summary> /// The Parameter array should be populated with default values here. /// </summary> public override void Initialize() { _inputParam = new Parameter[2]; _inputParam[0] = new RasterParam(TextStrings.inputRaster) { HelpText = TextStrings.InputRastercontainingtargetcells }; _inputParam[1] = new DoubleParam(TextStrings.Maximumdistance, 100.0) { HelpText = TextStrings.Maximumdistancetobecalculated }; _outputParam = new Parameter[2]; _outputParam[0] = new RasterParam(TextStrings.OutputRaster) { HelpText = TextStrings.SelectresultrasterfileName }; _outputParam[1] = new BooleanParam(TextStrings.OutputParameter_AddToMap, TextStrings.OutputParameter_AddToMap_CheckboxText, true); } /// <summary> /// Reads and converts the specified row from input raster to an array of integer /// It assigns noDataVal to 'noData' values and assigns dataVal to other values. /// </summary> /// <param name="input">Raster from which the row is read.</param> /// <param name="rowNumber">Number of the row that gets converted.</param> /// <param name="rowArray">The array where the row is saved. This array must be correctly dimensioned.</param> /// <param name="dataVal">New value which will be assigned to value cells.</param> /// <param name="noDataVal">New value which will be assigned to 'no data value' cells.</param> private static void ReadInputRow(IRaster input, int rowNumber, int[] rowArray, int dataVal, int noDataVal) { // IValueGrid vals = input.Value; double inputNoDataVal = input.NoDataValue; int numColumns = input.NumColumns; for (int column = 0; column < numColumns; column++) { if (input.Value[rowNumber, column] == inputNoDataVal) { rowArray[column] = noDataVal; } else { rowArray[column] = dataVal; } } } /// <summary> /// Writes the integer row array to the output raster. The square distance is /// converted to a normal distance. Unknown distance is converted to 'no data' value. /// </summary> /// <param name="output">The raster the row array is written to.</param> /// <param name="rowNumber">Number of the row.</param> /// <param name="rowArray">The array that contains the row. This array must be correctly dimensioned.</param> private static void WriteOutputRow(Raster<int> output, int rowNumber, int[] rowArray) { int noDataVal = (int)output.NoDataValue; for (int col = 0; col < rowArray.Length; col++) { int val = rowArray[col]; if (val == int.MaxValue) { output.Data[rowNumber][col] = noDataVal; } else { output.Data[rowNumber][col] = (int)Math.Sqrt(val); } } } #endregion } }
46.559796
148
0.432561
[ "MIT" ]
eapbokma/DotSpatial
Source/DotSpatial.Tools/RasterDistance.cs
18,300
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.GitHub.index/getRelease { public static class GetRelease { /// <summary> /// Use this data source to retrieve information about a GitHub release in a specific repository. /// /// {{% examples %}} /// {{% /examples %}} /// </summary> public static Task<GetReleaseResult> InvokeAsync(GetReleaseArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetReleaseResult>("github:index/getrelease/getRelease:getRelease", args ?? new GetReleaseArgs(), options.WithVersion()); } public sealed class GetReleaseArgs : Pulumi.InvokeArgs { /// <summary> /// Owner of the repository. /// </summary> [Input("owner", required: true)] public string Owner { get; set; } = null!; /// <summary> /// ID of the release to retrieve. Must be specified when `retrieve_by` = `id`. /// </summary> [Input("releaseId")] public int? ReleaseId { get; set; } /// <summary> /// Tag of the release to retrieve. Must be specified when `retrieve_by` = `tag`. /// </summary> [Input("releaseTag")] public string? ReleaseTag { get; set; } /// <summary> /// Name of the repository to retrieve the release from. /// </summary> [Input("repository", required: true)] public string Repository { get; set; } = null!; /// <summary> /// Describes how to fetch the release. Valid values are `id`, `tag`, `latest`. /// </summary> [Input("retrieveBy", required: true)] public string RetrieveBy { get; set; } = null!; public GetReleaseArgs() { } } [OutputType] public sealed class GetReleaseResult { /// <summary> /// URL of any associated assets with the release /// </summary> public readonly string AssertsUrl; /// <summary> /// Contents of the description (body) of a release /// </summary> public readonly string Body; /// <summary> /// Date of release creation /// </summary> public readonly string CreatedAt; /// <summary> /// (`Boolean`) indicates whether the release is a draft /// </summary> public readonly bool Draft; /// <summary> /// URL directing to detailed information on the release /// </summary> public readonly string HtmlUrl; /// <summary> /// id is the provider-assigned unique ID for this managed resource. /// </summary> public readonly string Id; /// <summary> /// Name of release /// </summary> public readonly string Name; public readonly string Owner; /// <summary> /// (`Boolean`) indicates whether the release is a prerelease /// </summary> public readonly bool Prerelease; /// <summary> /// Date of release publishing /// </summary> public readonly string PublishedAt; /// <summary> /// ID of release /// </summary> public readonly int? ReleaseId; /// <summary> /// Tag of release /// </summary> public readonly string? ReleaseTag; public readonly string Repository; public readonly string RetrieveBy; /// <summary> /// Download URL of a specific release in `tar.gz` format /// </summary> public readonly string TarballUrl; /// <summary> /// Commitish value that determines where the Git release is created from /// </summary> public readonly string TargetCommitish; /// <summary> /// URL that can be used to upload Assets to the release /// </summary> public readonly string UploadUrl; /// <summary> /// Base URL of the release /// </summary> public readonly string Url; /// <summary> /// Download URL of a specific release in `zip` format /// </summary> public readonly string ZipballUrl; [OutputConstructor] private GetReleaseResult( string assertsUrl, string body, string createdAt, bool draft, string htmlUrl, string id, string name, string owner, bool prerelease, string publishedAt, int? releaseId, string? releaseTag, string repository, string retrieveBy, string tarballUrl, string targetCommitish, string uploadUrl, string url, string zipballUrl) { AssertsUrl = assertsUrl; Body = body; CreatedAt = createdAt; Draft = draft; HtmlUrl = htmlUrl; Id = id; Name = name; Owner = owner; Prerelease = prerelease; PublishedAt = publishedAt; ReleaseId = releaseId; ReleaseTag = releaseTag; Repository = repository; RetrieveBy = retrieveBy; TarballUrl = tarballUrl; TargetCommitish = targetCommitish; UploadUrl = uploadUrl; Url = url; ZipballUrl = zipballUrl; } } }
29.55102
174
0.549378
[ "ECL-2.0", "Apache-2.0" ]
timmyers/pulumi-github
sdk/dotnet/index/getRelease/GetRelease.cs
5,792
C#
using System; namespace Pioneer.Common.Logging; /// <summary> /// The logger is a tool to log messages to the console and the log file system of Pioneer. /// </summary> public interface ILogger { /// <summary> /// Prints an info message to the logging system. /// </summary> /// <param name="message">The message to be printed</param> /// <param name="args">Arguments which will be placed into the message by {PLACEHOLDERS}</param> void Info(string message, params object[] args); /// <summary> /// Prints a warning message to the logging system. /// </summary> /// <param name="message">The message to be printed</param> /// <param name="args">Arguments which will be placed into the message by {PLACEHOLDERS}</param> void Warn(string message, params object[] args); /// <summary> /// Prints a verbose message to the logging system. /// </summary> /// <param name="message">The message to be printed</param> /// <param name="args">Arguments which will be placed into the message by {PLACEHOLDERS}</param> void Verbose(string message, params object[] args); /// <summary> /// Prints a debug message to the logging system. /// This message is only getting printed, when Pioneer is in Debug mode. /// </summary> /// <param name="message">The message to be printed</param> /// <param name="args">Arguments which will be placed into the message by {PLACEHOLDERS}</param> void Debug(string message, params object[] args); /// <summary> /// Prints a fatal message to the logging system. /// </summary> /// <param name="message">The message to be printed</param> /// <param name="args">Arguments which will be placed into the message by {PLACEHOLDERS}</param> void Fatal(string message, params object[] args); /// <summary> /// Prints an error message to the logging system. /// </summary> /// <param name="exception">The exception which occurred</param> /// <param name="message">The message to be printed</param> /// <param name="args">Arguments which will be placed into the message by {PLACEHOLDERS}</param> void Error(Exception exception, string message, params object[] args); /// <summary> /// Manually setting the debug mode enabled or disabled. /// </summary> /// <param name="enabled">True if the debug mode should be enabled</param> void SetDebug(bool enabled); }
41.491525
100
0.663399
[ "MIT" ]
PioneerMod/Pioneer
Pioneer.Common/Logging/ILogger.cs
2,450
C#
using System; using System.Linq; using EntityFramework.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Tracker.SqlServer.Entities; #if NET4 namespace Tracker.SqlServer.EF6.NET4.Tests #elif NET45 namespace Tracker.SqlServer.EF6.NET45.Tests #elif NET451 namespace Tracker.SqlServer.EF6.NET451.Tests #endif { [TestClass] public class BatchObjectContext { /// <summary> /// /// </summary> [TestMethod] public void Delete() { var db = new TrackerEntities(); string emailDomain = "@test.com"; int count = db.Users.Delete(u => u.Email.EndsWith(emailDomain)); } /// <summary> /// /// </summary> [TestMethod] public void DeleteWithExpressionContainingNullParameter() { // This test verifies that the delete is processed correctly when the where expression uses a parameter with a null parameter var db = new TrackerEntities(); string emailDomain = "@test.com"; string optionalComparisonString = null; int count = db.Users.Delete(u => u.Email.EndsWith(emailDomain) && (string.IsNullOrEmpty(optionalComparisonString) || u.AvatarType == optionalComparisonString)); } /// <summary> /// /// </summary> [TestMethod] public void DeleteWhereWithExpressionContainingNullParameter() { // This test verifies that the delete is processed correctly when the where expression uses a parameter with a null parameter var db = new TrackerEntities(); string emailDomain = "@test.com"; string optionalComparisonString = null; int count = db.Users .Where(u => (string.IsNullOrEmpty(optionalComparisonString) || u.AvatarType == optionalComparisonString) && u.Email.EndsWith(emailDomain)) .Delete(); } /// <summary> /// /// </summary> [TestMethod] public void Update() { var db = new TrackerEntities(); string emailDomain = "@test.com"; int count = db.Users.Update( u => u.Email.EndsWith(emailDomain), u => new User { IsApproved = false, LastActivityDate = DateTime.Now }); } /// <summary> /// /// </summary> [TestMethod] public void UpdateWithExpressionContainingNullParameter() { // This test verifies that the update is interpreted correctly when the where expression uses a parameter with a null parameter var db = new TrackerEntities(); string emailDomain = "@test.com"; string optionalComparisonString = null; int count = db.Users.Update( u => u.Email.EndsWith(emailDomain) && (string.IsNullOrEmpty(optionalComparisonString) || u.AvatarType == optionalComparisonString), u => new User { IsApproved = false, LastActivityDate = DateTime.Now }); } } }
33.419355
172
0.59556
[ "BSD-3-Clause" ]
advancedrei/EntityFramework.Extended
Source/Samples/EF6/Tracker.SqlServer.NET451.Tests/BatchObjectContext.cs
3,110
C#
#region Russian /* Повторное генерирование исключений Исключение, перехваченное в одном блоке catch, может быть повторно сгенерировано в другом блоке, чтобы быть перехваченным во внешнем блоке catch. Наиболее вероятной причиной для повторного генерирования исключения служит предоставление доступа к исключению нескольким обработчикам. Допустим, что один обработчик оперирует каким-нибудь одним аспектом исключения, а другой обработчик — другим его аспектом. Для повторного генерирования исключения достаточно указать оператор throw без сопутствующего выражения, как в приведенной ниже форме. throw ; Не следует, однако, забывать, что когда исключение генерируется повторно, то оно не перехватывается снова тем же самым блоком catch, а передается во внешний блок catch. В приведенном ниже примере программы демонстрируется повторное генерирование исключения. В данном случае генерируется исключение IndexOutOfRangeException. */ // Сгенерировать исключение повторно. using System; class Rethrow { public static void GenException() { // Здесь массив numer длиннее массива denom. int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 }; int[] denom = { 2, 0, 4, 4, 0, 8 }; for (int i = 0; i < numer.Length; i++) { try { Console.WriteLine(numer[i] + " / " + denom[i] + " равно " + numer[i] / denom[i]); } catch (DivideByZeroException) { Console.WriteLine("Делить на ноль нельзя!"); } catch (IndexOutOfRangeException) { Console.WriteLine("Подходящий элемент не найден."); throw; // сгенерировать исключение повторно } } } } class RethrowDemo { static void Main() { try { Rethrow.GenException(); } catch (IndexOutOfRangeException) { // перехватить исключение повторно Console.WriteLine("Неисправимая ошибка - программа прервана."); } Console.ReadKey(); } } /* В этом примере программы ошибки из-за деления на нуль обрабатываются локально в методе GenException(), но ошибка выхода за границы массива генерируется повторно. В данном случае исключение IndexOutOfRangeException обрабатывается в методе Main(). */ #endregion #region English /* Rethrowing an Exception An exception caught by one catch can be rethrown so that it can be caught by an outer catch. The most likely reason for rethrowing an exception is to allow multiple handlers access to the exception. For example, perhaps one exception handler manages one aspect of an exception, and a second handler copes with another aspect. To rethrow an exception, you simply specify throw, without specifying an expression. That is, you use this form of throw: throw ; Remember, when you rethrow an exception, it will not be recaught by the same catch clause. Instead, it will propagate to an outer catch. The following program illustrates rethrowing an exception. In this case, it rethrows an IndexOutOfRangeException. */ // Rethrow an exception. //using System; //class Rethrow //{ // public static void GenException() // { // // Here, numer is longer than denom. // int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 }; // int[] denom = { 2, 0, 4, 4, 0, 8 }; // for (int i = 0; i < numer.Length; i++) // { // try // { // Console.WriteLine(numer[i] + " / " + // denom[i] + " is " + // numer[i] / denom[i]); // } // catch (DivideByZeroException) // { // Console.WriteLine("Can't divide by Zero!"); // } // catch (IndexOutOfRangeException) // { // Console.WriteLine("No matching element found."); // throw; // rethrow the exception // } // } // } //} //class RethrowDemo //{ // static void Main() // { // try // { // Rethrow.GenException(); // } // catch (IndexOutOfRangeException) // { // // recatch exception // Console.WriteLine("Fatal error -- " + "program terminated."); // } // Console.ReadKey(); // } //} /* In this program, divide-by-zero errors are handled locally, by GenException( ), but an array boundary error is rethrown. In this case, the IndexOutOfRangeException is handled by Main( ). */ #endregion
27.502994
97
0.617026
[ "Unlicense" ]
Vladimir-Zakharenkov/csharp-4-schildt
Chapter-13/Part-10/Program.cs
5,683
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Net; namespace stNet { public static class stACL { private const uint localHost = 2130706433; public enum IpFilterType : int { None = 0, GeoASN, GeoCountry, IPRange, BlackList, WhiteList }; #region private method private static void _IpFilterAddIpRange(this List<stIpRange> IpListRange, string aip) { string [] ipRange = new string[2] { "", "" }; if (string.IsNullOrWhiteSpace(aip)) { throw new ArgumentNullException(Properties.Resources.aclExceptionAddress); } if (aip.Contains("-")) { ipRange = aip.Split('-'); } else if (aip.Contains("/")) { uint mask, startIp, endIp; ipRange = aip.Split('/'); if (ipRange.Length >= 2) { if (ipRange[1].Length > 2) { mask = ipRange[1].IpStringToUInt(); startIp = (ipRange[0].IpStringToUInt() & mask); endIp = (startIp | (mask ^ 0xffffffff)); } else { int cidr = Convert.ToInt32(ipRange[1]); mask = ~(0xFFFFFFFF >> cidr); startIp = (ipRange[0].IpStringToUInt() & mask); endIp = (startIp | (mask ^ 0xffffffff)); } if (endIp <= 0) { throw new ArgumentOutOfRangeException(Properties.Resources.aclExceptioConvertIpEnd); } ipRange[0] = startIp.IpUIntToString(); ipRange[1] = endIp.IpUIntToString(); #if DEBUGIPRANGE Console.Write("start ip: " + startIp.IpUIntToString() + "\r\n"); Console.Write("end ip: " + endIp.IpUIntToString() + "\r\n"); Console.Write("mask: " + mask.IpUIntToString() + "\r\n"); #endif } } else { ipRange[0] = aip; ipRange[1] = aip; } if (ipRange.Length < 2) { throw new ArgumentOutOfRangeException(Properties.Resources.aclExceptioSourceFormat); } stACL._IpFilterAddIpRange(IpListRange, ipRange[0], ipRange[1]); } private static void _IpFilterAddIpRange(this List<stIpRange> IpListRange, string bip, string eip) { try { if (IpListRange == null) { throw new ArgumentNullException(Properties.Resources.aclExceptionList); } if ((string.IsNullOrWhiteSpace(bip)) || (string.IsNullOrWhiteSpace(eip))) { throw new ArgumentNullException(Properties.Resources.aclExceptionAddress); } IpListRange.Add( new stIpRange() { ipStart = bip.IpStringToUInt(), ipEnd = eip.IpStringToUInt() } ); } catch (Exception e) { throw new Exception(e.Message + " " + e.Source); } } private static stIPFilter _IpFilterCreate( StringCollection strIPList, StringCollection strASNList, StringCollection strCountryList, bool isIpBlackList, bool isGeoAsnBlackList, bool isGeoCountryBlackList, Func<uint, List<int>, int, bool, bool> GeoAction, Func<string, int> GeoCountryFunc ) { stIPFilter IpFilter = new stIPFilter(); try { if ((strIPList != null) && (strIPList.Count > 0)) { foreach (string rip in strIPList) { if (string.IsNullOrWhiteSpace(rip)) { continue; } stACL._IpFilterAddIpRange(IpFilter.IpRange, rip); } IpFilter.IpFilterType = ((isIpBlackList) ? stACL.IpFilterType.BlackList : stACL.IpFilterType.WhiteList); } if ((strASNList != null) && (strASNList.Count > 0)) { foreach (string num in strASNList) { string asn; if (num.StartsWith("ASN")) { asn = num.Substring(3, (num.Length - 3)); } else if (num.StartsWith("AS")) { asn = num.Substring(2, (num.Length - 2)); } else { asn = num; } int n = 0; if (Int32.TryParse(asn.Trim(), out n)) { IpFilter.GeoDataASN.Add(n); } } IpFilter.GeoAsnFilterType = ((isGeoAsnBlackList) ? stACL.IpFilterType.BlackList : stACL.IpFilterType.WhiteList); } if ((strCountryList != null) && (strCountryList.Count > 0)) { foreach (string num in strCountryList) { int n = 0; string country = num.Trim(); if (Int32.TryParse(country, out n)) { IpFilter.GeoDataCounry.Add(n); } else { if ((GeoCountryFunc != null) && (country.Length == 2)) { if ((n = GeoCountryFunc(country)) != -1) { IpFilter.GeoDataCounry.Add(n); } } } } IpFilter.GeoCountryFilterType = ((isGeoCountryBlackList) ? stACL.IpFilterType.BlackList : stACL.IpFilterType.WhiteList); } if (GeoAction != null) { IpFilter.GeoAction = GeoAction; } } catch (Exception e) { throw new ArgumentException(e.Message); } return IpFilter; } #endregion #region IpFilterCreate public static stIPFilter IpFilterCreate( StringCollection strCollection, bool isBlackList = true ) { return stACL.IpFilterCreate( strCollection, IpFilterType.IPRange, isBlackList, null ); } /// <summary> /// Create IpFilter /// </summary> /// <param name="srcList">Source IpRange/ASN/Country based StringCollection</param> /// <param name="listType"></param> /// <param name="isBlackList"></param> /// <param name="act"></param> /// <returns></returns> public static stIPFilter IpFilterCreate( StringCollection strCollection, stACL.IpFilterType listType, bool isBlackList = true, Func<uint, List<int>, int, bool, bool> act = null, Func<string, int> func = null ) { return stACL._IpFilterCreate( ((listType == IpFilterType.IPRange) ? strCollection : null), ((listType == IpFilterType.GeoASN) ? strCollection : null), ((listType == IpFilterType.GeoCountry) ? strCollection : null), ((listType == IpFilterType.IPRange) ? isBlackList : true), ((listType == IpFilterType.GeoASN) ? isBlackList : true), ((listType == IpFilterType.GeoCountry) ? isBlackList : true), act, func ); } /// <summary> /// Create IpFilter /// </summary> /// <param name="geoCollection">IP based List string</param> /// <param name="IpBlackList"></param> /// <returns></returns> public static stIPFilter IpFilterCreate( List<string> ipList, bool IpBlackList = true ) { return stACL.IpFilterCreate( ipList, IpFilterType.IPRange, IpBlackList, null, null ); } /// <summary> /// Create IpFilter /// </summary> /// <param name="srcList">Source IpRange/ASN/Country based List string</param> /// <param name="listType"></param> /// <param name="isBlackList"></param> /// <param name="act"></param> /// <returns></returns> public static stIPFilter IpFilterCreate( List<string> srcList, stACL.IpFilterType listType, bool isBlackList = true, Func<uint, List<int>, int, bool, bool> act = null, Func<string, int> func = null ) { StringCollection geoCollection = null; if ((srcList != null) && (srcList.Count > 0)) { geoCollection = new StringCollection(); geoCollection.AddRange(srcList.ToArray()); } return stACL._IpFilterCreate( ((listType == IpFilterType.IPRange) ? geoCollection : null), ((listType == IpFilterType.GeoASN) ? geoCollection : null), ((listType == IpFilterType.GeoCountry) ? geoCollection : null), ((listType == IpFilterType.IPRange) ? isBlackList : true), ((listType == IpFilterType.GeoASN) ? isBlackList : true), ((listType == IpFilterType.GeoCountry) ? isBlackList : true), act, func ); } /// <summary> /// Create IpFilter /// </summary> /// <param name="srcList">Source ASN/Country based List int</param> /// <param name="listType"></param> /// <param name="isBlackList"></param> /// <param name="act"></param> /// <returns></returns> public static stIPFilter IpFilterCreate( List<int> srcList, stACL.IpFilterType listType, bool isBlackList = true, Func<uint, List<int>, int, bool, bool> act = null, Func<string, int> func = null ) { StringCollection geoCollection = null; if ( ((srcList != null) && (srcList.Count > 0)) && ((listType == IpFilterType.GeoASN) || (listType == IpFilterType.GeoCountry)) ) { geoCollection = new StringCollection(); foreach (int num in srcList) { geoCollection.Add(num.ToString()); } } return stACL._IpFilterCreate( null, ((listType == IpFilterType.GeoASN) ? geoCollection : null), ((listType == IpFilterType.GeoCountry) ? geoCollection : null), true, ((listType == IpFilterType.GeoASN) ? isBlackList : true), ((listType == IpFilterType.GeoCountry) ? isBlackList : true), act, func ); } /// <summary> /// Create IpFilter /// Full based StringCollection /// </summary> /// <param name="strIPList">IP Range source</param> /// <param name="strASNList">Geo ASN source</param> /// <param name="strCountryList">Geo Country source</param> /// <param name="isIpBlackList">Boolean, Ip source is BlackList</param> /// <param name="isGeoBlackList">Boolean, Geo source is BlackList</param> /// <param name="act"></param> /// <returns></returns> public static stIPFilter IpFilterCreate( StringCollection strIPList, StringCollection strASNList, StringCollection strCountryList, bool isIpBlackList = true, bool isGeoAsnBlackList = true, bool isGeoCountryBlackList = true, Func<uint, List<int>, int, bool, bool> act = null, Func<string, int> func = null ) { return stACL._IpFilterCreate(strIPList, strASNList, strCountryList, isIpBlackList, isGeoAsnBlackList, isGeoCountryBlackList, act, func); } #endregion #region IpFilterIpRange /// <summary> /// Check IP in list Ip Range (stIpRange) /// </summary> /// <param name="IpListRange">structure List stIpRange</param> /// <param name="ips">IP string</param> /// <param name="isBlackList">bool is BlackList true, White list false</param> /// <returns></returns> public static bool IpFilterIpRange(this List<stIpRange> IpListRange, string ips, bool isBlackList = true) { if (string.IsNullOrWhiteSpace(ips)) { return false; } uint ipa = 0; try { ipa = ips.IpStringToUInt(); if (ipa == 0) { return false; } } catch (Exception) { return false; } return stACL._IpFilterIpRange(IpListRange, ipa, isBlackList); } public static bool IpFilterIpRange(this List<stIpRange> IpListRange, uint ipa, bool isBlackList = true) { if (ipa == 0) { return false; } return stACL._IpFilterIpRange(IpListRange, ipa, isBlackList); } public static bool IpFilterIpRange(this List<stIpRange> IpListRange, uint ipa, stACL.IpFilterType ipListType = stACL.IpFilterType.BlackList) { if (ipa == 0) { return false; } return stACL._IpFilterIpRange(IpListRange, ipa, ((ipListType == stACL.IpFilterType.WhiteList) ? false : true)); } private static bool _IpFilterIpRange(List<stIpRange> IpListRange, uint ipa, bool isBlackList) { if ((IpListRange == null) || (IpListRange.Count == 0)) { return false; } foreach (stIpRange acl in (List<stIpRange>)IpListRange) { if ((ipa >= acl.ipStart) && ((ipa <= acl.ipEnd))) { return ((isBlackList) ? true : false); } } return ((isBlackList) ? false : true); } #endregion #region IpFilterCheck /// <summary> /// Check IP in stIPFilter structure set /// </summary> /// <param name="ipData">stIPFilter structure set</param> /// <param name="ipa">IP <see cref="System.Net.IPAddress"/></param> /// <returns>Boolean is found reverse true/false for Black or White list</returns> public static bool IpFilterCheck(this stIPFilter ipData, IPAddress ipa) { if ((ipa == null) || (ipData == null)) { return false; } uint ipu = 0; try { ipu = ipa.IpAddressToUInt(); if (ipu == 0) { return false; } } catch (Exception) { return false; } return stACL.IpFilterCheck(ipData, ipu); } /// <summary> /// Check IP in stIPFilter structure set /// </summary> /// <param name="ipData">stIPFilter structure set</param> /// <param name="ips">IP string</param> /// <returns>Boolean is found reverse true/false for Black or White list</returns> public static bool IpFilterCheck(this stIPFilter ipData, string ips) { if ((string.IsNullOrWhiteSpace(ips)) || (ipData == null)) { return false; } uint ipu = 0; try { ipu = ips.IpStringToUInt(); if (ipu == 0) { return false; } } catch (Exception) { return false; } return stACL.IpFilterCheck(ipData, ipu); } /// <summary> /// Check IP in stIPFilter structure set /// </summary> /// <param name="ipData">stIPFilter structure set</param> /// <param name="ipu">IP unsigned int, produced IpStringToUInt()</param> /// <returns>Boolean is found reverse true/false for Black or White list</returns> public static bool IpFilterCheck(this stIPFilter ipData, uint ipu = 0) { if (ipu == 0) { return true; } if ((ipu == localHost) || (ipData == null)) { return false; } bool ret = false; bool cond = ((ipData.IpFilterType == IpFilterType.WhiteList) ? false : true); if (ipData.IpRange.Count > 0) { ret = ipData.IpRange.IpFilterIpRange( ipu, cond ); } if ( (((ret) && (!cond)) || ((!ret) && (cond))) && (ipData.GeoDataASN.Count > 0) ) { cond = ((ipData.GeoAsnFilterType == IpFilterType.WhiteList) ? false : true); /// prototype stGeo.GeoFilter.InGeoRange( /// uint ip address, /// List<int> list numer asn or contry, /// int type (int)enum stACL.IpFilterType asn or contry, /// bool isBlackList) ret = ipData.GeoAction( ipu, ipData.GeoDataASN, (int)stACL.IpFilterType.GeoASN, cond ); } if ( (((ret) && (!cond)) || ((!ret) && (cond))) && (ipData.GeoDataCounry.Count > 0) ) { cond = ((ipData.GeoCountryFilterType == IpFilterType.WhiteList) ? false : true); ret = ipData.GeoAction( ipu, ipData.GeoDataCounry, (int)stACL.IpFilterType.GeoCountry, cond ); } return ret; } #endregion } }
35.800366
148
0.453676
[ "MIT" ]
PetersSharp/stCoCServer
stCoCServer/stExtLib/stNet-dll/stIPFilterACL.cs
19,549
C#