content
stringlengths
23
1.05M
using static System.Console; using System.IO; using System.Reflection; public class Program { public static void Main() { WriteLine(Path.Combine(Directory.GetCurrentDirectory(), @"EmailTemplate/email.html")); WriteLine(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"EmailTemplate/email.html")); } } //https://pt.stackoverflow.com/q/54119/101
using System; using System.Threading.Tasks; using N8T.Infrastructure.App.Dtos; using ShoppingCartService.Domain.Exception; using ShoppingCartService.Domain.Gateway; namespace ShoppingCartService.Infrastructure.Extensions { public static class CartDtoExtensions { public static async Task<CartDto> InsertItemToCartAsync(this CartDto cart, int quantity, Guid productId, IProductCatalogGateway productCatalogService) { var item = new CartItemDto {Quantity = quantity, ProductId = productId}; var product = await productCatalogService.GetProductByIdAsync(productId); if (product is not null) { item.ProductName = product.Name; item.ProductPrice = product.Price; item.ProductImagePath = product.ImageUrl; item.ProductDescription = product.Description; item.InventoryId = product.Inventory.Id; item.InventoryLocation = product.Inventory.Location; item.InventoryWebsite = product.Inventory.Website; item.InventoryDescription = product.Inventory.Description; } cart.Items.Add(item); return cart; } public static async Task<CartDto> CalculateCartAsync(this CartDto cart, IProductCatalogGateway productCatalogService, IShippingGateway shippingGateway, IPromoGateway promoGateway) { //DEMO: <tracing> temporary to slow-down the response // await Task.Delay(TimeSpan.FromSeconds(2)); if (cart.Items.Count > 0) { cart.CartItemTotal = 0.0D; foreach (var cartItemTemp in cart.Items) { var product = await productCatalogService.GetProductByIdAsync(cartItemTemp.ProductId); if (product is null) { throw new ProductNotFoundException(cartItemTemp.ProductId); } cart.CartItemPromoSavings += cartItemTemp.PromoSavings * cartItemTemp.Quantity; cart.CartItemTotal += product.Price * cartItemTemp.Quantity; } shippingGateway.CalculateShipping(cart); } promoGateway.ApplyShippingPromotions(cart); cart.CartTotal = cart.CartItemTotal + cart.ShippingTotal; return cart; } } }
using System; using System.Collections.Generic; using UnityEngine; namespace ET { public class TowerAIAwakeSystem : AwakeSystem<TowerAI> { public override void Awake(TowerAI self) { self.Awake(); } } public class TowerAIUpdateSystem : UpdateSystem<TowerAI> { public override void Update(TowerAI self) { self.Update(); } } public class TowerAI : AIBase { public override AIType aiType => AIType.Tower; enum State { Wait, Run } private Unit unit; private TargetableUnitComponent targetComponent; private State state; internal void Awake() { unit = GetParent<Unit>(); targetComponent = unit.GetComponent<TargetableUnitComponent>(); targetComponent.AddTrigger(unit, OnEnermyEnter, OnEnermyExit); state = State.Run; Game.EventSystem.Publish_Sync(new ET.EventType.PlayAnimation { unit = unit, ainmationKey = AinmationKey.Idle, dir = default, }); } private void OnEnermyEnter(Unit unit) { targetComponent.AddEnermy(unit); } private void OnEnermyExit(Unit unit) { targetComponent.RemoveEnermy(unit); } internal void Update() { var now = TimeHelper.ClientNow(); switch (state) { case State.Wait: return; case State.Run: //if (now - lastAtkTime < atkInterval) // return; if (targetComponent.targetCount <= 0) return; //lastAtkTime = now; BattleHelper.PlayerSkill(unit, now); //Unit target = targetComponent.GetFirst(); //if (!target) //{ // return; //} //var targetNum = target.GetComponent<NumericComponent>(); //int damage = num.GetAsInt(NumericType.Atk) - targetNum.GetAsInt(NumericType.Def); //damage = Mathf.Clamp(damage, 0, int.MaxValue); ////todo //Game.EventSystem.Publish_Sync(new ET.EventType.ShowDebugAtkLine //{ // unit = unit, // target = target, // damage = damage, // hp = targetNum.GetAsInt(NumericType.Hp), // maxHp = targetNum.GetAsInt(NumericType.MaxHp), //}); //target.GetComponent<DamageComponent>().Damage(unit,damage); return; default: break; } } } }
using MSHC.Lang.Attributes; namespace AlephNote.Common.Settings.Types { public enum URLMatchingMode { [EnumDescriptor("Standard-conform")] StandardConform, [EnumDescriptor("Extended character set")] ExtendedMatching, [EnumDescriptor("Tolerant")] Tolerant, } }
using OrchardCore.Workflows.ViewModels; using Rework.ContentApproval.Workflows.Activities; namespace Rework.ContentApproval.Workflows.ViewModels { public class ApprovalRequestEventViewModel : ActivityViewModel<ApprovalRequestEvent> { public ApprovalRequestEventViewModel() { } public ApprovalRequestEventViewModel(ApprovalRequestEvent activity) : base(activity) { } } }
@model Core1.Web.Features.Accounts.ConfirmEmail.CommandResult @{ ViewData["Title"] = "Confirm Email"; ViewData["ShowHeader"] = true; ViewData["ShowCookieConsent"] = false; } <div class="container"> <div class="columns"> <div class="column"> @if (Model.Succeeded) { <h2 class="title is-2">Email Confirmed</h2> <div class="field"> <p>Thank you for confirming your email.</p> </div> @if (!User.Identity.IsAuthenticated) { <a href="~/Accounts/Login" class="button is-link">Login</a> } else { <a href="~/Surveys/Index" class="button is-link">Go to Surveys</a> } } else { <h2 class="title is-2">Unable to Confirm Email</h2> <p>Something went wrong while confirming your email address.</p> } </div> </div> </div>
namespace OnlyM.Core.Utils { using System.Collections.ObjectModel; using System.Collections.Specialized; public class ObservableCollectionEx<T> : ObservableCollection<T> { private bool _notificationSupressed; private bool _supressNotification; public bool SupressNotification { get => _supressNotification; set { _supressNotification = value; if (_supressNotification == false && _notificationSupressed) { OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); _notificationSupressed = false; } } } protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { if (SupressNotification) { _notificationSupressed = true; return; } base.OnCollectionChanged(e); } } }
using System; using RabbitMQ.Client; namespace EasyNetQ.Producer { public interface IPublishConfirmationListener : IDisposable { IPublishConfirmationWaiter GetWaiter(IModel model); } }
using System.Collections.ObjectModel; using System.Windows.Input; using What_Should_I_Do.Models; using Xamarin.Forms; namespace What_Should_I_Do.ViewModels { public sealed class MainViewModel { public ObservableCollection<Reminder> Reminders => App.Reminders; public ICommand AddCommand { get; } public ICommand DeleteCommand { get; } public MainViewModel() { AddCommand = new Command(HandleAdd); DeleteCommand = new Command<Reminder>(HandleDelete); } private async void HandleAdd() { var nav = (NavigationPage)Application.Current.MainPage; await nav.PushAsync(new AddItemPage()); } private async void HandleDelete(Reminder reminder) { await App.Database.DeleteNoteAsync(reminder); Reminders.Remove(reminder); } } }
using System; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Android.Graphics; using Android.Animation; using Android.Graphics.Drawables; using Android.Views.Animations; using SVGParser = Org.Anddev.Andengine.Extension.Svg.SVGParser; namespace FriendTab { public static class SvgUtils { public static Bitmap GetBitmapFromSvgRes (Android.Content.Res.Resources resources, int resID, int width, int height) { var svg = SVGParser.ParseSVGFromResource (resources, resID); var bmp = Bitmap.CreateBitmap (width, height, Bitmap.Config.Argb8888); using (var c = new Canvas (bmp)) { var dst = new RectF (0, 0, width, height); c.DrawPicture (svg.Picture, dst); } // Returns an immutable copy return Bitmap.CreateBitmap (bmp); } public static Bitmap GetBitmapFromSvgString (string svgString, int width, int height) { var svg = SVGParser.ParseSVGFromString (svgString); var bmp = Bitmap.CreateBitmap (width, height, Bitmap.Config.Argb8888); using (var c = new Canvas (bmp)) { var dst = new RectF (0, 0, width, height); c.DrawPicture (svg.Picture, dst); } // Returns an immutable copy return Bitmap.CreateBitmap (bmp); } } }
using Flutterwave.Net.Utilities; using System.ComponentModel; namespace Flutterwave.Net { public enum Currency { /// <summary> /// "EUR" /// </summary> [Description(AppConstants.EURO_CODE)] Euro, /// <summary> /// "GHS" /// </summary> [Description(AppConstants.GHANAIAN_CEDI_CODE)] GhanaianCedi, /// <summary> /// "KES" /// </summary> [Description(AppConstants.KENYAN_SHILLING_CODE)] KenyanShilling, /// <summary> /// "NGN" /// </summary> [Description(AppConstants.NIGERIAN_NAIRA_CODE)] NigerianNaira, /// <summary> /// "GBP" /// </summary> [Description(AppConstants.POUND_STERLING_CODE)] PoundSterling, /// <summary> /// "RWF" /// </summary> [Description(AppConstants.RWANDAN_FRANC_CODE)] RwandanFranc, /// <summary> /// "SLL" /// </summary> [Description(AppConstants.SIERRA_LEONEAN_LEONE_CODE)] SierraLeoneanLeone, /// <summary> /// "ZAR" /// </summary> [Description(AppConstants.SOUTH_AFRICAN_RAND_CODE)] SouthAfricanRand, /// <summary> /// "TZS" /// </summary> [Description(AppConstants.TANZANIAN_SHILLING_CODE)] TanzanianShilling, /// <summary> /// "UGX" /// </summary> [Description(AppConstants.UGANDAN_SHILLING_CODE)] UgandanShilling, /// <summary> /// "USD" /// </summary> [Description(AppConstants.UNITED_STATES_DOLLAR_CODE)] UnitedStatesDollar, /// <summary> /// "XOF" /// </summary> [Description(AppConstants.WEST_AFRICAN_CFA_FRANC_CODE)] WestAfricanCFAFranc, /// <summary> /// "ZMW" /// </summary> [Description(AppConstants.ZAMBIAN_KWACHA_CODE)] ZambianKwacha }; }
namespace _InputTest.Entity.Scripts.Combat { public class Attack { public int Damage { get; } public bool Critical { get; } public Attack(int damage, bool critical) => (Damage, Critical) = (damage, critical); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DesignerAttribute; namespace Microsoft.CodeAnalysis.Remote { internal sealed partial class RemoteDesignerAttributeIncrementalAnalyzer : AbstractDesignerAttributeIncrementalAnalyzer { /// <summary> /// Channel back to VS to inform it of the designer attributes we discover. /// </summary> private readonly RemoteCallback<IRemoteDesignerAttributeDiscoveryService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; public RemoteDesignerAttributeIncrementalAnalyzer( RemoteCallback<IRemoteDesignerAttributeDiscoveryService.ICallback> callback, RemoteServiceCallbackId callbackId ) { _callback = callback; _callbackId = callbackId; } protected override async ValueTask ReportProjectRemovedAsync( ProjectId projectId, CancellationToken cancellationToken ) { await _callback .InvokeAsync( (callback, cancellationToken) => callback.OnProjectRemovedAsync(_callbackId, projectId, cancellationToken), cancellationToken ) .ConfigureAwait(false); } protected override async ValueTask ReportDesignerAttributeDataAsync( ImmutableArray<DesignerAttributeData> data, CancellationToken cancellationToken ) { await _callback .InvokeAsync( (callback, cancellationToken) => callback.ReportDesignerAttributeDataAsync( _callbackId, data, cancellationToken ), cancellationToken ) .ConfigureAwait(false); } } }
using MediatR; using System.Diagnostics.CodeAnalysis; namespace Liquid.WebApi.Http.UnitTests.Mocks { [ExcludeFromCodeCoverage] public class TestCaseRequest : IRequest<TestCaseResponse> { } }
using System.Linq; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Xunit; namespace MR.Augmenter { public class AugmenterServiceCollectionExtensionsTest : TestHost { [Fact] public void Works() { var services = new ServiceCollection(); services.AddAugmenter(config => { config.Configure<TestModel1>(c => { c.Add("Bar", (_, __) => "bar"); }); }); services.Configure<AugmenterConfiguration>(config => { config.Configure<TestModel1>(c => { c.Add("Bar2", (_, __) => "bar2"); }); }); var provider = services.BuildServiceProvider(); var augmenter = provider.GetRequiredService<IAugmenter>(); var configuration = provider.GetRequiredService<IOptions<AugmenterConfiguration>>().Value; configuration.TypeConfigurations.Should() .HaveCount(1).And .Subject.First().Type.Should().Be(typeof(TestModel1)); configuration.TypeConfigurations.First().Augments.Should().HaveCount(2); } } }
using System; using calc1.twoOper; using NUnit.Framework; namespace calc1.Tests.twoOper { public class CalculaterfactoryTests { [TestCase("plus", typeof(Add))] [TestCase("minus", typeof(Subtraction))] [TestCase("mul", typeof(Multiplication))] [TestCase("div", typeof(Division))] public void CreatCalculatorTest(string name, Type type) { ICalculate calculate = Calculaterfactory.CreatCalculator(name); Assert.IsInstanceOf(type, calculate); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using FeatureBits.Data.EF; using FluentAssertions; using Xunit; namespace FeatureBits.Data.Test { public class FeatureBitsEfDbContextTests : IDisposable { private readonly FeatureBitsEfDbContext _it; public FeatureBitsEfDbContextTests() { _it = FeatureBitEfHelper.SetupDbContext().Item1; } public void Dispose() { _it?.Dispose(); } [Fact] public void ItCanBeCreated() { _it.Should().NotBeNull(); } [Fact] public void ItHasAFeatureBitDefinitionsDbSet() { _it.FeatureBitDefinitions.Should().NotBeNull(); } } }
using System; using Foundation; using InputMask.Classes.Model; using UIKit; namespace InputMask.Classes.View { public class MaskedTextFieldDelegate : UITextFieldDelegate, IUITextFieldDelegate { private string _maskFormat; private bool _autocomplete; private bool _autocompleteOnFocus; public Mask mask; private IMaskedTextFieldDelegateListener listener; public IMaskedTextFieldDelegateListener Listener { get { return listener; } set { listener = value; } } public string MaskFormat { get { return _maskFormat; } set { _maskFormat = value; mask = Mask.GetOrCreate(value); } } public bool AutoComplete { get { return _autocomplete; } set { _autocomplete = value; } } public bool AutoCompleteOnFocus { get { return _autocompleteOnFocus; } set { _autocompleteOnFocus = value; } } public MaskedTextFieldDelegate(string format) { _maskFormat = format; mask = Mask.GetOrCreate(format); _autocomplete = _autocompleteOnFocus = false; } public MaskedTextFieldDelegate() : this(string.Empty) { } public void Put(string text, UITextField field) { var result = mask.Apply(new CaretString(text, text.Length - 1), _autocomplete); field.Text = result.FormattedText.Content; var position = result.FormattedText.CaretPosition; SetCaretPosition(position, field); listener?.TextField(field, result.Complete, result.ExtractedValue); } public string Placeholder() { return mask.Placeholder(); } public int AcceptableTextLength() { return mask.AcceptableTextLength(); } public int TotalTextLength() { return mask.TotalTextLength(); } public int AcceptableValueLength() { return mask.AcceptableValueLength(); } public int TotalValueLength() { return mask.TotalValueLength(); } public override bool ShouldChangeCharacters(UITextField textField, NSRange range, string replacementString) { string extractedValue; bool complete; if (IsDeletion(range, replacementString)) { extractedValue = DeleteText(range, textField, out complete); } else { extractedValue = ModifyText(range, textField, replacementString, out complete); } listener.TextField(textField, complete, extractedValue); listener.ShouldChangeCharacters(textField, range, replacementString); return false; } public string DeleteText(NSRange range, UITextField field, out bool complete) { var text = ReplaceCharacters(field.Text, range, string.Empty); var result = mask.Apply(new CaretString(text, range.Location), false); field.Text = result.FormattedText.Content; SetCaretPosition(range.Location, field); complete = result.Complete; return result.ExtractedValue; } public string ModifyText(NSRange range, UITextField field, string content, out bool complete) { var updatedText = ReplaceCharacters(field.Text, range, content); var result = mask.Apply(new CaretString(updatedText, CaretPosition(field) + content.Length), AutoComplete); field.Text = result.FormattedText.Content; var position = result.FormattedText.CaretPosition; SetCaretPosition(position, field); complete = result.Complete; return result.ExtractedValue; } public void SelectionWillChange(IUITextInput uiTextInput) { var field = uiTextInput as UITextField; if (field != null) { field.ShouldBeginEditing(field); } } public void SelectionDidChange(IUITextInput uiTextInput) { var field = uiTextInput as UITextField; if (field != null) { listener.ShouldEndEditing(field); } } public void TextWillChange(IUITextInput textField) { var field = textField as UITextField; if (field != null) { if (AutoCompleteOnFocus && string.IsNullOrEmpty(textField.ToString())) { ShouldChangeCharacters(field, new NSRange(0, 0), string.Empty); } listener.EditingStarted(field); } } public void TextDidChange(IUITextInput textField) { var field = textField as UITextField; if (field != null) { listener.EditingEnded(field); } } public bool TextFieldShouldClear(UITextField textField) { var shouldClear = listener.ShouldClear(textField); if (shouldClear) { var result = mask.Apply(new CaretString(string.Empty, 0), AutoComplete); listener.TextField(textField, result.Complete, result.ExtractedValue); } return shouldClear; } public bool TextFieldShouldReturn(UITextField textField) { return listener.ShouldReturn(textField); } public bool IsDeletion(NSRange range, string content) { return range.Length > 0 && content.Length == 0; } public string ReplaceCharacters(string text, NSRange range, string newText) { if (text != null) { var strg = new NSString(text); var result = new NSMutableString(); result.Append(strg); var newContent = new NSString(newText); if (range.Length > 0) { result.Replace(range, newContent); return text.Replace(text, newText); } else { result.Insert(newContent, range.Location); return result; } } return string.Empty; } public nint CaretPosition(UITextField field) { if (!field.IsFirstResponder) return field.Text.Length; var range = field.SelectedTextRange; if (range != null) { var selectedTextLocation = range.Start; return field.GetOffsetFromPosition(field.BeginningOfDocument, selectedTextLocation); } return 0; } public void SetCaretPosition(nint position, UITextField field) { if (!field.IsFirstResponder) return; if (position > field.Text.Length) return; var from = field.GetPosition(field.BeginningOfDocument, position); var to = field.GetPosition(from, 0); field.SelectedTextRange = field.GetTextRange(from, to); } } }
using System.Threading.Tasks; namespace ESO_LangEditor.GUI.Services { public interface IStartupCheck { void UpdateEditor(); Task UpdateUpdater(); //bool CompareDatabaseRevNumber(); Task DownloadFullDatabase(); Task SyncRevDatabase(); Task StartupTaskList(); Task Login(); Task LoginTaskList(); Task SyncUsers(); //Task SyncUserInfo(); } }
using Digitteck.Gateway.DMapper; using Digitteck.Gateway.Service.Common.Guards; using Digitteck.Gateway.Service.Exceptions; using Digitteck.Gateway.SourceModels; using System; using System.Linq; namespace Digitteck.Gateway.Service.JsonModelProvider { public sealed class JSDownstreamMap : DataMap<JSDownstream, Downstream> { public override Downstream Map(JSDownstream source, DataMapper provider) { try { Ensure.NotNull(source, nameof(source)); Ensure.NotNull(provider, nameof(provider)); return new Downstream { RunAsync = source.RunAsync, Operations = provider.Map<OperationCore>(source.Operations).ToList() }; } catch (Exception ex) { throw new GatewayException(ErrorCode.MappingError, ex.Message); } } } }
using System; using CSF.Validation; namespace Agiil.Domain.Tickets { public class EditTicketResponse { readonly IValidationResultInterpreter resultInterpreter; public readonly IValidationResult ValidationResult; public Ticket Ticket { get; private set; } public bool IdentityIsInvalid => resultInterpreter.IncludesFailureFor<EditTicketRequest>(ValidationResult, x => x.Identity); public bool TitleIsInvalid => resultInterpreter.IncludesFailureFor<EditTicketRequest>(ValidationResult, x => x.Title); public bool DescriptionIsInvalid => resultInterpreter.IncludesFailureFor<EditTicketRequest>(ValidationResult, x => x.Description); public bool SprintIsInvalid => resultInterpreter.IncludesFailureFor<EditTicketRequest>(ValidationResult, x => x.SprintIdentity); public bool StoryPointsAreInvalid => resultInterpreter.IncludesFailureFor<EditTicketRequest>(ValidationResult, x => x.StoryPoints); public bool IsSuccess => ValidationResult.IsSuccess; protected EditTicketResponse() { } public EditTicketResponse(IValidationResult result, IValidationResultInterpreter resultInterpreter, Ticket createdTicket = null) { Ticket = createdTicket; this.ValidationResult = result ?? throw new ArgumentNullException(nameof(result)); this.resultInterpreter = resultInterpreter ?? throw new ArgumentNullException(nameof(resultInterpreter)); } } }
// ThreadDataTransferII.cs // // Showing how to pass data to a thread // // (C) Datasim Education BV 2009 // using System; using System.Threading; public class ThreadData_II { public static void Main() { // Create a thread running the "Print" method. Thread ts = new Thread(delegate(){Print("Hi double O: ", 007);}); // Start the thread ts.Start(); // Now we can do something else in main threa Console.WriteLine("Main method"); } // The method that will be run by the thread public static void Print(string myMessage, int number) { // Cast object to a string Console.WriteLine("{0}, {1}", myMessage, number); } }
using UnityEngine; using System.Runtime.InteropServices; using System; // TODO: // - Figure out a way to pass the Y texture directly to the native plugin to prevent marshalling. public class OpencvProcessingInterface { int[] m_outArray = new int[4]; IntPtr m_marshalledBuffer; int m_marshalledSize; byte[] m_lastBufferMarshalled; public int m_lastBufferMarshalledWidth; public int m_lastBufferMarshalledHeight; [DllImport ("__Internal")] private static extern int SaveDescriptors(IntPtr buffer, int width, int height); [DllImport ("__Internal")] private static extern int MatchDescriptors(IntPtr buffer, int width, int height, [In, Out] int[] boundingRect); public int SaveDescriptorsForFrame(Texture2D frame) { MarshalTexture(frame); return SaveDescriptors(m_marshalledBuffer, frame.width, frame.height); } public int MatchDescriptorsForFrame(Texture2D frame, ref Rect boundingRect) { MarshalTexture(frame); int val = MatchDescriptors(m_marshalledBuffer, frame.width, frame.height, m_outArray); if (val == 1) { boundingRect = new UnityEngine.Rect(m_outArray[0], m_outArray[1], m_outArray[2], m_outArray[3]); } return val; } public Color GetColorFromFrameAt(int x, int y) { int pixelStart = 3 * (y * m_lastBufferMarshalledWidth + x); byte r = m_lastBufferMarshalled[pixelStart]; byte g = m_lastBufferMarshalled[pixelStart + 1]; byte b = m_lastBufferMarshalled[pixelStart + 2]; return new Color(r/255.0f, g/255.0f, b/255.0f, 1.0f); } ~OpencvProcessingInterface() { if (m_marshalledBuffer != null) { Marshal.FreeHGlobal(m_marshalledBuffer); } } private void MarshalTexture(Texture2D frame) { if (frame.format != TextureFormat.RGB24) { Debug.LogError("Invalid texture format."); } else { m_lastBufferMarshalled = frame.GetRawTextureData(); m_lastBufferMarshalledWidth = frame.width; m_lastBufferMarshalledHeight = frame.height; int size = Marshal.SizeOf(m_lastBufferMarshalled[0]) * m_lastBufferMarshalled.Length; if (m_marshalledBuffer == null || m_marshalledSize != size) { if (m_marshalledBuffer != null) { Debug.Log("Free old marshalled buffer"); Marshal.FreeHGlobal(m_marshalledBuffer); } m_marshalledBuffer = Marshal.AllocHGlobal(size); m_marshalledSize = size; Debug.Log("Created new marshalled buffer"); } Marshal.Copy(m_lastBufferMarshalled, 0, m_marshalledBuffer, m_lastBufferMarshalled.Length); } } }
using Microsoft.CodeAnalysis; using ProxyInterfaceSourceGenerator.Enums; namespace ProxyInterfaceSourceGenerator.Extensions { internal static class TypeSymbolExtensions { public static TypeEnum GetTypeEnum(this ITypeSymbol ts) { if (ts.IsValueType || ts.IsString()) { return TypeEnum.ValueTypeOrString; } if (ts.TypeKind == TypeKind.Interface) { return TypeEnum.Interface; } return TypeEnum.Complex; } public static bool IsString(this ITypeSymbol ts) { return ts.ToString() == "string" || ts.ToString() == "string?"; } } }
namespace RealTimeThemingEngine.ThemeManagement.Data.Entities { public class ThemeVariableValue { public int ThemeVariableValueId { get; set; } public int ThemeId { get; set; } public int VariableId { get; set; } public string Value { get; set; } public virtual Theme Theme { get; set; } public virtual ThemeVariable ThemeVariable { get; set; } } }
using Godot; using System; public class Singleton : Node { public static byte IconMode = 0; public static byte TrackMode = 0; }
using BepInEx; using BepInEx.Configuration; using System.Collections.Generic; using System.IO; using System.Linq; using Valheim.SpawnThat.Configuration; using Valheim.SpawnThat.Configuration.ConfigTypes; using Valheim.SpawnThat.Core; using Valheim.SpawnThat.Core.Configuration; namespace Valheim.SpawnThat.PreConfigured { public static class SimpleConfigAllCreatures { public static void Initialize() { if (ConfigurationManager.GeneralConfig?.InitializeWithCreatures?.Value ?? false) { string configPath = Path.Combine(Paths.ConfigPath, ConfigurationManager.SimpleConfigFile); if (!File.Exists(configPath)) { ConfigFile file = new ConfigFile(configPath, true); var config = new SimpleConfigurationFile(); Log.LogDebug($"Initializing {ConfigurationManager.SimpleConfigFile}."); CreateEntry(file, "Crow"); CreateEntry(file, "FireFlies"); CreateEntry(file, "Deer"); CreateEntry(file, "Fish1"); CreateEntry(file, "Fish2"); CreateEntry(file, "Fish3"); CreateEntry(file, "Seagal"); CreateEntry(file, "Leviathan"); CreateEntry(file, "Boar"); CreateEntry(file, "Neck"); CreateEntry(file, "Greyling"); CreateEntry(file, "Greydwarf"); CreateEntry(file, "Greydwarf_Elite"); CreateEntry(file, "Greydwarf_shaman"); CreateEntry(file, "Troll"); CreateEntry(file, "Ghost"); CreateEntry(file, "Skeleton"); CreateEntry(file, "Skeleton_NoArcher"); CreateEntry(file, "Skeleton_poison"); CreateEntry(file, "Blob"); CreateEntry(file, "BlobElite"); CreateEntry(file, "Draugr"); CreateEntry(file, "Draugr_Ranged"); CreateEntry(file, "Draugr_Elite"); CreateEntry(file, "Leech"); CreateEntry(file, "Surtling"); CreateEntry(file, "Wraith"); CreateEntry(file, "Wolf"); CreateEntry(file, "Hatchling"); CreateEntry(file, "StoneGolem"); CreateEntry(file, "Fenring"); CreateEntry(file, "Deathsquito"); CreateEntry(file, "Lox"); CreateEntry(file, "Goblin"); CreateEntry(file, "GoblinArcher"); CreateEntry(file, "GoblinBrute"); CreateEntry(file, "GoblinShaman"); CreateEntry(file, "Serpent"); Log.LogDebug($"Finished initializing {ConfigurationManager.SimpleConfigFile}."); } } } private static void CreateEntry(ConfigFile file, string prefabName) { var config = new SimpleConfig(); config.PrefabName.DefaultValue = prefabName; var entryType = typeof(IConfigurationEntry); foreach(var field in typeof(SimpleConfig).GetFields().Where(x => entryType.IsAssignableFrom(x.FieldType))) { var entry = (field.GetValue(config) as IConfigurationEntry); entry.Bind(file, prefabName, field.Name); } } } }
using System; using System.Globalization; using System.Runtime.InteropServices; namespace Drexel.Terminal { /// <summary> /// Represents a coordinate (a pair of a horizontal position and a vertical position). /// </summary> [StructLayout(LayoutKind.Sequential)] public readonly struct Coord : IEquatable<Coord> { /// <summary> /// A coordinate representing a zero offset in both dimensions (0, 0). /// </summary> public static readonly Coord Zero = new Coord(0, 0); /// <summary> /// A coordinate representing a one offset in both dimensions (1, 1). /// </summary> public static readonly Coord OneOffset = new Coord(1, 1); /// <summary> /// A coordinate representing a one offset in the X dimension (1, 0). /// </summary> public static readonly Coord OneXOffset = new Coord(1, 0); /// <summary> /// A coordinate representing a one offset in the Y dimension (0, 1). /// </summary> public static readonly Coord OneYOffset = new Coord(0, 1); /// <summary> /// The horizontal position of this coordinate. /// </summary> public readonly short X; /// <summary> /// The vertical position of this coordinate. /// </summary> public readonly short Y; /// <summary> /// Initializes a new instance of the <see cref="Coord"/> struct. /// </summary> /// <param name="X"> /// The horizontal position of this <see cref="Coord"/>. /// </param> /// <param name="Y"> /// The vertical position of this <see cref="Coord"/>. /// </param> public Coord(short X, short Y) { this.X = X; this.Y = Y; } /// <summary> /// Adds the specified <see cref="Coord"/>s <paramref name="left"/> and <paramref name="right"/> as if they /// were vectors. /// </summary> /// <param name="left"> /// The <see cref="Coord"/> on the left side of the summation. /// </param> /// <param name="right"> /// The <see cref="Coord"/> on the right side of the summation. /// </param> /// <returns> /// The <see cref="Coord"/> resulting from adding the two <see cref="Coord"/> <paramref name="left"/> and /// <paramref name="right"/> together as if they were vectors. /// </returns> public static Coord operator +(Coord left, Coord right) { checked { return new Coord((short)(left.X + right.X), (short)(left.Y + right.Y)); } } /// <summary> /// Subtracts the specified <see cref="Coord"/>s <paramref name="left"/> and <paramref name="right"/> as if /// they were vectors. /// </summary> /// <param name="left"> /// The <see cref="Coord"/> on the left side of the subtraction. /// </param> /// <param name="right"> /// The <see cref="Coord"/> on the right side of the subtraction. /// </param> /// <returns> /// The <see cref="Coord"/> resulting from subtracting the two <see cref="Coord"/>s <paramref name="left"/> and /// <paramref name="right"/> as if they were vectors. /// </returns> public static Coord operator -(Coord left, Coord right) { checked { return new Coord((short)(left.X - right.X), (short)(left.Y - right.Y)); } } public static Coord operator -(Coord coord) { return new Coord((short)(-coord.X), (short)(-coord.Y)); } /// <summary> /// Multiplies the specified <see cref="Coord"/>s <paramref name="left"/> and <paramref name="right"/> as if /// they were vectors. /// </summary> /// <param name="left"> /// The <see cref="Coord"/> on the left side of the multiplication. /// </param> /// <param name="right"> /// The <see cref="Coord"/> on the right side of the multiplication. /// </param> /// <returns> /// The <see cref="Coord"/> resulting from multiplying the two <see cref="Coord"/>s <paramref name="left"/> and /// <paramref name="right"/> as if they were vectors. /// </returns> public static Coord operator *(Coord left, Coord right) { checked { return new Coord((short)(left.X * right.X), (short)(left.Y * right.Y)); } } /// <summary> /// Multiplies the <see cref="Coord"/> <paramref name="right"/> by the specified scalar <paramref name="left"/> /// as if the <see cref="Coord"/> <paramref name="right"/> was a vector. /// </summary> /// <param name="left"> /// The scalar value. /// </param> /// <param name="right"> /// The <see cref="Coord"/>. /// </param> /// <returns> /// The <see cref="Coord"/> resulting from the multiplication of the scalar <paramref name="left"/> and the /// <see cref="Coord"/> <paramref name="right"/> as if the <see cref="Coord"/> was a vector. /// </returns> public static Coord operator *(short left, Coord right) { checked { return new Coord((short)(left * right.X), (short)(left * right.Y)); } } /// <summary> /// Multiplies the <see cref="Coord"/> <paramref name="left"/> by the specified scalar /// <paramref name="right"/> as if the <see cref="Coord"/> <paramref name="left"/> was a vector. /// </summary> /// <param name="left"> /// The <see cref="Coord"/>. /// </param> /// <param name="right"> /// The scalar value. /// </param> /// <returns> /// The <see cref="Coord"/> resulting from the multiplication of the <see cref="Coord"/> /// <paramref name="left"/> and the scalar <paramref name="right"/> as if the <see cref="Coord"/> was a vector. /// </returns> public static Coord operator *(Coord left, short right) { checked { return new Coord((short)(left.X * right), (short)(left.Y * right)); } } /// <summary> /// Returns <see langword="true"/> if <paramref name="left"/> and <paramref name="right"/> have the same /// horizontal and vertical position; otherwise, returns <see langword="false"/>. /// </summary> /// <param name="left"> /// The <see cref="Coord"/> on the left side of the comparison. /// </param> /// <param name="right"> /// The <see cref="Coord"/> on the left side of the comparison. /// </param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> and <paramref name="right"/> have the same horizontal and /// vertical position; otherwise, <see langword="false"/>. /// </returns> public static bool operator ==(Coord left, Coord right) { return left.Equals(right); } /// <summary> /// Returns <see langword="true"/> if <paramref name="left"/> and <paramref name="right"/> do not have the same /// horizontal and vertical position; otherwise, returns <see langword="false"/>. /// </summary> /// <param name="left"> /// The <see cref="Coord"/> on the left side of the comparison. /// </param> /// <param name="right"> /// The <see cref="Coord"/> on the left side of the comparison. /// </param> /// <returns> /// <see langword="true"/> if <paramref name="left"/> and <paramref name="right"/> do not have the same /// horizontal and vertical position; otherwise, <see langword="false"/>. /// </returns> public static bool operator !=(Coord left, Coord right) { return !(left == right); } /// <summary> /// Determines whether this instance and the specified <see cref="object"/> <paramref name="obj"/> are equal. /// </summary> /// <param name="obj"> /// The object this instance should compare itself to. /// </param> /// <returns> /// <see langword="true"/> if this instance is equal to the specified <paramref name="obj"/>; otherwise, /// <see langword="false"/>. /// </returns> public override bool Equals(object obj) { if (obj is Coord other) { return this.Equals(other); } return false; } /// <summary> /// Determines whether this <see cref="Coord"/> and the specified <see cref="Coord"/> <paramref name="other"/> /// have the same horizontal and vertical position. /// </summary> /// <param name="other"> /// The <see cref="Coord"/> this instance should compare itself to. /// </param> /// <returns> /// <see langword="true"/> if this instance and <paramref name="other"/> have the same horizontal and vertical /// position; otherwise, <see langword="false"/>. /// </returns> public bool Equals(Coord other) { return this.X == other.X && this.Y == other.Y; } /// <summary> /// Returns the hash code for this <see cref="Coord"/>. /// </summary> /// <returns> /// The hash code for this <see cref="Coord"/>. /// </returns> public override int GetHashCode() { int hash = 991; hash = (hash * 31) + this.X; hash = (hash * 31) + this.Y; return hash; } /// <summary> /// Returns a <see cref="string"/> that represents this <see cref="Coord"/>. /// </summary> /// <returns> /// A <see cref="string"/> that represents this <see cref="Coord"/>. /// </returns> public override string ToString() { return string.Concat( "(", this.X.ToString(CultureInfo.InvariantCulture), ", ", this.Y.ToString(CultureInfo.InvariantCulture), ")"); } }; }
using System; using System.Xml.Serialization; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// User alias usage mode for AS translations on incoming calls. /// </summary> [Serializable] [XmlRoot(Namespace = "")] public enum IncomingCallToUserAliasMode { [XmlEnum(Name = "Enabled")] Enabled, [XmlEnum(Name = "ExplicitAlias")] ExplicitAlias, [XmlEnum(Name = "Disabled")] Disabled, } }
using Micromed.EventCalculation.Common; using Micromed.ExternalCalculation.Common.Dto; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Micromed.ExternalCalculation.MockExternalCalculation { public class MockPlugin : IExternalCalculationPlugin { public Guid Guid { get; private set; } public string Name { get; private set; } public string Description { get; private set; } public string Author { get; private set; } public string Version { get; private set; } private bool isRunning = false; private void runCommand(string exeCommand) { ProcessStartInfo cmdsi = new ProcessStartInfo(exeCommand); cmdsi.Arguments = ""; Process cmd = Process.Start(cmdsi); cmd.WaitForExit(); } public MockPlugin() { Guid = Guid.Parse("1BC8E16D-3C09-40BE-8EC2-F9D7E4F0111C"); Name = "Mock Calculation"; Description = "Mock External Calculation plugin"; Author = "Micromed"; System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); Version = fvi.FileVersion; } public int Start(PluginParametersDto pluginParameters) { if (isRunning) return 1; //isrunning runCommand("notepad.exe"); isRunning = true; OnProgress(100); return 0; } public bool Stop() { if (!isRunning) return false; isRunning = false; OnCancelled(); return true; } public event EventHandler Completed; protected void OnCompleted() { EventHandler handler = Completed; if (handler != null) handler(this, null); } public event EventHandler Cancelled; protected void OnCancelled() { EventHandler handler = Cancelled; if (handler != null) handler(this, null); } public event EventHandler<string> Error; protected void OnError(string e) { EventHandler<string> handler = Error; if (handler != null) handler(this, e); } public event EventHandler<int> Progress; protected void OnProgress(int e) { EventHandler<int> handler = Progress; if (handler != null) handler(this, e); } public bool NeedTraceFilePathList { get { return true; } } public bool NeedExchangeTraceFilePathList { get { return false; } } public bool NeedExchangeEventFilePath { get { return false; } } public bool NeedExchangeReportFilePath { get { return true; } } public bool NeedExchangeTrendFilePathList { get { return false; } } public bool NeedFilteredData { get { return true; } } public bool DerivationOptionEnabled { get { return false; } } public bool TraceSelectionOptionEnabled { get { return false; } } } }
using System; namespace RxLibrary { public interface ITemperatureSensor { IObservable<double> Readings { get; } } }
// Copyright(c) 2016 Guus Waals (guus_waals@live.nl) // Licensed under the MIT License(MIT) // See "LICENSE.txt" for more information using osu.Framework.GameModes.Testing; using osu.Framework.Graphics3D; namespace FX2.Game.Tests { public class TestTrack3D : TestCase { private Render3DContainer render3DContainer; public override string Name { get; } = "Beatmap (3D)"; public override string Description { get; } = "Tests rendering 3D beatmaps"; public override void Reset() { base.Reset(); } } }
using System.Collections.Generic; using Htc.Vita.Core.Log; namespace Htc.Vita.Core.Config { /// <summary> /// Class DummyConfigV2. /// Implements the <see cref="ConfigV2" /> /// </summary> /// <seealso cref="ConfigV2" /> public class DummyConfigV2 : ConfigV2 { /// <summary> /// Initializes a new instance of the <see cref="DummyConfigV2"/> class. /// </summary> public DummyConfigV2() { Logger.GetInstance(typeof(ConfigV2)).Error($"You are using dummy {typeof(ConfigV2)} instance!!"); } /// <inheritdoc /> protected override ISet<string> OnAllKeys() { return null; } /// <inheritdoc /> protected override bool OnHasKey(string key) { return false; } /// <inheritdoc /> protected override string OnGet(string key) { return null; } } }
using System; using System.Threading.Tasks; using R5T.D0078; using R5T.T0106; using R5T.T0113; using R5T.T0114; using Instances = R5T.T0113.X0001.Instances; namespace System { public static class ISolutionGeneratorExtensions { public static async Task CreateSolution(this ISolutionGenerator _, string repositoryDirectoryPath, string solutionName, IVisualStudioSolutionFileOperator visualStudioSolutionFileOperator, Func<SolutionFileContext, Task> solutionFileContextAction = default) { var solutionFilePath = Instances.SolutionPathsOperator.GetSolutionFilePath( repositoryDirectoryPath, solutionName); await _.CreateSolution( solutionFilePath, visualStudioSolutionFileOperator, solutionFileContextAction); } public static async Task CreateSolution(this ISolutionGenerator _, string solutionFilePath, IVisualStudioSolutionFileOperator visualStudioSolutionFileOperator, Func<SolutionFileContext, Task> solutionFileContextAction = default) { // Create the solution file. await visualStudioSolutionFileOperator.Create(solutionFilePath); // Now modify the solution. var solutionFileContext = Instances.SolutionPathsOperator.GetSolutionFileContext( solutionFilePath); await FunctionHelper.Run(solutionFileContextAction, solutionFileContext); } public static async Task CreateSolutionOnlyIfNotExistsButAlwaysModify(this ISolutionGenerator _, string solutionDirectoryPath, string solutionName, IVisualStudioSolutionFileOperator visualStudioSolutionFileOperator, Func<SolutionFileContext, Task> solutionFileContextAction = default) { var solutionFilePath = Instances.SolutionPathsOperator.GetSolutionFilePath( solutionDirectoryPath, solutionName); await _.CreateSolutionOnlyIfNotExistsButAlwaysModify( solutionFilePath, visualStudioSolutionFileOperator, solutionFileContextAction); } public static async Task CreateSolutionOnlyIfNotExistsButAlwaysModify(this ISolutionGenerator _, string solutionFilePath, IVisualStudioSolutionFileOperator visualStudioSolutionFileOperator, Func<SolutionFileContext, Task> solutionFileContextAction = default) { var solutionFileExists = Instances.FileSystemOperator.FileExists(solutionFilePath); if(!solutionFileExists) { // Create the solution file. await visualStudioSolutionFileOperator.Create(solutionFilePath); } // Now modify the solution. var solutionFileContext = Instances.SolutionPathsOperator.GetSolutionFileContext( solutionFilePath); await FunctionHelper.Run(solutionFileContextAction, solutionFileContext); } } }
using UdonSharp; using VRC.SDKBase; namespace InariUdon.Player { [UdonBehaviourSyncMode(BehaviourSyncMode.NoVariableSync)] public class PlayerEventLogger : UdonSharpBehaviour { #region Public Variables public UI.UdonLogger logger; public string level = "NOTICE"; public string joinedFormat = "{0} <color=green>joined</color> (Total {1})"; public string leftFormat = "{0} <color=orange>left</color> (Total {1})"; #endregion #region Unity Events void Start() { Log("Info", "Initialized"); } #endregion #region Udon Events public override void OnPlayerJoined(VRCPlayerApi player) { Log("Info", string.Format(joinedFormat, player.displayName, VRCPlayerApi.GetPlayerCount())); } public override void OnPlayerLeft(VRCPlayerApi player) { if (player == null) return; Log("Info", string.Format(leftFormat, player.displayName, VRCPlayerApi.GetPlayerCount() - 1)); } #endregion #region UdonLogger private void Log(string level, string log) { logger.Log(level, gameObject.name, log); } #endregion } }
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; namespace ArangoDBNetStandard.Serialization { /// <summary> /// Implements a <see cref="IApiClientSerialization"/> that uses Json.NET. /// </summary> public class JsonNetApiClientSerialization : IApiClientSerialization { /// <summary> /// Deserializes the JSON structure contained by the specified stream /// into an instance of the specified type. /// </summary> /// <typeparam name="T">The type of the object to deserialize to.</typeparam> /// <param name="stream">The stream containing the JSON structure to deserialize.</param> /// <returns></returns> public virtual T DeserializeFromStream<T>(Stream stream) { if (stream == null || stream.CanRead == false) { return default(T); } using (var sr = new StreamReader(stream)) using (var jtr = new JsonTextReader(sr)) { var js = new JsonSerializer(); T result = js.Deserialize<T>(jtr); return result; } } /// <summary> /// Serializes the specified object to a JSON string encoded as UTF-8 bytes, /// following the provided rules for camel case property name and null value handling. /// </summary> /// <typeparam name="T">The type of the object to serialize.</typeparam> /// <param name="item">The object to serialize.</param> /// <param name="useCamelCasePropertyNames">Whether property names should be camel cased (camelCase).</param> /// <param name="ignoreNullValues">Whether null values should be ignored.</param> /// <returns></returns> public virtual byte[] Serialize<T>( T item, bool useCamelCasePropertyNames, bool ignoreNullValues) { var jsonSettings = new JsonSerializerSettings { NullValueHandling = ignoreNullValues ? NullValueHandling.Ignore : NullValueHandling.Include }; if (useCamelCasePropertyNames) { jsonSettings.ContractResolver = new CamelCasePropertyNamesExceptDictionaryContractResolver(); } string json = JsonConvert.SerializeObject(item, jsonSettings); return Encoding.UTF8.GetBytes(json); } } }
//----------------------------------------------------------------------- // <copyright> // Copyright (c) 2018 wanderer. All rights reserved. // </copyright> // <describe> #游戏模块的基类# </describe> // <email> dutifulwanderer@gmail.com </email> // <time> #2018年6月22日 14点59分# </time> //----------------------------------------------------------------------- namespace Wanderer.GameFramework { public abstract class GameFrameworkModule { /// <summary> /// 优先级,默认100 /// </summary> public virtual int Priority => 100; //初始化 public virtual void OnInit() { } /// <summary> /// 关闭当前模块 /// </summary> public abstract void OnClose(); /// <summary> /// 缓存大小 字节 /// </summary> /// <returns></returns> public virtual long CacheSize() { return 0; } /// <summary> /// 清理缓存 /// </summary> public virtual void ClearCache() { } } }
//------------------------------------------------------------------------------ // <auto-generated> // Ten kod został wygenerowany przez narzędzie. // Wersja wykonawcza:4.0.30319.42000 // // Zmiany w tym pliku mogą spowodować nieprawidłowe zachowanie i zostaną utracone, jeśli // kod zostanie ponownie wygenerowany. // </auto-generated> //------------------------------------------------------------------------------ [assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("img/break.png")] [assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("img/ex1.png")] [assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("img/ex10.png")] [assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("img/ex2.png")] [assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("img/ex3.png")] [assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("img/ex4.png")] [assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("img/ex5.png")] [assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("img/ex6.png")] [assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("img/ex7.png")] [assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("img/ex8.png")] [assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("img/ex9.png")] [assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("img/example.jpg")] [assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("img/longbreak.png")] [assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("img/preparation.png")] [assembly: System.Windows.Resources.AssemblyAssociatedContentFileAttribute("img/trainingfinished.png")]
using System.Linq; using System.Threading.Tasks; using AElf.CSharp.Core.Extension; using AElf.Kernel; using AElf.Kernel.Blockchain.Application; using AElf.OS.BlockSync.Dto; using AElf.OS.BlockSync.Infrastructure; using AElf.OS.Network.Application; using AElf.Sdk.CSharp; using AElf.Types; using Shouldly; using Virgil.Crypto; using Xunit; namespace AElf.OS.BlockSync.Application { public class BlockSyncServiceTests : BlockSyncTestBase { private readonly IBlockSyncService _blockSyncService; private readonly IBlockchainService _blockchainService; private readonly INetworkService _networkService; private readonly IBlockSyncStateProvider _blockSyncStateProvider; private readonly IBlockDownloadJobStore _blockDownloadJobStore; private readonly IAnnouncementCacheProvider _announcementCacheProvider; private readonly OSTestHelper _osTestHelper; public BlockSyncServiceTests() { _blockSyncService = GetRequiredService<IBlockSyncService>(); _blockchainService = GetRequiredService<IBlockchainService>(); _networkService = GetRequiredService<INetworkService>(); _blockSyncStateProvider = GetRequiredService<IBlockSyncStateProvider>(); _blockDownloadJobStore = GetRequiredService<IBlockDownloadJobStore>(); _announcementCacheProvider = GetRequiredService<IAnnouncementCacheProvider>(); _osTestHelper = GetRequiredService<OSTestHelper>(); } [Fact] public async Task SyncByAnnounce_Success() { var chain = await _blockchainService.GetChainAsync(); var resp = await _networkService.GetBlocksAsync(chain.BestChainHash, 30, null); var peerBlocks = resp.Payload; var block = peerBlocks[0]; var peerBlockHash = block.GetHash(); var peerBlockHeight = block.Height; { // Sync one block to best chain // BestChainHeight: 12 await _blockSyncService.SyncByAnnouncementAsync(chain, new SyncAnnouncementDto { SyncBlockHash = peerBlockHash, SyncBlockHeight = peerBlockHeight, BatchRequestBlockCount = 5 }); chain = await _blockchainService.GetChainAsync(); chain.BestChainHeight.ShouldBe(12); chain.BestChainHash.ShouldBe(peerBlocks[0].GetHash()); } { // Handle the same announcement again // BestChainHeight: 12 await _blockSyncService.SyncByAnnouncementAsync(chain, new SyncAnnouncementDto { SyncBlockHash = peerBlockHash, SyncBlockHeight = peerBlockHeight, BatchRequestBlockCount = 5 }); chain = await _blockchainService.GetChainAsync(); chain.BestChainHash.ShouldBe(peerBlocks[0].GetHash()); chain.BestChainHeight.ShouldBe(12); } { // Mined one block, and fork await _osTestHelper.MinedOneBlock(); chain = await _blockchainService.GetChainAsync(); chain.BestChainHeight.ShouldBe(13); } { // Receive a higher fork block, sync from the lib // BestChainHeight: 31 block = peerBlocks.Last(); peerBlockHash = block.GetHash(); peerBlockHeight = block.Height; await _blockSyncService.SyncByAnnouncementAsync(chain, new SyncAnnouncementDto { SyncBlockHash = peerBlockHash, SyncBlockHeight = peerBlockHeight, BatchRequestBlockCount = 5 }); var jobInfo = await _blockDownloadJobStore.GetFirstWaitingJobAsync(); jobInfo.TargetBlockHeight.ShouldBe(peerBlockHeight); jobInfo.TargetBlockHash.ShouldBe(peerBlockHash); } } [Fact] public async Task SyncByAnnounce_LessThenFetchLimit_Success() { var response = await _networkService.GetBlockByHashAsync(HashHelper.ComputeFrom("PeerBlock"), null); var peerBlock = response.Payload; var block = await _blockchainService.GetBlockByHashAsync(peerBlock.GetHash()); block.ShouldBeNull(); var chain = await _blockchainService.GetChainAsync(); await _blockSyncService.SyncByAnnouncementAsync(chain, new SyncAnnouncementDto { SyncBlockHash = peerBlock.GetHash(), SyncBlockHeight = peerBlock.Height, BatchRequestBlockCount = 5 }); block = await _blockchainService.GetBlockByHashAsync(peerBlock.GetHash()); block.GetHash().ShouldBe(peerBlock.GetHash()); chain = await _blockchainService.GetChainAsync(); chain.BestChainHash.ShouldBe(peerBlock.GetHash()); chain.BestChainHeight.ShouldBe(peerBlock.Height); } [Fact] public async Task SyncByAnnounce_FetchQueueIsBusy() { var response = await _networkService.GetBlockByHashAsync(HashHelper.ComputeFrom("PeerBlock"), null); var peerBlock = response.Payload; var block = await _blockchainService.GetBlockByHashAsync(peerBlock.GetHash()); block.ShouldBeNull(); var chain = await _blockchainService.GetChainAsync(); var bestChainHash = chain.BestChainHash; var bestChainHeight = chain.BestChainHeight; _blockSyncStateProvider.SetEnqueueTime(OSConstants.BlockFetchQueueName, TimestampHelper.GetUtcNow() .AddMilliseconds(-(BlockSyncConstants.BlockSyncFetchBlockAgeLimit + 100))); await _blockSyncService.SyncByAnnouncementAsync(chain, new SyncAnnouncementDto { SyncBlockHash = peerBlock.GetHash(), SyncBlockHeight = peerBlock.Height, BatchRequestBlockCount = 5 }); block = await _blockchainService.GetBlockByHashAsync(peerBlock.GetHash()); block.ShouldBeNull(); chain = await _blockchainService.GetChainAsync(); chain.BestChainHash.ShouldBe(bestChainHash); chain.BestChainHeight.ShouldBe(bestChainHeight); } [Fact] public async Task SyncByAnnounce_LessThenFetchLimit_FetchReturnFalse() { var chain = await _blockchainService.GetChainAsync(); var bestChainHash = chain.BestChainHash; var bestChainHeight = chain.BestChainHeight; await _blockSyncService.SyncByAnnouncementAsync(chain, new SyncAnnouncementDto { SyncBlockHash = Hash.Empty, SyncBlockHeight = 12, BatchRequestBlockCount = 5 }); chain = await _blockchainService.GetChainAsync(); chain.BestChainHash.ShouldBe(bestChainHash); chain.BestChainHeight.ShouldBe(bestChainHeight); } [Fact] public async Task SyncByAnnounce_MoreThenFetchLimit_Success() { var chain = await _blockchainService.GetChainAsync(); var peerBlockHash = HashHelper.ComputeFrom("PeerBlock"); var peerBlockHeight = chain.LongestChainHeight + BlockSyncConstants.BlockSyncModeHeightOffset +1; await _blockSyncService.SyncByAnnouncementAsync(chain, new SyncAnnouncementDto { SyncBlockHash = peerBlockHash, SyncBlockHeight = peerBlockHeight, BatchRequestBlockCount = 5 }); var jobInfo = await _blockDownloadJobStore.GetFirstWaitingJobAsync(); jobInfo.TargetBlockHeight.ShouldBe(peerBlockHeight); jobInfo.TargetBlockHash.ShouldBe(peerBlockHash); } [Fact] public async Task SyncByAnnounce_Fetch_AttachAndExecuteQueueIsBusy() { _blockSyncStateProvider.SetEnqueueTime(KernelConstants.UpdateChainQueueName, TimestampHelper.GetUtcNow() .AddMilliseconds(-(BlockSyncConstants.BlockSyncAttachAndExecuteBlockAgeLimit + 100))); var response = await _networkService.GetBlockByHashAsync(HashHelper.ComputeFrom("PeerBlock"), null); var peerBlock = response.Payload; var chain = await _blockchainService.GetChainAsync(); await _blockSyncService.SyncByAnnouncementAsync(chain, new SyncAnnouncementDto { SyncBlockHash = peerBlock.GetHash(), SyncBlockHeight = chain.LongestChainHeight + BlockSyncConstants.BlockSyncModeHeightOffset, BatchRequestBlockCount = 5 }); var block = await _blockchainService.GetBlockByHashAsync(peerBlock.GetHash()); block.ShouldBeNull(); } [Fact] public async Task SyncByAnnounce_Download_AttachAndExecuteQueueIsBusy() { _blockSyncStateProvider.SetEnqueueTime(KernelConstants.UpdateChainQueueName, TimestampHelper.GetUtcNow() .AddMilliseconds(-(BlockSyncConstants.BlockSyncAttachAndExecuteBlockAgeLimit + 100))); var response = await _networkService.GetBlockByHashAsync(HashHelper.ComputeFrom("PeerBlock"), null); var peerBlock = response.Payload; var chain = await _blockchainService.GetChainAsync(); var bestChainHash = chain.BestChainHash; var bestChainHeight = chain.BestChainHeight; await _blockSyncService.SyncByAnnouncementAsync(chain, new SyncAnnouncementDto { SyncBlockHash = peerBlock.GetHash(), SyncBlockHeight = chain.LongestChainHeight + BlockSyncConstants.BlockSyncModeHeightOffset +1 , BatchRequestBlockCount = 5 }); chain = await _blockchainService.GetChainAsync(); chain.BestChainHash.ShouldBe(bestChainHash); chain.BestChainHeight.ShouldBe(bestChainHeight); } [Fact] public async Task SyncByAnnounce_Fetch_AttachQueueIsBusy() { _blockSyncStateProvider.SetEnqueueTime(OSConstants.BlockSyncAttachQueueName, TimestampHelper.GetUtcNow().AddMilliseconds(-(BlockSyncConstants.BlockSyncAttachBlockAgeLimit + 100))); var response = await _networkService.GetBlockByHashAsync(HashHelper.ComputeFrom("PeerBlock"), null); var peerBlock = response.Payload; var chain = await _blockchainService.GetChainAsync(); await _blockSyncService.SyncByAnnouncementAsync(chain, new SyncAnnouncementDto { SyncBlockHash = peerBlock.GetHash(), SyncBlockHeight = chain.LongestChainHeight + BlockSyncConstants.BlockSyncModeHeightOffset, BatchRequestBlockCount = 5 }); var block = await _blockchainService.GetBlockByHashAsync(peerBlock.GetHash()); block.ShouldBeNull(); } [Fact] public async Task SyncByAnnounce_Download_AttachQueueIsBusy() { _blockSyncStateProvider.SetEnqueueTime(OSConstants.BlockSyncAttachQueueName, TimestampHelper.GetUtcNow().AddMilliseconds(-(BlockSyncConstants.BlockSyncAttachBlockAgeLimit + 100))); var response = await _networkService.GetBlockByHashAsync(HashHelper.ComputeFrom("PeerBlock"), null); var peerBlock = response.Payload; var chain = await _blockchainService.GetChainAsync(); var bestChainHash = chain.BestChainHash; var bestChainHeight = chain.BestChainHeight; await _blockSyncService.SyncByAnnouncementAsync(chain, new SyncAnnouncementDto { SyncBlockHash = peerBlock.GetHash(), SyncBlockHeight = chain.LongestChainHeight + BlockSyncConstants.BlockSyncModeHeightOffset +1, BatchRequestBlockCount = 5 }); chain = await _blockchainService.GetChainAsync(); chain.BestChainHash.ShouldBe(bestChainHash); chain.BestChainHeight.ShouldBe(bestChainHeight); } [Fact] public async Task SyncByAnnounce_RetryByNextSender() { _blockSyncStateProvider.SetEnqueueTime(OSConstants.BlockSyncAttachQueueName, TimestampHelper.GetUtcNow().AddMilliseconds(-(BlockSyncConstants.BlockSyncAttachBlockAgeLimit + 100))); var response = await _networkService.GetBlockByHashAsync(HashHelper.ComputeFrom("PeerBlock"), null); var peerBlock = response.Payload; _announcementCacheProvider.TryAddOrUpdateAnnouncementCache(peerBlock.GetHash(), peerBlock.Height, "NextPeerPubkey"); var chain = await _blockchainService.GetChainAsync(); await _blockSyncService.SyncByAnnouncementAsync(chain, new SyncAnnouncementDto { SyncBlockHash = peerBlock.GetHash(), SyncBlockHeight = chain.LongestChainHeight + BlockSyncConstants.BlockSyncModeHeightOffset, BatchRequestBlockCount = 5 }); _announcementCacheProvider.TryGetAnnouncementNextSender(peerBlock.GetHash(), out var nextPeerPubkey); nextPeerPubkey.ShouldBeNull(); } [Fact] public async Task SyncByBlock_Success() { var response = await _networkService.GetBlockByHashAsync(HashHelper.ComputeFrom("PeerBlock"), null); var peerBlock = response.Payload; var block = await _blockchainService.GetBlockByHashAsync(peerBlock.GetHash()); block.ShouldBeNull(); var chain = await _blockchainService.GetChainAsync(); await _blockSyncService.SyncByBlockAsync(chain, new SyncBlockDto { BlockWithTransactions = peerBlock, BatchRequestBlockCount = 5 }); block = await _blockchainService.GetBlockByHashAsync(peerBlock.GetHash()); block.GetHash().ShouldBe(peerBlock.GetHash()); chain = await _blockchainService.GetChainAsync(); chain.BestChainHash.ShouldBe(peerBlock.GetHash()); chain.BestChainHeight.ShouldBe(peerBlock.Height); } [Fact] public async Task SyncByBlock_MoreThenFetchLimit_Success() { var chain = await _blockchainService.GetChainAsync(); var peerBlockHash = HashHelper.ComputeFrom("PeerBlock"); var peerBlockHeight = chain.LongestChainHeight + BlockSyncConstants.BlockSyncModeHeightOffset +1; var block = _osTestHelper.GenerateBlockWithTransactions(peerBlockHash, peerBlockHeight); await _blockSyncService.SyncByBlockAsync(chain, new SyncBlockDto { BlockWithTransactions = block, BatchRequestBlockCount = 10, SuggestedPeerPubkey = "SuggestedPeerPubkey" }); var jobInfo = await _blockDownloadJobStore.GetFirstWaitingJobAsync(); jobInfo.TargetBlockHeight.ShouldBe(block.Height); jobInfo.TargetBlockHash.ShouldBe(block.GetHash()); } } }
using System.Data.Entity.ModelConfiguration; using Advertise.DomainClasses.Entities.Products; namespace Advertise.DomainClasses.Configurations.Products { /// <summary> /// </summary> public class ProductSpecificationConfig : EntityTypeConfiguration<ProductSpecification> { /// <summary> /// </summary> public ProductSpecificationConfig() { Property(specification => specification.RowVersion).IsRowVersion(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using BoxLaunch.Actions; using NDesk.Options; namespace BoxLaunch.Commands { public class CleanDirectoryCommand : BaseCommand { public string TargetPath { get; set; } public override void Run(IEnumerable<string> args) { var p = new OptionSet { { "t|target=", "The {TARGET DIRECTORY} that should be purged.", v => TargetPath = v.EndsWith("\\") ? v : v + "\\" } }; var extra = Parse( p, args, "clean-directory", "-t={TARGET DIRECTORY}", "Purges the contents of a directory." ); if (extra == null) return; var action = new CleanDirectoryAction { TargetPath = TargetPath }; action.Execute(); } } }
using System; using System.Collections.Generic; using System.Linq; using SFA.DAS.Commitments.Domain.Entities; using SFA.DAS.Commitments.Domain.Entities.DataLock; using SFA.DAS.Provider.Events.Api.Types; using EventStatus = SFA.DAS.Commitments.Domain.Entities.EventStatus; namespace SFA.DAS.Commitments.Infrastructure.Services { public class PaymentEventMapper : IPaymentEventMapper { public DataLockStatus Map(DataLockEvent dataLockEvent) { return new DataLockStatus { DataLockEventId = dataLockEvent.Id, DataLockEventDatetime = dataLockEvent.ProcessDateTime, PriceEpisodeIdentifier = dataLockEvent.PriceEpisodeIdentifier, ApprenticeshipId = dataLockEvent.ApprenticeshipId, IlrTrainingCourseCode = DeriveTrainingCourseCode(dataLockEvent), IlrTrainingType = DeriveTrainingType(dataLockEvent), IlrActualStartDate = dataLockEvent.IlrStartDate, IlrEffectiveFromDate = dataLockEvent.IlrPriceEffectiveFromDate, IlrPriceEffectiveToDate = dataLockEvent.IlrPriceEffectiveToDate, IlrTotalCost = dataLockEvent.IlrTrainingPrice + dataLockEvent.IlrEndpointAssessorPrice, ErrorCode = DetermineErrorCode(dataLockEvent.Errors), Status = dataLockEvent.Errors?.Any() ?? false ? Status.Fail : Status.Pass, EventStatus = (EventStatus)dataLockEvent.Status }; } private TrainingType DeriveTrainingType(DataLockEvent dataLockEvent) { return dataLockEvent.IlrProgrammeType == 25 ? TrainingType.Standard : TrainingType.Framework; } private string DeriveTrainingCourseCode(DataLockEvent dataLockEvent) { return dataLockEvent.IlrProgrammeType == 25 ? $"{dataLockEvent.IlrStandardCode}" : $"{dataLockEvent.IlrFrameworkCode}-{dataLockEvent.IlrProgrammeType}-{dataLockEvent.IlrPathwayCode}"; } private DataLockErrorCode DetermineErrorCode(Provider.Events.Api.Types.DataLockEventError[] errors) { return ListToEnumFlags<DataLockErrorCode>( errors?.Select(m => m.ErrorCode) .Select(m => m.Replace("_", "")) .ToList()); } public static T ListToEnumFlags<T>(List<string> enumFlagsAsList) where T : struct { if (!typeof(T).IsEnum) throw new NotSupportedException(typeof(T).Name + " is not an Enum"); T flags; if(enumFlagsAsList == null) return default(T); enumFlagsAsList.RemoveAll(c => !Enum.TryParse(c, true, out flags)); var commaSeparatedFlags = string.Join(",", enumFlagsAsList); Enum.TryParse(commaSeparatedFlags, true, out flags); return flags; } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.CommandLine.Parsing; using System.Linq; using BenchmarkDotNet.Attributes; namespace System.CommandLine.Benchmarks.CommandLine { /// <summary> /// Measures the performance of <see cref="Parser"/> when parsing commands. /// </summary> [BenchmarkCategory(Categories.CommandLine)] public class Perf_Parser_NestedCommands { private string _testSymbolsAsString; private Parser _testParser; private Command _rootCommand; /// <remarks> /// 1 - cmd-root /// /// 2 - cmd-root/ /// |-cmd-nested0 /// /// 5 - cmd-root/ /// |-cmd-nested0/ /// |-cmd-nested00/ /// |-cmd-nested000/ /// |-cmd-nested0000 /// </remarks> [Params(1, 2, 5)] public int TestCommandsDepth; private void GenerateTestNestedCommands(Command parent, int depth, int countPerLevel) { if (depth == 0) return; for (int i = 0; i < countPerLevel; i++) { string cmdName = $"{parent.Name}_{depth}.{i}"; Command cmd = new Command(cmdName); parent.AddCommand(cmd); GenerateTestNestedCommands(cmd, depth - 1, countPerLevel); } } [GlobalSetup(Target = nameof(ParserFromNestedCommands_Ctor))] public void SetupRootCommand() { string rootCommandName = "root"; var rootCommand = new Command(rootCommandName); _testSymbolsAsString = rootCommandName; GenerateTestNestedCommands(rootCommand, TestCommandsDepth, TestCommandsDepth); // Choose only one path from the commands tree for the test arguments string ISymbol currentCmd = rootCommand; while (currentCmd.Children.Count > 0) { currentCmd = currentCmd.Children[0]; _testSymbolsAsString = string.Join(" ", _testSymbolsAsString, currentCmd.Name); } _rootCommand = rootCommand; } [GlobalSetup(Target = nameof(Parser_Parse))] public void SetupParser() { SetupRootCommand(); _testParser = new Parser(_rootCommand); } [Benchmark] public Parser ParserFromNestedCommands_Ctor() => new Parser(_rootCommand); [Benchmark] public ParseResult Parser_Parse() => _testParser.Parse(_testSymbolsAsString); } }
using System; using System.Text.Json.Serialization; // TODO: IsInBounds(Rectangle) namespace Engine.Core { /// <summary> /// Represents an integral position in the two-dimensional plane. /// </summary> public struct Position : IEquatable<Position> { /// <summary> /// The x-coordinate of the position. /// </summary> public int X { get; set; } /// <summary> /// The y-coordinate of the position. /// </summary> public int Y { get; set; } /// <summary> /// Whether this position represents the origin (both coordinates zero) /// </summary> [JsonIgnore] public bool IsOrigin => this.X == 0 && this.Y == 0; /// <summary> /// The origin position, with both coordinates set to zero. /// </summary> public static Position Origin => new Position(0, 0); /// <summary> /// Delta position north /// </summary> public static Position North => new Position(0, -1); /// <summary> /// Delta position south /// </summary> public static Position South => new Position(0, 1); /// <summary> /// Delta position west /// </summary> public static Position West => new Position(-1, 0); /// <summary> /// Delta position east /// </summary> public static Position East => new Position(1, 0); /// <summary> /// Construct a position with given coordinates. /// </summary> /// <param name="x">The x-coordinate</param> /// <param name="y">The y-coordinate</param> public Position(int x, int y) { this.X = x; this.Y = y; } /// <summary> /// Check whether this position is inside the bounds described by given rectangle. /// </summary> /// <param name="rectangle">Rectangle providing bounds to check against</param> /// <returns>Flag indicating whether positions lies withing given bounds</returns> public bool IsInBounds(Rectangle rectangle) { return (this.X >= rectangle.TopLeft.X && this.X <= rectangle.BottomRight.X) && (this.Y >= rectangle.TopLeft.Y && this.Y <= rectangle.BottomRight.Y); } /// <summary> /// Check whether this position is inside the bounds described by given size. /// </summary> /// <param name="size">Size providing bounds to check against</param> /// <returns>Flag indicating whether positions lies withing given bounds</returns> public bool IsInBounds(Size size) { return (this.X >= 0 && this.X < size.Width) && (this.Y >= 0 && this.Y < size.Height); } /// <summary> /// Calculate the distance between two points. /// </summary> public static float GetDistance(Position lhs, Position rhs) { return (float) Math.Sqrt( Math.Pow(rhs.X - lhs.X, 2.0) + Math.Pow(rhs.Y - lhs.Y, 2.0) ); } /// <summary> /// Create new position with clamped coordinates /// </summary> /// <param name="min">Minimum values for the two coordinates</param> /// <param name="max">Maximum values for the two coordinates</param> /// <returns></returns> public Position Clamp(Position min, Position max) { return new Position( Math.Max(min.X, Math.Min(max.X, this.X)), Math.Max(min.Y, Math.Min(max.Y, this.Y)) ); } /// <summary> /// Create new position from given string representation /// </summary> public static Position FromString(string value) { var elements = value.Split(','); return new Position(int.Parse(elements[0]), int.Parse(elements[1])); } public override string ToString() { return $"{X},{Y}"; } #region Equality Implementation public bool Equals(Position other) { return X == other.X && Y == other.Y; } public override bool Equals(object obj) { return obj is Position other && Equals(other); } public override int GetHashCode() { return HashCode.Combine(X, Y); } public static bool operator ==(Position left, Position right) { return left.Equals(right); } public static bool operator !=(Position left, Position right) { return !left.Equals(right); } #endregion #region Arithmetic Operators /// <summary> /// Add two positions together. /// </summary> /// <param name="lhs">First position</param> /// <param name="rhs">Second position</param> /// <returns>Position representing the component-wise sum of the given positions.</returns> public static Position operator +(Position lhs, Position rhs) { return new Position(lhs.X + rhs.X, lhs.Y + rhs.Y); } /// <summary> /// Subtract two positions from each other. Note that this might result in negative coordinates. /// </summary> /// <param name="lhs">First position</param> /// <param name="rhs">Second position</param> /// <returns>Position representing the component-wise difference of the given positions.</returns> public static Position operator -(Position lhs, Position rhs) { return new Position(lhs.X - rhs.X, lhs.Y - rhs.Y); } /// <summary> /// Multiply position components with given factor. /// </summary> public static Position operator *(Position lhs, int f) { return new Position(lhs.X * f, lhs.Y * f); } #endregion #region Implicit Conversion Operators /// <summary> /// Implicit conversion from <see cref="Size"/> to a position instance. /// </summary> public static implicit operator Position(Size size) => new Position(size.Width, size.Height); #endregion } }
using Engine.Interfaces.Config; using Engine.Models.Boards; using Engine.Models.Enums; using Engine.Models.Helpers; namespace Engine.Models.Config { public class StaticValueProvider: IStaticValueProvider { private readonly StaticTableCollection _collection; public StaticValueProvider(StaticTableCollection collection) { _collection = collection; } #region Implementation of IStaticValueProvider public int GetValue(Piece piece, Phase phase, Square square) { return GetValue(piece.AsByte(), phase, square.AsString()); } public int GetValue(byte piece, byte phase, byte square) { return GetValue(piece, (Phase)phase, new Square(square).AsString()); } private int GetValue(byte piece, Phase phase, string square) { return _collection.Values[piece].Values[phase].Values[square]; } #endregion #region Overrides of Object public override string ToString() { return _collection.ToString(); } #endregion } }
namespace O10.Client.DataLayer.Enums { public enum ServiceProviderType : short { DocumentsManager = 1, Bank } }
using Synapse.Config; using System.ComponentModel; namespace AutoNuke { public class Config : AbstractConfigSection { [Description("How long until nuke goes off? (-1 = not), (in seconds)")] public float AutoNukeTime { get; set; } = 600; [Description("What is the broadcast message?")] public string AutoNukeMessage { get; set; } = "AutoNuke is going off!"; [Description("Should AutoNuke be cancelable?")] public bool Cancelable { get; set; } = true; } }
using Boxed.Mapping; using LanguageExt; using SJP.Schematic.Core; namespace SJP.Schematic.Serialization.Mapping; public class NumericPrecisionMapper : IImmutableMapper<Dto.NumericPrecision?, Option<INumericPrecision>> , IImmutableMapper<Option<INumericPrecision>, Dto.NumericPrecision?> { public Option<INumericPrecision> Map(Dto.NumericPrecision? source) { return source == null ? Option<INumericPrecision>.None : Option<INumericPrecision>.Some(new NumericPrecision(source.Precision, source.Scale)); } public Dto.NumericPrecision? Map(Option<INumericPrecision> source) { return source.MatchUnsafe( static p => new Dto.NumericPrecision { Precision = p.Precision, Scale = p.Scale }, static () => (Dto.NumericPrecision?)null ); } }
namespace FubuMVC.HelloWorld.Controllers.Earth { public class EarthController { public EarthViewModel Rock(EarthViewModel whereAreWe) { return whereAreWe; } } public class EarthViewModel { public string RawUrl { get; set; } } }
namespace WTabs { public class W_2 : BaseTab { } }
using System.Collections.Generic; using Sharpduino.Base; using Sharpduino.Constants; using Sharpduino.Exceptions; using Sharpduino.Messages; using Sharpduino.Messages.Send; namespace Sharpduino.Creators { public class SamplingIntervalMessageCreator : BaseMessageCreator<SamplingIntervalMessage> { public override byte[] CreateMessage(SamplingIntervalMessage message) { if (message == null) throw new MessageCreatorException("This is not a valid Sampling Interval Message"); var bytes = new List<byte>() { MessageConstants.SYSEX_START, SysexCommands.SAMPLING_INTERVAL, }; bytes.AddRange(BitHelper.GetBytesFromInt(message.Interval)); bytes.Add(MessageConstants.SYSEX_END); return bytes.ToArray(); } } }
// Copyright (c) 2007 James Newton-King. All rights reserved. // Use of this source code is governed by The MIT License, // as found in the license.md file. using System.Collections.Immutable; public class Issue1984 { [Fact] public void Test_NullValue() { var actual = JsonConvert.DeserializeObject<A>("{ Values: null}"); Assert.NotNull(actual); Assert.Null(actual.Values); } [Fact] public void Test_WithoutValue() { var actual = JsonConvert.DeserializeObject<A>("{ }"); Assert.NotNull(actual); Assert.Null(actual.Values); } public class A { public ImmutableArray<string>? Values { get; set; } } }
using UnityEngine; public class DragAndDrop : MonoBehaviour { private PeopleGroup group; private void Start() { group = transform.parent.GetComponent<PeopleGroup>(); } private void OnMouseDown() { group.BeginDrag(); } private void OnMouseUp() { group.StopDrag(); } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall; using FlatRedBall.Input; using FlatRedBall.AI.Pathfinding; using FlatRedBall.Graphics.Animation; using FlatRedBall.Graphics.Particle; using FlatRedBall.Math.Geometry; using FlatRedBall.Math.Splines; using BitmapFont = FlatRedBall.Graphics.BitmapFont; using Cursor = FlatRedBall.Gui.Cursor; using GuiManager = FlatRedBall.Gui.GuiManager; #if FRB_XNA || SILVERLIGHT using Keys = Microsoft.Xna.Framework.Input.Keys; using Vector3 = Microsoft.Xna.Framework.Vector3; using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D; #endif namespace GlueTestProject.Entities { public partial class FlatRedBallTypeEntity { private void CustomInitialize() { this.OffsetScene.Sprites[0].ForceUpdateDependencies(); this.OffsetScene.Sprites[1].ForceUpdateDependencies(); if (this.OffsetScene.Sprites[0].X != this.OffsetScene.Sprites[1].X) { throw new Exception("Attachments on Sprits in Scenes that are offset is not working properly"); } if (this.ShouldHaveAName.Name != "ShouldHaveAName") { throw new Exception("Names on Sprites are not getting assigned on the instance at runtime"); } } private void CustomActivity() { } private void CustomDestroy() { } private static void CustomLoadStaticContent(string contentManagerName) { } } }
using System.IO; using System.Runtime.InteropServices; namespace KHAOSS; public class TransactionRecord { public string Key; public int Version; public byte[] Body; public DocumentChangeType ChangeType; public int SizeInStore; private const int FIXED_HEADER_SIZE = 4 + // Keylength 4 + // Bodylength 4 + // Version 1; // ChangeType public static TransactionRecord LoadFromStream(Stream stream, ref byte[] readBuffer) { Span<byte> headerBytes = stackalloc byte[FIXED_HEADER_SIZE]; var lengthHeaderBytesRead = stream.Read(headerBytes); if (lengthHeaderBytesRead < FIXED_HEADER_SIZE) { return null; } var keyLength = BitConverter.ToInt32(headerBytes.Slice(0, 4)); var bodyLength = BitConverter.ToInt32(headerBytes.Slice(4, 4)); var version = BitConverter.ToInt32(headerBytes.Slice(8, 4)); var changeType = (DocumentChangeType)headerBytes[12]; var variableContentLength = keyLength + bodyLength; SizeBuffer(variableContentLength, ref readBuffer); var recordBytesRead = stream.Read(readBuffer, 0, variableContentLength); if (recordBytesRead != variableContentLength) { return null; //throw new Exception("Failed to read a record"); //TODO: figure out how we want to log or recover from a record missing at the end of a file } var readSpan = readBuffer.AsSpan(0, recordBytesRead); var key = Encoding.UTF8.GetString(readSpan.Slice(0, keyLength)); var body = readSpan.Slice(keyLength, bodyLength); var record = new TransactionRecord { Body = body.ToArray(), ChangeType = changeType, Key = key, Version = version, SizeInStore = FIXED_HEADER_SIZE + variableContentLength }; return record; } private static void SizeBuffer(int recordLength, ref byte[] readBuffer) { // Make sure we have enough space in our read buffer // We don't reallocate a buffer for each read so that we can minimize allocation // Though byte array pooling could also be used here if (readBuffer.Length < recordLength) { // Attempt to minimize effect of slowly growing buffer size a bit var newBufferSize = readBuffer.Length; while (newBufferSize < recordLength) { newBufferSize *= 2; } readBuffer = new byte[newBufferSize]; } } public void WriteTostream(Stream stream) { Span<byte> headerBytes = stackalloc byte[FIXED_HEADER_SIZE]; var keyLength = Key.Length; var bodyLength = Body.Length; var version = Version; var changeType = (byte)ChangeType; MemoryMarshal.Write(headerBytes.Slice(0, 4), ref keyLength); MemoryMarshal.Write(headerBytes.Slice(4, 4), ref bodyLength); MemoryMarshal.Write(headerBytes.Slice(8, 4), ref version); MemoryMarshal.Write(headerBytes.Slice(12, 1), ref changeType); stream.Write(headerBytes); var keyBytes = Encoding.UTF8.GetBytes(Key); stream.Write(keyBytes); stream.Write(Body, 0, Body.Length); SizeInStore = FIXED_HEADER_SIZE + keyLength + bodyLength; } }
using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; namespace DotXxlJob.Core { /// <summary> /// ip utility /// </summary> internal static class IPUtility { #region Private Members /// <summary> /// A类: 10.0.0.0-10.255.255.255 /// </summary> private static long ipABegin, ipAEnd; /// <summary> /// B类: 172.16.0.0-172.31.255.255 /// </summary> private static long ipBBegin, ipBEnd; /// <summary> /// C类: 192.168.0.0-192.168.255.255 /// </summary> private static long ipCBegin, ipCEnd; #endregion #region Constructors /// <summary> /// static new /// </summary> static IPUtility() { ipABegin = ConvertToNumber("10.0.0.0"); ipAEnd = ConvertToNumber("10.255.255.255"); ipBBegin = ConvertToNumber("172.16.0.0"); ipBEnd = ConvertToNumber("172.31.255.255"); ipCBegin = ConvertToNumber("192.168.0.0"); ipCEnd = ConvertToNumber("192.168.255.255"); } #endregion #region Public Methods /// <summary> /// ip address convert to long /// </summary> /// <param name="ipAddress"></param> /// <returns></returns> private static long ConvertToNumber(string ipAddress) { return ConvertToNumber(IPAddress.Parse(ipAddress)); } /// <summary> /// ip address convert to long /// </summary> /// <param name="ipAddress"></param> /// <returns></returns> private static long ConvertToNumber(IPAddress ipAddress) { var bytes = ipAddress.GetAddressBytes(); return bytes[0] * 256 * 256 * 256 + bytes[1] * 256 * 256 + bytes[2] * 256 + bytes[3]; } /// <summary> /// true表示为内网IP /// </summary> /// <param name="ipAddress"></param> /// <returns></returns> public static bool IsIntranet(string ipAddress) { return IsIntranet(ConvertToNumber(ipAddress)); } /// <summary> /// true表示为内网IP /// </summary> /// <param name="ipAddress"></param> /// <returns></returns> private static bool IsIntranet(IPAddress ipAddress) { return IsIntranet(ConvertToNumber(ipAddress)); } /// <summary> /// true表示为内网IP /// </summary> /// <param name="longIP"></param> /// <returns></returns> private static bool IsIntranet(long longIP) { return ((longIP >= ipABegin) && (longIP <= ipAEnd) || (longIP >= ipBBegin) && (longIP <= ipBEnd) || (longIP >= ipCBegin) && (longIP <= ipCEnd)); } /// <summary> /// 获取本机内网IP /// </summary> /// <returns></returns> public static IPAddress GetLocalIntranetIP() { return NetworkInterface .GetAllNetworkInterfaces() .Select(p => p.GetIPProperties()) .SelectMany(p => p.UnicastAddresses ).FirstOrDefault(p => p.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(p.Address) && IsIntranet(p.Address))?.Address; } /// <summary> /// 获取本机内网IP列表 /// </summary> /// <returns></returns> public static List<IPAddress> GetLocalIntranetIPList() { var infList =NetworkInterface.GetAllNetworkInterfaces() .Select(p => p.GetIPProperties()) .SelectMany(p => p.UnicastAddresses) .Where(p => p.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(p.Address) && IsIntranet(p.Address) ); var result = new List<IPAddress>(); foreach (var child in infList) { result.Add(child.Address); } return result; } #endregion } }
using System; using System.Collections; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Timers; using System.Windows; using System.Windows.Threading; namespace SyncFusionLiveTest { public class MainWindowViewModel : INotifyPropertyChanged { private readonly Random _random = new(); private DateTime _visibleMinimum = new(2021, 11, 11); private DateTime _visibleMaximum = new(2021, 11, 11, 2, 0, 0); private ObservableCollection<DataPoint> _dataPoints = new(); public const double DataFps = 100; public const double RefreshFps = 60; public MainWindowViewModel() { var samplePointTimer = new Timer(); samplePointTimer.Elapsed += SamplePointTimerTick; samplePointTimer.Interval = DataFps; samplePointTimer.Start(); var updateTimer = new DispatcherTimer(); updateTimer.Tick += UpdateTimerOnElapsed; updateTimer.Interval = TimeSpan.FromMilliseconds(1000d / RefreshFps); updateTimer.Start(); } public ObservableCollection<DataPoint> DataPoints { get => _dataPoints; set { _dataPoints = value; OnPropertyChanged(nameof(DataPoints)); } } public DateTime VisibleMinimum { get => _visibleMinimum; set { _visibleMinimum = value; OnPropertyChanged(nameof(VisibleMinimum)); } } public DateTime VisibleMaximum { get => _visibleMaximum; set { _visibleMaximum = value; OnPropertyChanged(nameof(VisibleMaximum)); } } public Size MaxZoom => new(3, 1); public double VisibleSeconds => 30; private void SamplePointTimerTick(object? sender, EventArgs e) { GenerateSamplePoint(); } private void UpdateTimerOnElapsed(object? sender, EventArgs e) { lock (((ICollection)DataPoints).SyncRoot) { VisibleMinimum = DateTime.Now.AddSeconds(-(VisibleSeconds + 1)); VisibleMaximum = DateTime.Now.AddSeconds(-1); } } private void GenerateSamplePoint() { var x = DateTime.Now; var y = _random.Next(0, 1000); var point = new DataPoint(x, y); Application.Current.Dispatcher.InvokeAsync(() => { DataPoints.Add(point); DataPoints.Remove((e) => e.X < VisibleMinimum); }, DispatcherPriority.Render); } public event PropertyChangedEventHandler? PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
// Copyright (c) 2015-17 Liam McSherry // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace McSherry.SemanticVersioning.Internals { /// <summary> /// <para> /// Provides tests for the <see cref="PseudoBigInt"/> class. /// </para> /// </summary> [TestClass] public class PseudoBigIntTests { private const string Category = "Pseudo-BigInteger"; /// <summary> /// <para> /// Tests that <see cref="PseudoBigInt.Compare(string, string)"/> /// throws an <see cref="ArgumentNullException"/> when expected. /// </para> /// </summary> [TestMethod, TestCategory(Category)] public void PseudoBigInt_NullArguments() { new Action(() => PseudoBigInt.Compare(null, "555")) .AssertThrows<ArgumentNullException>( "Did not throw on null subject." ); new Action(() => PseudoBigInt.Compare("555", null)) .AssertThrows<ArgumentNullException>( "Did not throw on null against." ); new Action(() => PseudoBigInt.Compare(null, null)) .AssertThrows<ArgumentNullException>( "Did not throw on both null." ); } /// <summary> /// <para> /// Tests that <see cref="PseudoBigInt.Compare(string, string)"/> /// throws a <see cref="FormatException"/> when expected. /// </para> /// </summary> [TestMethod, TestCategory(Category)] public void PseudoBigInt_InvalidFormat() { var badStrings = new[] { // 0 Zero-length input "", // 1 Leading zeroes on number "01", // 2 Leading zeroes on number "001", // 3 Leading zero on zero "00", // 4 Invalid character, negative sign "-1", // 5 Invalid character, close bottom of to numeric range "(1", // 6 Invalid character, close to top of numeric range "@1", // 7 Invalid character "f1", // 8 Invalid character, no numbers "uw", // 9 Invalid character, decimal point "10.2", // 10 Invalid character, decimal comma "10,2", // 11 Invalid character, E notation "1e3", }; for (int i = 0; i < badStrings.Length; i++) { new Action(() => PseudoBigInt.Compare(badStrings[i], "555")) .AssertThrows<FormatException>( $"Did not throw on invalid subject (input #{i})." ); new Action(() => PseudoBigInt.Compare("555", badStrings[i])) .AssertThrows<FormatException>( $"Did not throw on invalid against (input #{i})." ); new Action(() => PseudoBigInt.Compare(badStrings[i], badStrings[i])) .AssertThrows<FormatException>( $"Did not throw on both invalid (input #{i})." ); } } /// <summary> /// <para> /// Tests that <see cref="PseudoBigInt.Compare(string, string)"/> /// produces the correct result for given inputs. /// </para> /// </summary> [TestMethod, TestCategory(Category)] public void PseudoBigInt_Valid() { var vals = new (string Subject, string Against, bool? Result)[] { // 0 Basic equality ("0", "0", null), // 1 Basic equality ("127", "127", null), // 2 Basic inequality, greater ("1", "0", true), // 3 Basic inequality, greater ("391", "87", true), // 4 Basic inequality, greater ("2017", "2015", true), // 5 Basic inequality, lesser ("0", "1", false), // 6 Basic inequality, lesser ("21", "863", false), // 7 Basic inequality, lesser ("2015", "2017", false), // 8 BigInt equality ("36893488147419103232", "36893488147419103232", null), // 9 BigInt equality ("1180591620717411303424", "1180591620717411303424", null), // 10 BigInt inequality, greater ("1180591620717411303424", "1180591620717411300000", true), // 11 BigInt inequality, greater ("1180591620717411303424", "1180591620517411300000", true), // 12 BigInt inequality, greater ("1180591620717411303424", "5823", true), // 13 BigInt inequality, lesser ("1180591620717411303424", "37778931862957161709568", false), // 14 BigInt inequality, lesser ("1180591620717411303424", "1190000000000000000000", false), // 15 BigInt inequality, lesser ("76392", "37778931862957161709568", false), }; for (int i = 0; i < vals.Length; i++) { var actualValue = PseudoBigInt.Compare( subject: vals[i].Subject, against: vals[i].Against ); Assert.AreEqual( expected: vals[i].Result, actual: actualValue, message: $@"Failed on input #{i}: got ""{actualValue}"", " + $@"expected ""{vals[i].Result}""." ); } } } }
using System; using System.IO; namespace Ropufu.UpdaterApp { public interface IInstruction { /// <summary> /// Reads the instruction from a stream. /// </summary> Boolean ReadFrom(StreamReader reader); /// <summary> /// Writes the instruction to a stream. /// </summary> Boolean WriteTo(StreamWriter writer); /// <summary> /// Tries to executes the instruction. /// </summary> /// <returns></returns> Boolean TryExecute(); /// <summary> /// Tries to rollback the instruction. /// </summary> /// <returns></returns> Boolean Rollback(); } }
using System; using System.Collections.Generic; using System.Text; namespace System.IO.Ports { /// <summary> /// Stop bits /// note that only One and Two are implemented /// </summary> public enum StopBits { None = 0, One = 1, Two = 2, OnePointFive = 3 }; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Ardalis.GuardClauses; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Szlem.Domain.Exceptions { public class ValidationFailure { public ValidationFailure(string error) : this(string.Empty, error) { } public ValidationFailure(string propertyName, string error) : this(propertyName, new[] { error }) { } public ValidationFailure(string propertyName, IEnumerable<string> errors) { Guard.Against.Null(propertyName, nameof(propertyName)); Guard.Against.Null(errors, nameof(errors)); PropertyName = propertyName; Errors = errors?.ToArray() ?? throw new ArgumentNullException(nameof(errors)); } public string PropertyName { get; set; } public IReadOnlyCollection<string> Errors { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CharacterPreview : MonoBehaviour { public Sprite[] Previews = new Sprite[4]; public void ChangePreview(int index) { GetComponent<Image>().sprite = Previews[index]; } }
using UnityEngine; using UnityEditor; namespace UnityToolkit.Editor.Controls { public class Control : IDrawable { public virtual void Draw() { } public virtual void DrawAbsolute(Rect position) { } } }
using Microsoft.AspNetCore.Mvc; namespace CutieShop.Models.Utils { public static class CookiesUtils { public static string SessionId(this Controller controller) { return controller.Request.Cookies["sessionId"]; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Autodesk.DesignScript.Runtime; using Autodesk.DesignScript.Interfaces; using Autodesk.DesignScript.Geometry; using Machina; using MAction = Machina.Action; using MPoint = Machina.Point; using MVector = Machina.Vector; using MOrientation = Machina.Orientation; using MTool = Machina.Tool; using System.IO; namespace MachinaDynamo { // ██╗ ██╗ █████╗ ██╗████████╗ // ██║ ██║██╔══██╗██║╚══██╔══╝ // ██║ █╗ ██║███████║██║ ██║ // ██║███╗██║██╔══██║██║ ██║ // ╚███╔███╔╝██║ ██║██║ ██║ // ╚══╝╚══╝ ╚═╝ ╚═╝╚═╝ ╚═╝ // partial class Actions { /// <summary> /// Pause program execution for a specified amount of time. /// </summary> /// <param name="millis">Pause time in milliseconds</param> /// <returns name="Action">Wait Action</returns> public static MAction Wait(double millis = 0) => new ActionWait((long)Math.Round(millis)); } }
/**** * CAP - "Configuration and Property" * Copyright (C) 2020-2021 Yigty.ORG; all rights reserved. * Copyright (C) 2020-2021 Takym. * * distributed under the MIT License. ****/ using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using TakymLib.Tests; namespace CAP.Tests { [TestClass()] public class CapStreamTests : DisposableBaseTests { [TestMethod()] public override void DisposeTest() { var obj = new DummyCapStream(); using (obj) { } Assert.IsNotNull(obj); Assert.IsTrue(obj.IsDisposing); Assert.IsTrue(obj.IsDisposed); } [TestMethod()] public override void DisposeAsyncTest() { var obj = new DummyCapStream(); DisposeAsyncTestCore(obj); Assert.IsNotNull(obj); Assert.IsTrue(obj.IsDisposing); Assert.IsTrue(obj.IsDisposed); } private sealed class DummyCapStream : CapStream { protected override void Dispose(bool disposing) { base.Dispose(disposing); } protected override async ValueTask DisposeAsyncCore() { await base.DisposeAsyncCore(); } } } }
using FazendaFeliz.ApplicationCore.Business; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace FazendaFeliz.ApplicationCore.Interfaces.Repository { public interface IAnuncioRepository : IRepository<Anuncio> { Task<List<AnuncioCompleto>> ObterTodosCompletos(int id_usuario, string tipo, string s); Task<List<Anuncio>> ObterAnunciosProdutor(int id_usuario); } }
using System; using FluentAssertions.NodaTime; using NodaTime; namespace FluentAssertions { public static class InstantAssertionsExtensions { public static InstantAssertions Should(this Instant? value) { if (value == null) throw new ArgumentNullException(nameof(value)); return new InstantAssertions(value); } public static InstantAssertions Should(this Instant value) { if (value == null) throw new ArgumentNullException(nameof(value)); return new InstantAssertions(value); } } }
using System; using System.Collections.Generic; using Orchard.ContentManagement; using Orchard.Security; using Orchard.Security.Providers; using Orchard.Settings; using Orchard.Users.Models; namespace Orchard.Users.Services { public class PasswordChangedDateUserDataProvider : BaseUserDataProvider { private readonly ISiteService _siteService; public PasswordChangedDateUserDataProvider( ISiteService siteService) : base(true) { // By calling base(true) we set DefaultValid to true. This means that cookies whose // UserData dictionary does not contain the entry from this provider will be valid. _siteService = siteService; } protected override bool DefaultValid { get { return !_siteService .GetSiteSettings() .As<SecuritySettingsPart>() .ShouldInvalidateAuthOnPasswordChanged; } } public override bool IsValid(IUser user, IDictionary<string, string> userData) { return DefaultValid || base.IsValid(user, userData); } protected override string Value(IUser user) { var part = user.As<UserPart>(); if (part == null) { return string.Empty; } var date = GetDate(part); return date.ToString(); } private DateTime GetDate(UserPart part) { // CreatedUTC should never require a default value to fallback to. var created = DateOrDefault(part.CreatedUtc); // LastPasswordChangeUtc may require a value to fallback to for users that have not changed their // password since migration UpdateFrom4() var changed = DateOrDefault(part.LastPasswordChangeUtc); // Return the most recent of the two dates return created > changed ? created : changed; } private DateTime DateOrDefault(DateTime? date) { return date.HasValue ? date.Value : new DateTime(1990, 1, 1);// Just a default value. } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using UniRx; using UnityEngine; using UnityEngine.Networking; using Debug = UnityEngine.Debug; namespace UnityAsyncAwaitUtil { public class UniRxTests : MonoBehaviour { Subject<string> _signal = new Subject<string>(); public void OnGUI() { if (GUI.Button(new Rect(100, 100, 500, 100), "Test UniRx observable")) { RunUniRxTestAsync().WrapErrors(); } if (GUI.Button(new Rect(100, 300, 500, 100), "Trigger UniRx observable")) { _signal.OnNext("zcvd"); } } async Task RunUniRxTestAsync() { Debug.Log("Waiting for UniRx trigger..."); var result = await _signal; Debug.Log("Received UniRx trigger with value: " + result); } } }
/* * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; namespace Tizen.Multimedia { internal static class MultimediaLog { [Conditional("DEBUG")] public static void Debug(string tag, string message, Exception e = null, [CallerFilePath] string file = "", [CallerMemberName] string func = "", [CallerLineNumber] int line = 0) { Log.Debug(tag, BuildMessage(message, e), file, func, line); } public static void Error(string tag, string message, Exception e = null, [CallerFilePath] string file = "", [CallerMemberName] string func = "", [CallerLineNumber] int line = 0) { Log.Error(tag, BuildMessage(message, e), file, func, line); } public static void Fatal(string tag, string message, Exception e = null, [CallerFilePath] string file = "", [CallerMemberName] string func = "", [CallerLineNumber] int line = 0) { Log.Fatal(tag, BuildMessage(message, e), file, func, line); } public static void Info(string tag, string message, Exception e = null, [CallerFilePath] string file = "", [CallerMemberName] string func = "", [CallerLineNumber] int line = 0) { Log.Info(tag, BuildMessage(message, e), file, func, line); } public static void Verbose(string tag, string message, Exception e = null, [CallerFilePath] string file = "", [CallerMemberName] string func = "", [CallerLineNumber] int line = 0) { Log.Verbose(tag, BuildMessage(message, e), file, func, line); } public static void Warn(string tag, string message, Exception e = null, [CallerFilePath] string file = "", [CallerMemberName] string func = "", [CallerLineNumber] int line = 0) { Log.Warn(tag, BuildMessage(message, e), file, func, line); } private static string BuildMessage(string message, Exception exception) { if (exception == null) { return message; } StringBuilder sb = new StringBuilder(); Exception e = exception; while (e != null) { message += e.Message + Environment.NewLine + e.StackTrace; e = e.InnerException; } return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; namespace Revitalize.Framework.Utilities { public class RotationUtilities { public static float get90Degrees() { float angle = (float)Math.PI * .5f; return angle; } public static float get180Degrees() { float angle = (float)Math.PI; return angle; } public static float get270Degrees() { float angle = (float)Math.PI * (1.5f); return angle; } public static float get360Degrees() { return 0; } /// <summary> /// Gets a rotation from the degrees passed in. /// </summary> /// <param name="degrees"></param> /// <returns></returns> public static float getRotationFromDegrees(int degrees) { float amount = degrees / 180; float angle = (float)Math.PI * (amount); return angle; } /// <summary> /// Gets an angle from a passed in vector. /// </summary> /// <param name="vec"></param> /// <returns></returns> public static float getAngleFromVector(Vector2 vec) { Vector2 zero = new Vector2(1,0); vec = vec.UnitVector(); float dot=Vector2.Dot(zero, vec); float len1 = vec.Length(); float len2 = zero.Length(); float lenTotal = len1 * len2; float cosAngle = dot / lenTotal; float angle = (float)((Math.Acos(cosAngle)*180)/Math.PI); return angle; } public static float getRadiansFromVector(Vector2 vec) { Vector2 zero = new Vector2(1, 0); vec = vec.UnitVector(); float dot = Vector2.Dot(zero, vec); float len1 = vec.Length(); float len2 = zero.Length(); float lenTotal = len1 * len2; float cosAngle = dot / lenTotal; float angle = (float)((Math.Acos(cosAngle))); return angle; } /// <summary> /// Gets a rotation amount for xna based off the unit circle. /// </summary> /// <param name="vec"></param> /// <returns></returns> public static float getRotationFromVector(Vector2 vec) { return getRadiansFromVector(vec); } } }
using System; using System.Collections.Generic; using System.Text; using VehicleLoan.BusinessModels; namespace VehicleLoan.DataAccessLayer.Repository.Abstraction { public interface IUserRegistrationDao { int AddRecord(UserRegistrationModel userModel); int UpdateRecord(UserRegistrationModel userModel); int DeleteRecord(string userid); string GetLoginDetails(string userid); } }
@{ ViewBag.Title = "Search"; ViewBag.Word = '"' + ViewBag.Word + '"'; } <h2 style="text-align: center;">Results for word @ViewBag.Word</h2> <div> <h2>Subject results</h2> @foreach (Forum.Models.Subject subject in ViewBag.Subjects) { ViewData["subjectClickable"] = true; <div class="panel panel-default"> @Html.Partial("SubjectInfo", subject, ViewData) </div> <hr /> ViewData["subjectClickable"] = null; } <br /> <hr /> <br /> <h2>Comment results</h2> @foreach (Forum.Models.Comment comment in ViewBag.Comments) { ViewBag.CommentClickable = true; ViewBag.CommentIncludeActions = null; <text> @Html.Partial("CommentInfo", comment) </text> <hr /> } </div>
using Serilog; using System.Configuration; namespace Service.Extensions { public class LogConfigWeb { public static ILogger GetLogger() { Log.Logger = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.File(ConfigurationManager.AppSettings["log"], outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day) .CreateLogger(); return Log.Logger; } } }
using EmsDepRelation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyNewClass.Common { public class ErrorLogHelper { public ErrorLogHelper(string content) { string EmailTitle = string.Empty; string GroupCode = string.Empty; try { EmailTitle = System.Configuration.ConfigurationManager.AppSettings["EmailTitle"].ToString(); GroupCode = System.Configuration.ConfigurationManager.AppSettings["ErrorLogCode"].ToString(); MailHelper helper = new MailHelper(); helper.SendToGroup(GroupCode, EmailTitle, content, true, true); } catch (Exception ex) { Console.WriteLine("提示錯誤(判斷是否存在錯誤,數據是否異常):"); Console.WriteLine("EmailTitle值為:"+EmailTitle); Console.WriteLine("GroupCode值為:" + GroupCode); Console.WriteLine("系統提示錯誤:"); Console.WriteLine(ex); Console.ReadKey(); } } } }
// Copyright(c) 2017 Vertical Software - All rights reserved // // This code file has been made available under the terms of the // MIT license. Please refer to LICENSE.txt in the root directory // or refer to https://opensource.org/licenses/MIT using Vertical.CommandLine.Configuration; using Vertical.CommandLine.Conversion; using Vertical.CommandLine.Mapping; using Vertical.CommandLine.Validation; namespace Vertical.CommandLine.Parsing { /// <summary> /// Defines the interface of a parser builder. /// </summary> /// <typeparam name="TOptions">Options type.</typeparam> /// <typeparam name="TValue">Value type.</typeparam> public interface IParserBuilder<out TOptions, TValue> : IComponentSink<IValueConverter<TValue>>, IComponentSink<IValidator<TValue>>, IComponentSink<IMapper<TOptions, TValue>> where TOptions : class { } }
using TfsDeployer.Data; namespace TfsDeployer.Web.Services { public interface IConfigurationService { string[] GetDeployerInstanceAddress(); IDeployerService CreateDeployerService(int instanceIndex); void SetDeployerInstanceAddress(string deployerServiceUrl); } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Windows; using Archimedes.Patterns.WPF.DragNDrop.Utilities; using System.Windows.Controls; using System.ComponentModel; namespace Archimedes.Patterns.WPF.DragNDrop { class DefaultDropHandler : IDropTarget { public virtual void DragOver(DropInfo dropInfo) { if (CanAcceptData(dropInfo)) { dropInfo.Effects = DragDropEffects.Copy; dropInfo.DropTargetAdorner = DropTargetAdorners.Insert; } } public virtual void Drop(DropInfo dropInfo) { int insertIndex = dropInfo.InsertIndex; IList destinationList = GetList(dropInfo.TargetCollection); IEnumerable data = ExtractData(dropInfo.Data); if (dropInfo.DragInfo.VisualSource == dropInfo.VisualTarget) { IList sourceList = GetList(dropInfo.DragInfo.SourceCollection); foreach (object o in data) { int index = sourceList.IndexOf(o); if (index != -1) { sourceList.RemoveAt(index); if (sourceList == destinationList && index < insertIndex) { --insertIndex; } } } } foreach (object o in data) { destinationList.Insert(insertIndex++, o); } } protected static bool CanAcceptData(DropInfo dropInfo) { if (dropInfo.DragInfo.SourceCollection == dropInfo.TargetCollection) { return GetList(dropInfo.TargetCollection) != null; } else if (dropInfo.DragInfo.SourceCollection is ItemCollection) { return false; } else { if (TestCompatibleTypes(dropInfo.TargetCollection, dropInfo.Data)) { return !IsChildOf(dropInfo.VisualTargetItem, dropInfo.DragInfo.VisualSourceItem); } else { return false; } } } protected static IEnumerable ExtractData(object data) { if (data is IEnumerable && !(data is string)) { return (IEnumerable)data; } else { return Enumerable.Repeat(data, 1); } } protected static IList GetList(IEnumerable enumerable) { if (enumerable is ICollectionView) { return ((ICollectionView)enumerable).SourceCollection as IList; } else { return enumerable as IList; } } protected static bool IsChildOf(UIElement targetItem, UIElement sourceItem) { ItemsControl parent = ItemsControl.ItemsControlFromItemContainer(targetItem); while (parent != null) { if (parent == sourceItem) { return true; } parent = ItemsControl.ItemsControlFromItemContainer(parent); } return false; } protected static bool TestCompatibleTypes(IEnumerable target, object data) { TypeFilter filter = (t, o) => { return (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>)); }; var enumerableInterfaces = target.GetType().FindInterfaces(filter, null); var enumerableTypes = from i in enumerableInterfaces select i.GetGenericArguments().Single(); if (enumerableTypes.Count() > 0) { Type dataType = TypeUtilities.GetCommonBaseClass(ExtractData(data)); return enumerableTypes.Any(t => t.IsAssignableFrom(dataType)); } else { return target is IList; } } } }
namespace ConDep.Dsl { public interface IOfferAwsBootstrapUserDataOptions { IOfferAwsBootstrapOptions PowerShell(string script); IOfferAwsBootstrapOptions RunCmd(string script); } }
using EasyDesk.Tools.Collections; using EasyDesk.Tools.Options; using Microsoft.AspNetCore.Mvc.ModelBinding; using System; using System.Collections.Generic; namespace EasyDesk.CleanArchitecture.Web.ModelBinders; public class TypedModelBinderProvider : IModelBinderProvider { private readonly IDictionary<Type, Func<IModelBinder>> _bindersByType; public TypedModelBinderProvider(IDictionary<Type, Func<IModelBinder>> bindersByType) { _bindersByType = bindersByType; } public IModelBinder GetBinder(ModelBinderProviderContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var modelType = context.Metadata.UnderlyingOrModelType; return _bindersByType .GetOption(modelType) .Map(p => p()) .OrElseDefault(); } }
namespace KnowYourCustomer.Kyc.Data.Contracts.Enumerations { public enum Operation { ProcessPassportMrz = 0, IdentityVerification = 1 } }
using Podler.Models; using Podler.Models.Interfaces; namespace Podler.Responses { public class SelectAddResponse : IResponse { public bool IsSuccess { get; } public string Message { get; } public ISelectableItem Model { get; } public SelectAddResponse(bool isSuccess, string message) { IsSuccess = isSuccess; Message = message; } public SelectAddResponse(bool isSuccess, string menssage, ISelectableItem model) : this(isSuccess, menssage) { Model = model; } } }
using Microsoft.Azure.KeyVault; using Microsoft.Azure.Services.AppAuthentication; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.AzureKeyVault; using Microsoft.Extensions.Hosting; namespace Api.Configuration { public static class AzureKeyVaultConfigHostBuilderExtension { public static IHostBuilder ConfigureAzureKeyVault(this IHostBuilder hostBuilder) { hostBuilder.ConfigureAppConfiguration((context, config) => { if (context.HostingEnvironment.IsProduction()) config.ConfigureProductionAzureKeyVault(); }); return hostBuilder; } private static void ConfigureProductionAzureKeyVault(this IConfigurationBuilder config) { var builtConfig = config.Build(); // Ignore if no Key Vault is configured var keyVault = builtConfig.GetValue<string>("KeyVault"); if (keyVault is null) return; var tokenProvider = new AzureServiceTokenProvider(); var authCallback = new KeyVaultClient.AuthenticationCallback(tokenProvider.KeyVaultTokenCallback); var keyVaultClient = new KeyVaultClient(authCallback); config.AddAzureKeyVault(keyVault, keyVaultClient, new DefaultKeyVaultSecretManager()); } } }
using Shared.RequestResponse; using System; namespace Uniwiki.Shared.RequestResponse { public class EditHomeFacultyRequestDto : RequestBase<EditHomeFacultyResponseDto> { public EditHomeFacultyRequestDto(Guid? facultyId) { FacultyId = facultyId; } public Guid? FacultyId { get; } } }
//----------------------------------------------------------------------------- // <copyright file="UriParserExtenstionEdmModel.cs" company=".NET Foundation"> // Copyright (c) .NET Foundation and Contributors. All rights reserved. // See License.txt in the project root for license information. // </copyright> //------------------------------------------------------------------------------ using Microsoft.OData.Edm; using Microsoft.OData.ModelBuilder; namespace Microsoft.AspNetCore.OData.E2E.Tests.UriParserExtension { public class UriParserExtenstionEdmModel { public static IEdmModel GetEdmModel() { var builder = new ODataConventionModelBuilder(); builder.EntitySet<Customer>("Customers"); builder.EntitySet<Order>("Orders"); builder.EntityType<Customer>().Function("CalculateSalary").Returns<int>().Parameter<int>("month"); builder.EntityType<Customer>().Action("UpdateAddress"); builder.EntityType<Customer>() .Collection.Function("GetCustomerByGender") .ReturnsCollectionFromEntitySet<Customer>("Customers") .Parameter<Gender>("gender"); return builder.GetEdmModel(); } } }
using System; using System.Collections.Generic; namespace _03_Queues { class Program { static void Main(string[] args) { /* * Очередь Queue<T> - коллекция объектов, основанная на принципе "первый поступил -- первым обслужен" * используется, когда необходимо, чтобы приложение выполнялось асинхронно */ Queue<int> integerQueue = new Queue<int>(); integerQueue.Enqueue(1); //добавить элемент в конец очереди integerQueue.Enqueue(2); integerQueue.Enqueue(3); while (true) { if (integerQueue.Count == 0) break; Console.WriteLine(integerQueue.Dequeue()); //Взять значение и удалить элемент из начала очереди Console.WriteLine(integerQueue.Count); //Число элементов в очереди } } } }
using System; using System.Reflection; using System.Reflection.Emit; delegate int Getter(); class Host { static int Field = 42; Getter g; public Host(Getter g) { this.g = g; } ~Host() { int d = g(); Console.WriteLine(d); } } class Program { static Host h; public static int Main() { DynamicMethod method = new DynamicMethod( "GetField", typeof(int), new Type[0], Type.GetType("Host") ); ILGenerator il = method.GetILGenerator(); il.Emit( OpCodes.Ldsfld, typeof(Host).GetField("Field", BindingFlags.Static | BindingFlags.NonPublic) ); il.Emit(OpCodes.Ret); Getter g = (Getter)method.CreateDelegate(typeof(Getter)); /* * Create an object whose finalizer calls a dynamic method which * dies at the same time. * Storing into a static guarantees that this is only finalized during * shutdown. This is needed since the !shutdown case still doesn't * work. */ h = new Host(g); return 0; } }
 #region Copyright (C) 2017 Kevin (OSS开源作坊) 公众号:osscore /*************************************************************************** *   文件功能描述:公号的功能接口 —— 消息统计接口实体 * *   创建人: Kevin * 创建人Email:1985088337@qq.com * 创建日期:2017-1-19 * *****************************************************************************/ #endregion using System; using System.Collections.Generic; namespace OSS.SocialSDK.WX.Offcial.Statistic.Mos { /// <summary> /// 微信统计消息基类 /// </summary> public class WXChatStatBaseMo { /// <summary> /// 数据的日期,需在begin_date和end_date之间 /// </summary> public DateTime ref_date { get; set; } /// <summary> /// 上行发送了(向公众号发送了)消息的用户数 /// </summary> public int msg_user { get; set; } } /// <summary> /// 消息统计实体 /// </summary> public class WXChatUpStatMo: WXChatStatBaseMo { /// <summary> /// 消息类型,代表含义如下:1代表文字2代表图片3代表语音4代表视频6代表第三方应用消息(链接消息) /// </summary> public int msg_type { get; set; } /// <summary> /// 上行发送了消息的消息总数 /// </summary> public int msg_count { get; set; } } /// <summary> /// 消息时分统计实体 /// </summary> public class WXChatUpStatHourMo: WXChatUpStatMo { /// <summary> /// 数据的小时,包括从000到2300,分别代表的是[000,100)到[2300,2400),即每日的第1小时和最后1小时 /// </summary> public int ref_hour { get; set; } } /// <summary> /// 消息分布统计实体 /// </summary> public class WXChatUpStatDistMo : WXChatStatBaseMo { /// <summary> /// 当日发送消息量分布的区间,0代表“0”,1代表“1-5”,2代表“6-10”,3代表“10次以上” /// </summary> public int count_interval { get; set; } } }
// 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. namespace System { public class HttpStyleUriParser: UriParser { public HttpStyleUriParser():base(UriParser.HttpUri.Flags) { } } public class FtpStyleUriParser: UriParser { public FtpStyleUriParser():base(UriParser.FtpUri.Flags) { } } public class FileStyleUriParser: UriParser { public FileStyleUriParser():base(UriParser.FileUri.Flags) { } } public class NewsStyleUriParser: UriParser { public NewsStyleUriParser():base(UriParser.NewsUri.Flags) { } } public class GopherStyleUriParser: UriParser { public GopherStyleUriParser():base(UriParser.GopherUri.Flags) { } } public class LdapStyleUriParser: UriParser { public LdapStyleUriParser():base(UriParser.LdapUri.Flags) { } } public class NetPipeStyleUriParser: UriParser { public NetPipeStyleUriParser():base(UriParser.NetPipeUri.Flags) { } } public class NetTcpStyleUriParser: UriParser { public NetTcpStyleUriParser():base(UriParser.NetTcpUri.Flags) { } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Diagnostics; using System.Xml.XPath; using System.Xml; using System.IO; using DigitalPlatform; //using DigitalPlatform.XmlEditor; using DigitalPlatform.GUI; using DigitalPlatform.IO; using DigitalPlatform.Xml; using DigitalPlatform.rms; using DigitalPlatform.rms.Client; using DigitalPlatform.Text; using DigitalPlatform.Core; namespace dp2rms { public class ResFileList : ListViewNF { public XmlEditor editor = null; // 本对象所关联的XmlEditor public const int COLUMN_ID = 0; public const int COLUMN_STATE = 1; public const int COLUMN_LOCALPATH = 2; public const int COLUMN_SIZE = 3; public const int COLUMN_MIME = 4; public const int COLUMN_TIMESTAMP = 5; bool bNotAskTimestampMismatchWhenOverwrite = false; public Delegate_DownloadFiles procDownloadFiles = null; public Delegate_DownloadOneMetaData procDownloadOneMetaData = null; Hashtable m_tableFileId = new Hashtable(); bool m_bChanged = false; private System.Windows.Forms.ColumnHeader columnHeader_state; private System.Windows.Forms.ColumnHeader columnHeader_serverName; private System.Windows.Forms.ColumnHeader columnHeader_localPath; private System.Windows.Forms.ColumnHeader columnHeader_size; private System.Windows.Forms.ColumnHeader columnHeader_mime; private System.Windows.Forms.ColumnHeader columnHeader_timestamp; private System.ComponentModel.Container components = null; public ResFileList() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // TODO: Add any initialization after the InitComponent call } protected override void Dispose( bool disposing ) { if( disposing ) { if( components != null ) components.Dispose(); } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.columnHeader_state = new System.Windows.Forms.ColumnHeader(); this.columnHeader_serverName = new System.Windows.Forms.ColumnHeader(); this.columnHeader_localPath = new System.Windows.Forms.ColumnHeader(); this.columnHeader_size = new System.Windows.Forms.ColumnHeader(); this.columnHeader_mime = new System.Windows.Forms.ColumnHeader(); this.columnHeader_timestamp = new System.Windows.Forms.ColumnHeader(); // // columnHeader_state // this.columnHeader_state.Text = "状态"; this.columnHeader_state.Width = 100; // // columnHeader_serverName // this.columnHeader_serverName.Text = "服务器端别名"; this.columnHeader_serverName.Width = 200; // // columnHeader_localPath // this.columnHeader_localPath.Text = "本地物理路径"; this.columnHeader_localPath.Width = 200; // // columnHeader_size // this.columnHeader_size.Text = "尺寸"; this.columnHeader_size.Width = 100; // // columnHeader_mime // this.columnHeader_mime.Text = "媒体类型"; this.columnHeader_mime.Width = 200; // // columnHeader_timestamp // this.columnHeader_timestamp.Text = "时间戳"; this.columnHeader_timestamp.Width = 200; // // ResFileList // this.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader_serverName, this.columnHeader_state, this.columnHeader_localPath, this.columnHeader_size, this.columnHeader_mime, this.columnHeader_timestamp}); this.FullRowSelect = true; this.HideSelection = false; this.View = System.Windows.Forms.View.Details; this.DoubleClick += new System.EventHandler(this.ResFileList_DoubleClick); this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.ResFileList_MouseUp); } #endregion public bool Changed { get { return m_bChanged; } set { m_bChanged = value; } } // 初始化列表内容 // parameters: public void Initial(XmlEditor editor) { //this.Items.Clear(); m_tableFileId.Clear(); this.editor = editor; this.editor.ItemCreated -= new ItemCreatedEventHandle(this.ItemCreated); this.editor.ItemChanged -= new ItemChangedEventHandle(this.ItemChanged); this.editor.BeforeItemCreate -= new BeforeItemCreateEventHandle(this.BeforeItemCreate); this.editor.ItemDeleted -= new ItemDeletedEventHandle(this.ItemDeleted); this.editor.ItemCreated += new ItemCreatedEventHandle(this.ItemCreated); this.editor.ItemChanged += new ItemChangedEventHandle(this.ItemChanged); this.editor.BeforeItemCreate += new BeforeItemCreateEventHandle(this.BeforeItemCreate); this.editor.ItemDeleted += new ItemDeletedEventHandle(this.ItemDeleted); } #region 接管的事件 bool IsFileElement(DigitalPlatform.Xml.Item item) { if (!(item is ElementItem)) return false; ElementItem element = (ElementItem)item; if (element.LocalName != "file") return false; if (element.NamespaceURI == DpNs.dprms ) return true; return false; } // 接管XmlEditor中各种渠道创建<file>对象的事件 void BeforeItemCreate(object sender, DigitalPlatform.Xml.BeforeItemCreateEventArgs e) { /* if (!(e.item is ElementItem)) return; if (IsFileElement(e.item) == false) return; ResObjectDlg dlg = new ResObjectDlg(); dlg.ShowDialog(this); if (dlg.DialogResult != DialogResult.OK) { e.Cancel = true; return; } SetItemProperty(editor, (ElementItem)e.item, dlg.textBox_mime.Text, dlg.textBox_localPath.Text, dlg.textBox_size.Text); return; */ } void ItemCreated(object sender, DigitalPlatform.Xml.ItemCreatedEventArgs e) { if (e.item is AttrItem) { ElementItem parent = e.item.parent; if (parent == null) return; if (this.IsFileElement(parent) == false) return; /* string strId = parent.GetAttrValue("id"); if (strId == null || strId == "") return; */ if (e.item.Name == "id") { ChangeFileAttr((AttrItem)e.item, "", e.item.Value); } else { ChangeFileAttr((AttrItem)e.item, null, e.item.Value); } return; } if (!(e.item is ElementItem)) return; if (IsFileElement(e.item) == false) return; ElementItem element = (ElementItem)e.item; // 看看创建时是否已经有id属性 string strID = element.GetAttrValue("id"); // 客户端 if (strID == null || strID == "") { NewLine(element, true); ResObjectDlg dlg = new ResObjectDlg(); dlg.Font = GuiUtil.GetDefaultFont(); dlg.ShowDialog(this); if (dlg.DialogResult != DialogResult.OK) { // e.Cancel = true; // 删除刚刚创建的element ElementItem parent = element.parent; parent.Remove(element); return; } // 直接对xmleditor进行修改 element.SetAttrValue("__mime",dlg.textBox_mime.Text); element.SetAttrValue("__localpath",dlg.textBox_localPath.Text); element.SetAttrValue("__size",dlg.textBox_size.Text); strID = NewFileId(); // 用到了id if (m_tableFileId.Contains((object)strID) == false) m_tableFileId.Add(strID, (object)true); element.SetAttrValue("id", strID); /* SetItemProperty(editor, (ElementItem)e.item, dlg.textBox_mime.Text, dlg.textBox_localPath.Text, dlg.textBox_size.Text); NewLine((ElementItem)e.item, true); */ } else // 来自服务器端的 { string strState = element.GetAttrValue("__state"); if (strState == null || strState == "") { NewLine(element, false); GetMetaDataParam(element); } else { NewLine(element, IsNewFileState(strState)); // 跟踪全部xml属性 ChangeLine(strID, null, // newid element.GetAttrValue("__state"), element.GetAttrValue("__localpath"), element.GetAttrValue("__mime"), element.GetAttrValue("__size"), element.GetAttrValue("__timestamp")); } } } void ItemDeleted(object sender, DigitalPlatform.Xml.ItemDeletedEventArgs e) { if (!(e.item is ElementItem)) return; e.RecursiveChildEvents = true; e.RiseAttrsEvents = true; // e.item中还残存原有的id if (IsFileElement(e.item) == false) return; string strID = ((ElementItem)e.item).GetAttrValue("id"); // m_tableFileId.Remove((object)strID); // 此句可以造成删除后的id重复使用的效果 DeleteLineById(strID); } void ItemChanged(object sender, DigitalPlatform.Xml.ItemChangedEventArgs e) { if (!(e.item is AttrItem)) return; // 只关心属性改变 ElementItem parent = (ElementItem)e.item.parent; if (parent == null) { // 节点尚未插入 return; } // e.item已经是一个属性结点 ChangeFileAttr((AttrItem)e.item, e.OldValue, e.NewValue); } void ChangeFileAttr(AttrItem attr, string strOldValue, string strNewValue) { ElementItem parent = attr.parent; string strID = parent.GetAttrValue("id"); if (strID == null) strID = ""; if (attr.Name == "id") { ChangeLine(strOldValue, strNewValue, null, null, null, null, null); } else if (attr.Name == "__mime") { ChangeLine(strID, null, null, null, strNewValue, null, null); } else if (attr.Name == "__localpath") { ChangeLine(strID, null, null, strNewValue, null, null, null); } else if (attr.Name == "__state") { ChangeLine(strID, null, strNewValue, null, null, null, null); } else if (attr.Name == "__size") { ChangeLine(strID, null, null, null, null, strNewValue, null); } else if (attr.Name == "__timestamp") { ChangeLine(strID, null, null, null, null, null, strNewValue); } } #endregion // 从列表中检索一行是否存在 public ListViewItem SearchLine(string strID) { for(int i=0;i<this.Items.Count;i++) { if (ListViewUtil.GetItemText(this.Items[i], COLUMN_ID) == strID) { return this.Items[i]; } } return null; } // ? // 在listview加一行,如果此行已存在,则修改其内容 public void NewLine(DigitalPlatform.Xml.ElementItem fileitem, bool bIsNewFile) { string strID = fileitem.GetAttrValue("id"); if (strID == null || strID == "") { Debug.Assert(bIsNewFile == true, "必须是客户端文件才能无id属性"); } string strState; if (bIsNewFile == false) strState = this.ServerFileState; else strState = this.NewFileState; // 维护id表 if (strID != null && strID != "") { if (m_tableFileId.Contains((object)strID) == false) m_tableFileId.Add(strID, (object)true); } ListViewItem item = SearchLine(strID); if (item == null) { item = new ListViewItem(strID, 0); this.Items.Add(item); item.SubItems.Add(""); item.SubItems.Add(""); item.SubItems.Add(""); item.SubItems.Add(""); item.SubItems.Add(""); m_bChanged = true; } else { // 2006/6/22 // 重复插入. // 插入在已经发现的事项前面 int index = this.Items.IndexOf(item); item = new ListViewItem(strID, 0); this.Items.Insert(index, item); item.SubItems.Add(""); item.SubItems.Add(""); item.SubItems.Add(""); item.SubItems.Add(""); item.SubItems.Add(""); m_bChanged = true; } string strOldState = fileitem.GetAttrValue("__state"); if (strOldState != strState) fileitem.SetAttrValue("__state", strState); } // 从服务器获得元数据 public void GetMetaDataParam(DigitalPlatform.Xml.ElementItem element) { string strID = element.GetAttrValue("id"); if (strID == null || strID == "") { Debug.Assert(false); } // 如果没有挂回调函数,警告 if (this.procDownloadOneMetaData == null) { element.SetAttrValue("__mime", "?mime"); element.SetAttrValue("__localpath", "?localpath"); element.SetAttrValue("__size", "?size"); element.SetAttrValue("__timestamp", "?timestamp"); m_bChanged = true; } else { string strExistTimeStamp = element.GetAttrValue("__timestamp"); if (strExistTimeStamp != null && strExistTimeStamp != "") { ChangeLine(strID, null, // newid null, // state element.GetAttrValue("__localpath"), element.GetAttrValue("__mime"), element.GetAttrValue("__size"), element.GetAttrValue("__timestamp") ); return; } m_bChanged = true; string strMetaData = ""; string strError = ""; byte [] timestamp = null; int nRet = this.procDownloadOneMetaData( strID, out strMetaData, out timestamp, out strError); if (nRet == -1) { element.SetAttrValue("__localpath", strError); return; } if (strMetaData == "") { return; } // 取metadata Hashtable values = StringUtil.ParseMetaDataXml(strMetaData, out strError); if (values == null) { element.SetAttrValue("__localpath", strError); return; } string strTimeStamp = ByteArray.GetHexTimeStampString(timestamp); element.SetAttrValue("__mime", (string)values["mimetype"]); element.SetAttrValue("__localpath", (string)values["localpath"]); element.SetAttrValue("__size", (string)values["size"]); element.SetAttrValue("__timestamp", (string)strTimeStamp); } } // 删除一行(暂时无用) void DeleteLineById(string strId) { bool bFound = false; // 1.先根据传来的id删除相关行 for(int i=0;i<this.Items.Count;i++) { if (ListViewUtil.GetItemText(this.Items[i], COLUMN_ID) == strId) { this.Items.RemoveAt(i); bFound = true; m_bChanged = true; break; } } if (bFound == false) { Debug.Assert(false, "id[" + strId + "]在listview中没有找到..."); } } // 跟随事件,修改listview一行 void ChangeLine(string strID, string strNewID, string strState, string strLocalPath, string strMime, string strSize, string strTimestamp) { for(int i=0;i<this.Items.Count;i++) { if (ListViewUtil.GetItemText(this.Items[i], COLUMN_ID) == strID) { if (strNewID != null) ListViewUtil.ChangeItemText(this.Items[i], COLUMN_ID, strNewID); if (strState != null) ListViewUtil.ChangeItemText(this.Items[i], COLUMN_STATE, strState); if (strLocalPath != null) ListViewUtil.ChangeItemText(this.Items[i], COLUMN_LOCALPATH, strLocalPath); if (strMime != null) ListViewUtil.ChangeItemText(this.Items[i], COLUMN_MIME, strMime); if (strSize != null) ListViewUtil.ChangeItemText(this.Items[i], COLUMN_SIZE, strSize); if (strTimestamp != null) ListViewUtil.ChangeItemText(this.Items[i], COLUMN_TIMESTAMP, strTimestamp); m_bChanged = true; break; } } } private void ResFileList_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { if(e.Button != MouseButtons.Right) return; ContextMenu contextMenu = new ContextMenu(); MenuItem menuItem = null; bool bSelected = this.SelectedItems.Count > 0; // menuItem = new MenuItem("修改(&M)"); menuItem.Click += new System.EventHandler(this.button_modifyFile_Click); if (bSelected == false) { menuItem.Enabled = false; } contextMenu.MenuItems.Add(menuItem); // --- menuItem = new MenuItem("-"); contextMenu.MenuItems.Add(menuItem); menuItem = new MenuItem("删除(&D)"); menuItem.Click += new System.EventHandler(this.DeleteLines_Click); if (bSelected == false) menuItem.Enabled = false; contextMenu.MenuItems.Add(menuItem); // --- menuItem = new MenuItem("-"); contextMenu.MenuItems.Add(menuItem); // menuItem = new MenuItem("新增(&N)"); menuItem.Click += new System.EventHandler(this.NewLine_Click); contextMenu.MenuItems.Add(menuItem); // --- menuItem = new MenuItem("-"); contextMenu.MenuItems.Add(menuItem); // menuItem = new MenuItem("下载(&D)"); menuItem.Click += new System.EventHandler(this.DownloadLine_Click); bool bFound = false; if (bSelected == true) { for(int i=0;i<this.SelectedItems.Count;i++) { if (IsNewFileState(ListViewUtil.GetItemText(this.SelectedItems[i], COLUMN_STATE) ) == false) { bFound = true; break; } } } if (bFound == false || procDownloadFiles == null) menuItem.Enabled = false; contextMenu.MenuItems.Add(menuItem); /* menuItem = new MenuItem("测试"); menuItem.Click += new System.EventHandler(this.Test_click); contextMenu.MenuItems.Add(menuItem); */ contextMenu.Show(this, new Point(e.X, e.Y) ); } public void Test_click(object sender, System.EventArgs e) { XmlNamespaceManager mngr = new XmlNamespaceManager(new NameTable()); mngr.AddNamespace("dprms", DpNs.dprms); ItemList fileItems = this.editor.VirtualRoot.SelectItems("//dprms:file", mngr); MessageBox.Show("选中" + Convert.ToString(fileItems.Count) + "个"); } DigitalPlatform.Xml.ElementItem GetFileItem(string strID) { XmlNamespaceManager mngr = new XmlNamespaceManager(new NameTable()); mngr.AddNamespace("dprms", DpNs.dprms); //StreamUtil.WriteText("I:\\debug.txt","dprms的值:'" + DpNs.dprms + "'\r\n"); //mngr.AddNamespace("abc","http://purl.org/dc/elements/1.1/"); ItemList items = this.editor.VirtualRoot.SelectItems("//dprms:file[@id='" + strID + "']", mngr); if (items.Count == 0) return null; return (ElementItem)items[0]; } // 菜单:删除一行或者多行 void DeleteLines_Click(object sender, System.EventArgs e) { if (this.SelectedItems.Count == 0) { MessageBox.Show(this, "尚未选择要删除的行..."); return; } string[] ids = new string[this.SelectedItems.Count]; for(int i=0;i<ids.Length;i++) { ids[i] = this.SelectedItems[i].Text; } for(int i=0;i<ids.Length;i++) { /* XmlNamespaceManager mngr = new XmlNamespaceManager(new NameTable()); mngr.AddNamespace("dprms", DpNs.dprms); ItemList items = this.editor.SelectItems("//dprms:file[@id='" + ids[i]+ "']", mngr); if (items.Count == 0) { MessageBox.Show(this, "警告: id为[" +ids[i]+ "]的<dprms:file>元素在editor中不存在..."); } else { this.editor.Remove(items[0]); // 自然会触发事件,更新listview } */ DigitalPlatform.Xml.Item item = GetFileItem(ids[i]); if (item == null) { MessageBox.Show(this, "警告: id为[" +ids[i]+ "]的<dprms:file>元素在editor中不存在..."); continue; } ElementItem parent = item.parent; parent.Remove(item); // 自然会触发事件,更新listview m_bChanged = true; } } // 菜单:修改一行 void button_modifyFile_Click(object sender, System.EventArgs e) { if (this.SelectedItems.Count == 0) { MessageBox.Show(this, "尚未选择要修改的行..."); return ; } ResObjectDlg dlg = new ResObjectDlg(); dlg.Font = GuiUtil.GetDefaultFont(); dlg.textBox_serverName.Text = ListViewUtil.GetItemText(this.SelectedItems[0], COLUMN_ID); dlg.textBox_state.Text = ListViewUtil.GetItemText(this.SelectedItems[0], COLUMN_STATE); dlg.textBox_mime.Text = ListViewUtil.GetItemText(this.SelectedItems[0], COLUMN_MIME); dlg.textBox_localPath.Text = ListViewUtil.GetItemText(this.SelectedItems[0], COLUMN_LOCALPATH); dlg.textBox_size.Text = ListViewUtil.GetItemText(this.SelectedItems[0], COLUMN_SIZE); dlg.textBox_timestamp.Text = ListViewUtil.GetItemText(this.SelectedItems[0], COLUMN_TIMESTAMP); dlg.ShowDialog(this); if (dlg.DialogResult != DialogResult.OK) return; Cursor cursorSave = Cursor; Cursor = Cursors.WaitCursor; this.Enabled = false; DigitalPlatform.Xml.ElementItem item = GetFileItem(dlg.textBox_serverName.Text); if (item != null) { item.SetAttrValue("__mime", dlg.textBox_mime.Text); item.SetAttrValue("__localpath", dlg.textBox_localPath.Text); item.SetAttrValue("__state", this.NewFileState); item.SetAttrValue("__size", dlg.textBox_size.Text); item.SetAttrValue("__timestamp", dlg.textBox_timestamp.Text); m_bChanged = true; } else { Debug.Assert(false, "xmleditor中居然不存在id为[" + dlg.textBox_serverName.Text + "]的<dprms:file>元素"); } this.Enabled = true; Cursor = cursorSave; } // 菜单:下载一行或多行 void DownloadLine_Click(object sender, System.EventArgs e) { bool bFound = false; for(int i=0;i<this.SelectedItems.Count;i++) { if (IsNewFileState(ListViewUtil.GetItemText(this.SelectedItems[i], COLUMN_STATE)) == false) { bFound = true; } } if (bFound == false) { MessageBox.Show(this, "尚未选择要下载的事项,或者所选择的事项中没有状态为'已上载'的事项..."); return; } if (procDownloadFiles == null) { MessageBox.Show(this, "procDownloadFiles尚未设置..."); return; } procDownloadFiles(); } // 菜单:新增一行 void NewLine_Click(object sender, System.EventArgs e) { /* ResObjectDlg dlg = new ResObjectDlg(); dlg.ShowDialog(this); if (dlg.DialogResult != DialogResult.OK) return; */ DigitalPlatform.Xml.ElementItem fileitem = null; fileitem = CreateFileElementItem(editor); // string strError; try { editor.DocumentElement.AutoAppendChild(fileitem); } catch (Exception ex) { MessageBox.Show(ex.Message); } /* fileitem.SetAttrValue("__mime", dlg.textBox_mime.Text); fileitem.SetAttrValue("__localpath", dlg.textBox_localPath.Text); fileitem.SetAttrValue("__size", dlg.textBox_size.Text); */ m_bChanged = true; // -2为用户取消的状态 } // 创建资源节点函数 static ElementItem CreateFileElementItem(XmlEditor editor) { ElementItem item = editor.CreateElementItem("dprms", "file", DpNs.dprms); return item; } string NewFileId() { int nSeed = 0; string strID = ""; for(;;) { strID = Convert.ToString(nSeed++); if (m_tableFileId.Contains((object)strID) == false) return strID; } } /* // 设置<file>元素特有的特性 // 在新建元素的时候调此函数 void SetItemProperty(XmlEditor editor, DigitalPlatform.Xml.ElementItem item, string strMime, string strLocalPath, string strSize) { AttrItem attr = null; // id属性 attr = editor.CreateAttrItem("id"); attr.Value = NewFileId(); // editor.GetFileNo(null); item.AppendAttr(attr); // 加__mime属性 attr = editor.CreateAttrItem("__mime"); attr.Value = strMime; item.AppendAttr(attr); // 加__localpath属性 attr = editor.CreateAttrItem("__localpath"); attr.Value = strLocalPath; item.AppendAttr (attr); // __size属性 attr = editor.CreateAttrItem("__size"); attr.Value = strSize; item.AppendAttr(attr); // __state属性 attr = editor.CreateAttrItem("__state"); attr.Name = "__state"; attr.Value = this.NewFileState; item.AppendAttr(attr); // 这个属性在对应的资源上载完后要改过来 m_bChanged = true; } */ #if NO public static void ChangeMetaData(ref string strMetaData, string strID, string strLocalPath, string strMimeType, string strLastModified, string strPath, string strTimestamp) { XmlDocument dom = new XmlDocument(); if (strMetaData == "") strMetaData = "<file/>"; dom.LoadXml(strMetaData); if (strID != null) DomUtil.SetAttr(dom.DocumentElement, "id", strID); if (strLocalPath != null) DomUtil.SetAttr(dom.DocumentElement, "localpath", strLocalPath); if (strMimeType != null) DomUtil.SetAttr(dom.DocumentElement, "mimetype", strMimeType); if (strLastModified != null) DomUtil.SetAttr(dom.DocumentElement, "lastmodified", strLastModified); if (strPath != null) DomUtil.SetAttr(dom.DocumentElement, "path", strPath); if (strTimestamp != null) DomUtil.SetAttr(dom.DocumentElement, "timestamp", strTimestamp); strMetaData = dom.OuterXml; } #endif // 从窗口中查得localpath public string GetLocalFileName(string strID) { for(int i=0;i<this.Items.Count;i++) { string strCurID = ListViewUtil.GetItemText(this.Items[i], COLUMN_ID); string strLocalFileName = ListViewUtil.GetItemText(this.Items[i], COLUMN_LOCALPATH); if (strID == strCurID) return strLocalFileName; } return ""; } // 下载资源,保存到备份文件 public int DoSaveResToBackupFile( Stream outputfile, string strXmlRecPath, RmsChannel channel, DigitalPlatform.Stop stop, out string strError) { strError = ""; string strTempFileName = Path.GetTempFileName(); try { long lRet; for(int i=0;i<this.Items.Count;i++) { string strState = ListViewUtil.GetItemText(this.Items[i], COLUMN_STATE); string strID = ListViewUtil.GetItemText(this.Items[i], COLUMN_ID); string strResPath = strXmlRecPath + "/object/" + ListViewUtil.GetItemText(this.Items[i], COLUMN_ID); string strLocalFileName = ListViewUtil.GetItemText(this.Items[i], COLUMN_LOCALPATH); string strMime = ListViewUtil.GetItemText(this.Items[i], COLUMN_MIME); string strMetaData; // 服务器端文件 if (IsNewFileState(strState) == false) { if (stop != null) stop.SetMessage("正在下载 " + strResPath); byte [] baOutputTimeStamp = null; string strOutputPath; lRet = channel.GetRes(strResPath, strTempFileName, stop, out strMetaData, out baOutputTimeStamp, out strOutputPath, out strError); if (lRet == -1) return -1; ResPath respath = new ResPath(); respath.Url = channel.Url; respath.Path = strResPath; // strMetaData还要加入资源id? StringUtil.ChangeMetaData(ref strMetaData, strID, null, null, null, respath.FullPath, ByteArray.GetHexTimeStampString(baOutputTimeStamp)); lRet = Backup.WriteOtherResToBackupFile(outputfile, strMetaData, strTempFileName); } else // 本地新文件 { if (stop != null) stop.SetMessage("正在复制 " + strLocalFileName); // strMetaData = "<file mimetype='"+ strMime+"' localpath='"+strLocalPath+"' id='"+strID+"'></file>"; ResPath respath = new ResPath(); respath.Url = channel.Url; respath.Path = strResPath; strMetaData = ""; FileInfo fi = new FileInfo(strLocalFileName); StringUtil.ChangeMetaData(ref strMetaData, strID, strLocalFileName, strMime, fi.LastWriteTimeUtc.ToString(), respath.FullPath, ""); lRet = Backup.WriteOtherResToBackupFile(outputfile, strMetaData, strLocalFileName); } } if (stop != null) stop.SetMessage("保存资源到备份文件全部完成"); } finally { if (strTempFileName != "") File.Delete(strTempFileName); } return 0; } // 上载资源 // return: // -1 error // >=0 实际上载的资源对象数 public int DoUpload( string strXmlRecPath, RmsChannel channel, DigitalPlatform.Stop stop, out string strError) { strError = ""; int nUploadCount = 0; string strLastModifyTime = DateTime.UtcNow.ToString("u"); bNotAskTimestampMismatchWhenOverwrite = false; for(int i=0;i<this.Items.Count;i++) { string strState = ListViewUtil.GetItemText(this.Items[i], COLUMN_STATE); string strID = ListViewUtil.GetItemText(this.Items[i], COLUMN_ID); string strResPath = strXmlRecPath + "/object/" + ListViewUtil.GetItemText(this.Items[i], COLUMN_ID); string strLocalFileName = ListViewUtil.GetItemText(this.Items[i], COLUMN_LOCALPATH); string strMime = ListViewUtil.GetItemText(this.Items[i], COLUMN_MIME); string strTimeStamp = ListViewUtil.GetItemText(this.Items[i], COLUMN_TIMESTAMP); if (IsNewFileState(strState) == false) continue; // 检测文件尺寸 FileInfo fi = new FileInfo(strLocalFileName); if (fi.Exists == false) { strError = "文件 '" + strLocalFileName + "' 不存在..."; return -1; } string[] ranges = null; if (fi.Length == 0) { // 空文件 ranges = new string[1]; ranges[0] = ""; } else { string strRange = ""; strRange = "0-" + Convert.ToString(fi.Length-1); // 按照100K作为一个chunk ranges = RangeList.ChunkRange(strRange, 100 * 1024 ); } byte [] timestamp = ByteArray.GetTimeStampByteArray(strTimeStamp); byte [] output_timestamp = null; nUploadCount ++; REDOWHOLESAVE: string strWarning = ""; for(int j=0;j<ranges.Length;j++) { REDOSINGLESAVE: Application.DoEvents(); // 出让界面控制权 if (stop.State != 0) { strError = "用户中断"; goto ERROR1; } string strWaiting = ""; if (j == ranges.Length - 1) strWaiting = " 请耐心等待..."; string strPercent = ""; RangeList rl = new RangeList(ranges[j]); if (rl.Count >= 1) { double ratio = (double)(rl[0]).lStart / (double)fi.Length; strPercent = String.Format("{0,3:N}",ratio * (double)100) + "%"; } if (stop != null) stop.SetMessage("正在上载 " + ranges[j] + "/" + Convert.ToString(fi.Length) + " " + strPercent + " " + strLocalFileName + strWarning + strWaiting); /* if (stop != null) stop.SetMessage("正在上载 " + ranges[j] + "/" + Convert.ToString(fi.Length) + " " + strLocalFileName); */ long lRet = channel.DoSaveResObject(strResPath, strLocalFileName, strLocalFileName, strMime, strLastModifyTime, ranges[j], j == ranges.Length - 1 ? true : false, // 最尾一次操作,提醒底层注意设置特殊的WebService API超时时间 timestamp, out output_timestamp, out strError); timestamp = output_timestamp; ListViewUtil.ChangeItemText(this.Items[i], COLUMN_TIMESTAMP, ByteArray.GetHexTimeStampString(timestamp)); strWarning = ""; if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (this.bNotAskTimestampMismatchWhenOverwrite == true) { timestamp = new byte[output_timestamp.Length]; Array.Copy(output_timestamp, 0, timestamp, 0, output_timestamp.Length); strWarning = " (时间戳不匹配, 自动重试)"; if (ranges.Length == 1 || j==0) goto REDOSINGLESAVE; goto REDOWHOLESAVE; } DialogResult result = MessageDlg.Show(this, "上载 '" + strLocalFileName + "' (片断:" + ranges[j] + "/总尺寸:"+Convert.ToString(fi.Length) +") 时发现时间戳不匹配。详细情况如下:\r\n---\r\n" + strError + "\r\n---\r\n\r\n是否以新时间戳强行上载?\r\n注:(是)强行上载 (否)忽略当前记录或资源上载,但继续后面的处理 (取消)中断整个批处理", "dp2batch", MessageBoxButtons.YesNoCancel, MessageBoxDefaultButton.Button1, ref this.bNotAskTimestampMismatchWhenOverwrite); if (result == DialogResult.Yes) { timestamp = new byte[output_timestamp.Length]; Array.Copy(output_timestamp, 0, timestamp, 0, output_timestamp.Length); strWarning = " (时间戳不匹配, 应用户要求重试)"; if (ranges.Length == 1 || j==0) goto REDOSINGLESAVE; goto REDOWHOLESAVE; } if (result == DialogResult.No) { goto END1; // 继续作后面的资源 } if (result == DialogResult.Cancel) { strError = "用户中断"; goto ERROR1; // 中断整个处理 } } goto ERROR1; } //timestamp = output_timestamp; } DigitalPlatform.Xml.ElementItem item = GetFileItem(strID); if (item != null) { item.SetAttrValue("__state", this.ServerFileState); } else { Debug.Assert(false, "xmleditor中居然不存在id为[" + strID + "]的<dprms:file>元素"); } } END1: if (stop != null) stop.SetMessage("上载资源全部完成"); return nUploadCount; ERROR1: return -1; } // 获得当前所选择的可以用于下载的全部id public string[] GetSelectedDownloadIds() { ArrayList aText = new ArrayList(); int i=0; for(i=0;i<this.SelectedItems.Count;i++) { if (IsNewFileState(ListViewUtil.GetItemText(this.SelectedItems[i], COLUMN_STATE)) == false) { aText.Add(ListViewUtil.GetItemText(this.SelectedItems[i], COLUMN_ID)); } } string[] result = new string[aText.Count]; for(i=0;i<aText.Count;i++) { result[i] = (string)aText[i]; } return result; } // 从XML数据中移除工作用的临时属性 // parameters: // bHasUploadedFile 是否含有已上载资源的<file>元素? public static int RemoveWorkingAttrs(string strXml, out string strResultXml, out bool bHasUploadedFile, out string strError) { bHasUploadedFile = false; strResultXml = strXml; strError = ""; XmlDocument dom = new XmlDocument(); try { dom.LoadXml(strXml); } catch (Exception ex) { strError = ExceptionUtil.GetAutoText(ex); return -1; } XmlNamespaceManager mngr = new XmlNamespaceManager(dom.NameTable); mngr.AddNamespace("dprms", DpNs.dprms); XmlNodeList nodes = dom.DocumentElement.SelectNodes("//dprms:file", mngr); for(int i=0; i<nodes.Count; i++) { XmlNode node = nodes[i]; string strState = DomUtil.GetAttr(node, "__state"); if (IsNewFileState(strState) == false) bHasUploadedFile = true; DomUtil.SetAttr(node, "__mime", null); DomUtil.SetAttr(node, "__localpath", null); DomUtil.SetAttr(node, "__state", null); DomUtil.SetAttr(node, "__size", null); DomUtil.SetAttr(node, "__timestamp", null); } strResultXml = dom.OuterXml; // ?? return 0; } #if NO // 得到Xml记录中所有<file>元素的id属性值 public static int GetFileIds(string strXml, out string[] ids, out string strError) { ids = null; strError = ""; XmlDocument dom = new XmlDocument(); try { dom.LoadXml(strXml); } catch (Exception ex) { strError = "装载 XML 进入 DOM 时出错: " + ex.Message; return -1; } XmlNamespaceManager mngr = new XmlNamespaceManager(dom.NameTable); mngr.AddNamespace("dprms", DpNs.dprms); XmlNodeList nodes = dom.DocumentElement.SelectNodes("//dprms:file", mngr); ids = new string[nodes.Count]; for(int i=0; i<nodes.Count; i++) { XmlNode node = nodes[i]; ids[i] = DomUtil.GetAttr(node, "id"); } return 0; } #endif static bool IsNewFileState(string strState) { if (String.IsNullOrEmpty(strState) == true) return false; if (strState == "已上载") return false; if (strState == "尚未上载") return true; // Debug.Assert(false, "未定义的状态"); return false; } private void ResFileList_DoubleClick(object sender, System.EventArgs e) { if (this.SelectedItems.Count == 0) return; button_modifyFile_Click(null, null); } string ServerFileState { get { return "已上载"; } } string NewFileState { get { return "尚未上载"; } } } public delegate void Delegate_DownloadFiles(); // strID: 资源id。 public delegate int Delegate_DownloadOneMetaData(string strID, out string strResultXml, out byte [] timestamp, out string strError); }
#region Header // Revit MEP API sample application // // Copyright (C) 2007-2021 by Jeremy Tammik, Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software // for any purpose and without fee is hereby granted, provided // that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. // AUTODESK, INC. DOES NOT WARRANT THAT THE OPERATION OF THE // PROGRAM WILL BE UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject // to restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. #endregion // Header #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using Autodesk.Revit.ApplicationServices; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.UI; #endregion // Namespaces namespace AdnRme { [Transaction( TransactionMode.ReadOnly )] class CmdUnhostedElements : IExternalCommand { #region Determine unhosted elements static bool IsValidHost( string hostValue ) { bool rc = ( "<not associated>" != hostValue ) && ( "None" != hostValue ); return rc; } /// <summary> /// Determine unhosted elements. /// </summary> static bool DetermineUnhostedElements( Document doc ) { int nHosted = 0; int nUnhosted = 0; bool needHeader = true; List<string> unhosted = new List<string>(); { WaitCursor waitCursor = new WaitCursor(); FilteredElementCollector collector = new FilteredElementCollector( doc ); collector.OfClass( typeof( FamilyInstance ) ); //int j = 0; // temporary problem: running this in rac_basic_sample_project.rvt throws an exception // Unable to cast object of type 'Autodesk.Revit.DB.Panel' to type 'Autodesk.Revit.DB.FamilyInstance'. // fixed in http://srd.autodesk.com/srdapp/ReportForm.asp?number=176141 foreach( FamilyInstance inst in collector ) { //Debug.WriteLine( ++j ); Parameter p = inst.get_Parameter( Bip.Host ); if( null != p ) { if( needHeader ) { Debug.WriteLine( "\nHosted and unhosted elements:" ); needHeader = false; } string description = Util.ElementDescriptionAndId( inst ); string hostValue = p.AsString(); bool hosted = IsValidHost( hostValue ); if( hosted ) { ++nHosted; } else { ++nUnhosted; //if( null == unhosted ) //{ // unhosted = new string[1]; // unhosted[0] = description; //} //else //{ // unhosted.se //} unhosted.Add( description ); } Debug.WriteLine( string.Format( "{0} {1} host is '{2}' --> {3}hosted", description, inst.Id.IntegerValue, hostValue, hosted ? "" : "un" ) ); } } } if( 0 < nHosted + nUnhosted ) { Debug.WriteLine( string.Format( "{0} hosted and {1} unhosted elements.", nHosted, nUnhosted ) ); } if( 0 < nUnhosted ) { string[] a = new string[unhosted.Count]; int i = 0; foreach( string s in unhosted ) { a[i++] = s; } // todo: present the element ids in a separete edit box for easier copy and paste: string msg = string.Format( "{0} unhosted element{1}:\n\n", nUnhosted, Util.PluralSuffix( nUnhosted ) ) + string.Join( "\n", a ); Util.InfoMsg( msg ); } return true; } #endregion // Determine unhosted elements #region Execute Command public Result Execute( ExternalCommandData commandData, ref String message, ElementSet elements ) { try { UIApplication app = commandData.Application; Document doc = app.ActiveUIDocument.Document; // // 5. determine unhosted elements (cf. SPR 134098). // list all hosted versus unhosted elements: // bool rc = DetermineUnhostedElements( doc ); return Result.Cancelled; } catch( Exception ex ) { message = ex.Message; return Result.Failed; } } #endregion // Execute Command } }
#region License /* * Copyright 2002-2008 the original author or authors. * * 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. */ #endregion namespace BitSharper.Threading.AtomicTypes { /// <summary> /// Provide atomic access to an instance of <typeparamref name="T"/>. /// </summary> /// <typeparam name="T">The type of the instance to be updated atomically.</typeparam> /// <author>Kenneth Xu</author> internal interface IAtomic<T> //NET_ONLY { /// <summary> /// Gets and sets the current value. /// </summary> T Value { get; set; } /// <summary> /// Eventually sets to the given value. /// </summary> /// <param name="newValue"> /// the new value /// </param> void LazySet(T newValue); /// <summary> /// Atomically sets the value to the <paramref name="newValue"/> /// if the current value equals the <paramref name="expectedValue"/>. /// </summary> /// <param name="expectedValue"> /// The expected value /// </param> /// <param name="newValue"> /// The new value to use of the current value equals the expected value. /// </param> /// <returns> /// <c>true</c> if the current value equaled the expected value, <c>false</c> otherwise. /// </returns> bool CompareAndSet(T expectedValue, T newValue); /// <summary> /// Atomically sets the value to the <paramref name="newValue"/> /// if the current value equals the <paramref name="expectedValue"/>. /// May fail spuriously. /// </summary> /// <param name="expectedValue"> /// The expected value /// </param> /// <param name="newValue"> /// The new value to use of the current value equals the expected value. /// </param> /// <returns> /// <c>true</c> if the current value equaled the expected value, <c>false</c> otherwise. /// </returns> bool WeakCompareAndSet(T expectedValue, T newValue); /// <summary> /// Atomically sets to the given value and returns the previous value. /// </summary> /// <param name="newValue"> /// The new value for the instance. /// </param> /// <returns> /// the previous value of the instance. /// </returns> T Exchange(T newValue); /// <summary> /// Returns the String representation of the current value. /// </summary> /// <returns> /// The String representation of the current value. /// </returns> string ToString(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Yibai.Api.Domain { /* * 用户信息的参数列表 */ public class UserInfo { public string username { set; get; } public string mobile { set; get; } public int smsBalance { set; get; } public long createdTime { set; get; } } }
using PureDI; using IOCCTest.TestCode; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace IOCCTest { [TestClass] public class StructTest { [TestMethod] public void ShouldInstantiateStruct() { StructRoot root = new DependencyInjector().CreateAndInjectDependencies<StructRoot>().rootBean; Assert.IsNotNull(root.child); } [TestMethod] public void ShouldCreateATreeWithStructs() { StructTree tree = new DependencyInjector().CreateAndInjectDependencies<StructTree>().rootBean; Assert.IsNotNull(tree.structChild); } [TestMethod] public void ShouldCreateTreeWithMixOfClassesAndStructs() { ClassTree tree = new DependencyInjector().CreateAndInjectDependencies<ClassTree>().rootBean; Assert.IsNotNull(tree); Assert.AreEqual(1, tree?.GetStructChild2().GetClassChild()?.someValue); } } }
using System.Collections; using System.Collections.Generic; using Group3d.Localization; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; namespace Tests.Runtime { public class LocalizationTests { private GameObject localizationGameObject; private Localization localization; [SetUp] public void Setup() { localizationGameObject = new GameObject("Localization"); localization = localizationGameObject.AddComponent<Localization>(); localization.SetSupportedLanguages(new List<SupportedLanguage> { new SupportedLanguage { languageCode = "en-US", systemLanguage = SystemLanguage.English, translationFile = new TextAsset("{}"), } }); } [TearDown] public void Teardown() { Object.Destroy(localizationGameObject); } [UnityTest] public IEnumerator Translate_TranslatingKey_KeyTranslated() { // Arrange localization.SetSupportedLanguages(new List<SupportedLanguage> { new SupportedLanguage { languageCode = "en-US", systemLanguage = SystemLanguage.English, translationFile = new TextAsset("{ \"TRANSLATION_KEY\": \"translation value\" }"), } }); localization.SelectNextLanguage(); // Act yield return null; var translatedValue = Localization.Translate("TRANSLATION_KEY"); // Assert Assert.AreEqual("translation value", translatedValue); } } }
// https://www.tutorialspoint.com/csharp/csharp_constants.htm using System; namespace Constant { class Program { static void Main(string[] args) { // integer literals Object constant = 212; Console.WriteLine(constant); constant = 215U; Console.WriteLine(constant); constant = 0xFeeL; // 4078 Console.WriteLine(constant); constant = 0x4b; Console.WriteLine(constant); constant = 85; /* decimal */ Console.WriteLine(constant); constant = 0x4b; /* hexadecimal */ Console.WriteLine(constant); constant = 30; /* int */ Console.WriteLine(constant); constant = 30U; /* unsigned int */ Console.WriteLine(constant); constant = 30L; /* long */ Console.WriteLine(constant); constant = 30UL; /* unsigned long */ Console.WriteLine(constant); // floating point literals constant = 3.14159; Console.WriteLine(constant); constant = 314159E-5F; Console.WriteLine(constant); } } }
using System; namespace RabbitMQWeb.Models { [Serializable] public class LongEaredRabbitMessage : RabbitMessage { public LongEaredRabbitMessage(string message) : base(message) { } public override string ToString() { return $"long eared rabbit says \"{Message}\""; } } }
using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Types; namespace CodyMazeBot.Game { [StateHandler(BotState.WaitingForDirection)] public class WaitingForDirectionProcessor : BaseStateProcessor { public WaitingForDirectionProcessor( Conversation conversation, ITelegramBotClient bot, ILogger<WaitingForDirectionProcessor> logger ) : base(conversation, bot, logger) { } private Direction? DirectionFromQuery(string s) { return s switch { "N" => Direction.North, "E" => Direction.East, "S" => Direction.South, "W" => Direction.West, _ => null }; } public override async Task<bool> Process(Update update) { if (update.CallbackQuery == null) { return false; } var dir = DirectionFromQuery(update.CallbackQuery.Data); if(dir == null) { return false; } if(!GridCoordinate.TryParse(Conversation.CurrentUser.PartialCoordinate, out var coord)) { Logger.LogError("Received direction without partial coordinate"); // TODO say something? return false; } var finalCoord = new GridCoordinate(coord.ColumnIndex, coord.RowIndex, dir); await HandleArrivalOn(update, finalCoord); return true; } } }
<html> <head> <title>Pollr</title> <link href="~/css/site.min.css" rel="stylesheet"> <link href="~/lib/tether/dist/css/tether.min.css" rel="stylesheet"> <link href="~/lib/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="~/favicon.ico" rel="icon" type="/image/vnd.microsoft.icon"> </head> <body> <div id="content"></div> <script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/tether/dist/js/tether.min.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.min.js"></script> <script src="~/lib/signalr/jquery.signalR.min.js"></script> <script src="~/signalr/hubs"></script> @if (!string.IsNullOrWhiteSpace(ViewBag?.Link)) { <script type="text/javascript"> sessionStorage['pollLink'] = '@ViewBag.Link'; </script> } <script src="@Url.Content("~/js/client.bundle.js")"></script> </body> </html>