content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FSS.Omnius.Modules.Tapestry.Actions { public abstract class ActionSequence : Action { private List<Action> _sequence; public ActionSequence() { _sequence = new List<Action>(); } public override ActionResult run(Dictionary<string, object> vars, IActionRule_Action actionRule_action) { ActionResult results = new ActionResult(); foreach(Action action in _sequence) { results.Join(action.run(vars, actionRule_action)); } return results; } } }
24.233333
111
0.618982
[ "MIT" ]
simplifate/omnius
application/FSS.Omnius.Modules/Tapestry/Actions/ActionSequence.cs
729
C#
namespace BaristaLabs.Skrapr.ChromeDevTools.Database { using Newtonsoft.Json; /// <summary> /// Enables database tracking, database events will now be delivered to the client. /// </summary> public sealed class EnableCommand : ICommand { private const string ChromeRemoteInterface_CommandName = "Database.enable"; [JsonIgnore] public string CommandName { get { return ChromeRemoteInterface_CommandName; } } } public sealed class EnableCommandResponse : ICommandResponse<EnableCommand> { } }
25.826087
87
0.659933
[ "MIT" ]
BaristaLabs/BaristaLabs.Skrapr
src/BaristaLabs.Skrapr.ChromeDevTools/Database/EnableCommand.cs
594
C#
using NBitcoin; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using WalletWasabi.WabiSabi.Backend.Models; namespace WalletWasabi.WabiSabi.Backend.Banning; /// <summary> /// Malicious UTXOs are sent here. /// </summary> public class Prison { public Prison() : this(Enumerable.Empty<Inmate>()) { } public Prison(IEnumerable<Inmate> inmates) { Inmates = inmates.ToDictionary(x => x.Utxo, x => x); } private Dictionary<OutPoint, Inmate> Inmates { get; } private object Lock { get; } = new object(); /// <summary> /// To identify the latest change happened in the prison. /// </summary> public Guid ChangeId { get; private set; } = Guid.NewGuid(); public (int noted, int banned) CountInmates() { lock (Lock) { return (Inmates.Count(x => x.Value.Punishment == Punishment.Noted), Inmates.Count(x => x.Value.Punishment == Punishment.Banned)); } } public void Note(Alice alice, uint256 lastDisruptedRoundId) { Punish(alice.Coin.Outpoint, Punishment.Noted, lastDisruptedRoundId); } public void Ban(Alice alice, uint256 lastDisruptedRoundId) { Punish(alice.Coin.Outpoint, Punishment.Banned, lastDisruptedRoundId); } public void Punish(OutPoint utxo, Punishment punishment, uint256 lastDisruptedRoundId) => Punish(new Inmate(utxo, punishment, DateTimeOffset.UtcNow, lastDisruptedRoundId)); public void Punish(Inmate inmate) { lock (Lock) { var utxo = inmate.Utxo; // If successfully removed, then it contained it previously, so make the punishment banned and restart its time. Inmate inmateToPunish = inmate; if (Inmates.Remove(utxo)) { // If it was noted before, then no matter the specified punishment, it must be banned. // Both the started and the last disrupted round parameters must be updated. inmateToPunish = new Inmate(utxo, Punishment.Banned, inmate.Started, inmate.LastDisruptedRoundId); } Inmates.Add(utxo, inmateToPunish); ChangeId = Guid.NewGuid(); } } public bool TryRelease(OutPoint utxo, [NotNullWhen(returnValue: true)] out Inmate? inmate) { lock (Lock) { if (Inmates.TryGetValue(utxo, out inmate)) { Inmates.Remove(utxo); ChangeId = Guid.NewGuid(); return true; } else { return false; } } } public IEnumerable<Inmate> ReleaseEligibleInmates(TimeSpan time) { lock (Lock) { var released = new List<Inmate>(); foreach (var inmate in Inmates.Values.ToList()) { if (inmate.TimeSpent > time) { Inmates.Remove(inmate.Utxo); released.Add(inmate); } } if (released.Any()) { ChangeId = Guid.NewGuid(); } return released; } } public bool TryGet(OutPoint utxo, [NotNullWhen(returnValue: true)] out Inmate? inmate) { lock (Lock) { return Inmates.TryGetValue(utxo, out inmate); } } public bool IsBanned(OutPoint utxo) { return TryGet(utxo, out var inmate) && inmate.Punishment is Punishment.Banned; } public IEnumerable<Inmate> GetInmates() { lock (Lock) { return Inmates.Select(x => x.Value).ToList(); } } }
22.851852
132
0.692382
[ "MIT" ]
dorisoy/WalletWasabi
WalletWasabi/WabiSabi/Backend/Banning/Prison.cs
3,085
C#
using System; using System.Collections.Generic; using System.Text; namespace JDCloudSDK.Core.Model { /// <summary> /// the sign result /// </summary> public class SignedRequestModel { /// <summary> /// sign nonce id /// </summary> public string RequestNonceId { get; set; } /// <summary> /// the after sign all request head /// </summary> public Dictionary<string, string> RequestHead { get; set; } = new Dictionary<string, string>(); /// <summary> /// the request body content sha 256 string /// </summary> public string ContentSHA256 { get; set; } /// <summary> /// the canonical request string /// </summary> public string CanonicalRequest { get; set; } /// <summary> /// the last string which need sign /// </summary> public string StringToSign { get; set; } /// <summary> /// string signature /// </summary> public string StringSignature { get; set; } /// <summary> /// the header need to signed /// </summary> public string SignedHeaders { get; set; } } }
24.4
103
0.536885
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net-signer
JDCloud.SDK.Signer/Core/Model/SignedRequestModel.cs
1,222
C#
using System; namespace KoharuYomiageApp.UseCase.AddMisskeyAccount.DataObjects { public record UserData(string Username, string DisplayName, Uri IconUrl); }
23.285714
77
0.809816
[ "Apache-2.0", "MIT" ]
MatchaChoco010/KoharuYomiage
KoharuYomiageApp/UseCase/AddMisskeyAccount/DataObjects/UserData.cs
165
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/Mobsync.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop.Windows; public static partial class IID { public static ref readonly Guid IID_ISyncMgrSynchronizeCallback { get { ReadOnlySpan<byte> data = new byte[] { 0x41, 0xDF, 0x95, 0x62, 0xEE, 0x35, 0xD1, 0x11, 0x87, 0x07, 0x00, 0xC0, 0x4F, 0xD9, 0x33, 0x27 }; Debug.Assert(data.Length == Unsafe.SizeOf<Guid>()); return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data)); } } public static ref readonly Guid IID_ISyncMgrEnumItems { get { ReadOnlySpan<byte> data = new byte[] { 0x2A, 0xDF, 0x95, 0x62, 0xEE, 0x35, 0xD1, 0x11, 0x87, 0x07, 0x00, 0xC0, 0x4F, 0xD9, 0x33, 0x27 }; Debug.Assert(data.Length == Unsafe.SizeOf<Guid>()); return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data)); } } public static ref readonly Guid IID_ISyncMgrSynchronize { get { ReadOnlySpan<byte> data = new byte[] { 0x40, 0xDF, 0x95, 0x62, 0xEE, 0x35, 0xD1, 0x11, 0x87, 0x07, 0x00, 0xC0, 0x4F, 0xD9, 0x33, 0x27 }; Debug.Assert(data.Length == Unsafe.SizeOf<Guid>()); return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data)); } } public static ref readonly Guid IID_ISyncMgrSynchronizeInvoke { get { ReadOnlySpan<byte> data = new byte[] { 0x2C, 0xDF, 0x95, 0x62, 0xEE, 0x35, 0xD1, 0x11, 0x87, 0x07, 0x00, 0xC0, 0x4F, 0xD9, 0x33, 0x27 }; Debug.Assert(data.Length == Unsafe.SizeOf<Guid>()); return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data)); } } public static ref readonly Guid IID_ISyncMgrRegister { get { ReadOnlySpan<byte> data = new byte[] { 0x42, 0xDF, 0x95, 0x62, 0xEE, 0x35, 0xD1, 0x11, 0x87, 0x07, 0x00, 0xC0, 0x4F, 0xD9, 0x33, 0x27 }; Debug.Assert(data.Length == Unsafe.SizeOf<Guid>()); return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data)); } } public static ref readonly Guid IID_SyncMgr { get { ReadOnlySpan<byte> data = new byte[] { 0x27, 0xDF, 0x95, 0x62, 0xEE, 0x35, 0xD1, 0x11, 0x87, 0x07, 0x00, 0xC0, 0x4F, 0xD9, 0x33, 0x27 }; Debug.Assert(data.Length == Unsafe.SizeOf<Guid>()); return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data)); } } }
26.261438
145
0.448482
[ "MIT" ]
reflectronic/terrafx.interop.windows
sources/Interop/Windows/Windows/um/Mobsync/IID.cs
4,020
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; #nullable disable namespace CentroHipicoAPI.Datos.Modelos.CentroHipico { public partial class CentroHipicoContext : DbContext { public CentroHipicoContext() { } public CentroHipicoContext(DbContextOptions<CentroHipicoContext> options) : base(options) { } public virtual DbSet<Carrera> Carreras { get; set; } public virtual DbSet<CarreraDetalle> CarreraDetalles { get; set; } public virtual DbSet<CarreraEjemplar> CarreraEjemplares { get; set; } public virtual DbSet<Cliente> Clientes { get; set; } public virtual DbSet<Ejemplar> Ejemplares { get; set; } public virtual DbSet<User> Users { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasAnnotation("Relational:Collation", "Modern_Spanish_CI_AS"); modelBuilder.Entity<Carrera>(entity => { entity.Property(e => e.FechaActualizacion).HasColumnType("datetime"); entity.Property(e => e.FechaCarrera).HasColumnType("datetime"); entity.Property(e => e.FechaCreacion).HasColumnType("datetime"); entity.Property(e => e.MontoGanancia).HasColumnType("decimal(9, 2)"); entity.Property(e => e.MontoSubTotal).HasColumnType("decimal(9, 2)"); entity.Property(e => e.MontoTotal).HasColumnType("decimal(9, 2)"); entity.Property(e => e.Ubicacion) .HasMaxLength(255) .IsUnicode(false); }); modelBuilder.Entity<CarreraDetalle>(entity => { entity.Property(e => e.FechaActualizacion).HasColumnType("datetime"); entity.Property(e => e.FechaCreacion).HasColumnType("datetime"); entity.Property(e => e.MontoApuesta).HasColumnType("decimal(9, 2)"); entity.HasOne(d => d.IdCarreraNavigation) .WithMany(p => p.CarreraDetalles) .HasForeignKey(d => d.IdCarrera) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK__CarreraDe__IdCar__440B1D61"); entity.HasOne(d => d.IdClienteNavigation) .WithMany(p => p.CarreraDetalles) .HasForeignKey(d => d.IdCliente) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK__CarreraDe__IdCli__44FF419A"); entity.HasOne(d => d.IdEjemplarNavigation) .WithMany(p => p.CarreraDetalles) .HasForeignKey(d => d.IdEjemplar) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK__CarreraDe__IdEje__45F365D3"); }); modelBuilder.Entity<CarreraEjemplar>(entity => { entity.Property(e => e.FechaActualizacion).HasColumnType("datetime"); entity.Property(e => e.FechaCreacion).HasColumnType("datetime"); entity.HasOne(d => d.IdCarreraNavigation) .WithMany(p => p.CarreraEjemplares) .HasForeignKey(d => d.IdCarrera) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK__CarreraEj__IdCar__412EB0B6"); entity.HasOne(d => d.IdEjemplarNavigation) .WithMany(p => p.CarreraEjemplares) .HasForeignKey(d => d.IdEjemplar) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK__CarreraEj__IdEje__403A8C7D"); }); modelBuilder.Entity<Cliente>(entity => { entity.Property(e => e.FechaActualizacion).HasColumnType("datetime"); entity.Property(e => e.FechaCreacion).HasColumnType("datetime"); entity.Property(e => e.Nombre) .IsRequired() .HasMaxLength(255) .IsUnicode(false); entity.Property(e => e.Telefono) .HasMaxLength(255) .IsUnicode(false); }); modelBuilder.Entity<Ejemplar>(entity => { entity.Property(e => e.FechaActualizacion).HasColumnType("datetime"); entity.Property(e => e.FechaCreacion).HasColumnType("datetime"); entity.Property(e => e.Nombre) .IsRequired() .HasMaxLength(255) .IsUnicode(false); }); modelBuilder.Entity<User>(entity => { entity.HasIndex(e => e.Username, "UQ__Users__536C85E40BFEA1C4") .IsUnique(); entity.Property(e => e.CreatedAt).HasColumnType("datetime"); entity.Property(e => e.Name) .IsRequired() .HasMaxLength(255) .IsUnicode(false); entity.Property(e => e.Password) .IsRequired() .HasMaxLength(255) .IsUnicode(false); entity.Property(e => e.UpdatedAt).HasColumnType("datetime"); entity.Property(e => e.Username) .IsRequired() .HasMaxLength(255) .IsUnicode(false); }); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } }
37.03871
87
0.546943
[ "MIT" ]
edwardmacorini/CentroHipicoV1
CentroHipicoAPI/CentroHipicoAPI.Datos/Modelos/CentroHipico/CentroHipicoContext.cs
5,743
C#
using System.ComponentModel.DataAnnotations; namespace CoffeeHouse.Models { public class MaquinaCafe { [Required(ErrorMessage = "Campo {0} obrigatório")] [Range(0, 100, ErrorMessage = "Campo {0}: Apenas números positivos")] [Display(Name = "R$ 0,01")] public int UmCentavo { get; set; } [Required(ErrorMessage = "Campo {0} obrigatório")] [Range(0, 100, ErrorMessage = "Campo {0}: Apenas números positivos")] [Display(Name = "R$ 0,05")] public int CincoCentavo { get; set; } [Required(ErrorMessage = "Campo {0} obrigatório")] [Range(0, 100, ErrorMessage = "Campo {0}: Apenas números positivos")] [Display(Name = "R$ 0,10")] public int DezCentavo { get; set; } [Required(ErrorMessage = "Campo {0} obrigatório")] [Range(0, 100, ErrorMessage = "Campo {0}: Apenas números positivos")] [Display(Name = "R$ 0,25")] public int VinteCincoCentavo { get; set; } [Required(ErrorMessage = "Campo {0} obrigatório")] [Range(0, 100, ErrorMessage = "Campo {0}: Apenas números positivos")] [Display(Name = "R$ 0,50")] public int CinquentaCentavo { get; set; } [Required(ErrorMessage = "Campo {0} obrigatório")] [Range(0, 100, ErrorMessage = "Campo {0}: Apenas números positivos")] [Display(Name = "R$ 1,00")] public int UmReal { get; set; } [Required(ErrorMessage = "Campo {0} obrigatório")] [Display(Name = "Selecione o café")] public int TipoCafe { get; set; } [DataType(DataType.Currency)] public double ValorCafe { get; set; } [DataType(DataType.Currency)] public double Troco { get; set; } [DataType(DataType.Currency)] public double ValorAceito { get; set; } public string Descricao { get; set; } public MaquinaCafe() { } } }
33.947368
77
0.586047
[ "MIT" ]
karolinagb/CoffeeHouse
CoffeeHouse/Models/MaquinaCafe.cs
1,951
C#
namespace Facade.Subsystems { public class Projector { public void On() { } public void WideScreenMode() { } public void Off() { } } }
13
36
0.425339
[ "MIT" ]
filimor/head-first-design-patterns
DesignPatterns/Structural/Facade/Subsystems/Projector.cs
223
C#
using Abp.Application.Services.Dto; using Abp.AutoMapper; using Futbol3.Authorization.Users; namespace Futbol3.Sessions.Dto { [AutoMapFrom(typeof(User))] public class UserLoginInfoDto : EntityDto<long> { public string Name { get; set; } public string Surname { get; set; } public string UserName { get; set; } public string EmailAddress { get; set; } } }
21.473684
51
0.659314
[ "MIT" ]
marcoscolombo66/6.0.0
aspnet-core/src/Futbol3.Application/Sessions/Dto/UserLoginInfoDto.cs
410
C#
using System; using System.Collections.Generic; using UnityEngine; namespace Unity.InteractiveTutorials { [Serializable] class TypedCriterion { [SerializeField] [SerializedTypeFilter(typeof(Criterion))] public SerializedType type; [SerializeField] public Criterion criterion; public TypedCriterion(SerializedType type, Criterion criterion) { this.type = type; this.criterion = criterion; } } [Serializable] class TypedCriterionCollection : CollectionWrapper<TypedCriterion> { public TypedCriterionCollection() : base() { } public TypedCriterionCollection(IList<TypedCriterion> items) : base(items) { } } }
21.638889
82
0.630295
[ "MIT" ]
CristianCamilo04/tson1
trod1-game/Library/PackageCache/com.unity.learn.iet-framework@0.2.3-preview.1/Framework/Interactive Tutorials/Editor/Models/TypedCriterion.cs
779
C#
/* Copyright (C) 2015 haha01haha01 * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using System.IO; using System.Text.RegularExpressions; using Footholds; using MapleLib.WzLib; using MapleLib.WzLib.WzProperties; using MapleLib.WzLib.Serialization; using System.Threading; using HaRepacker.GUI.Interaction; using MapleLib.WzLib.Util; using System.Runtime.InteropServices; using MapleLib.WzLib.WzStructure; using System.Net; using System.Text; using System.Diagnostics; using System.IO.Pipes; using System.Linq; using System.Threading.Tasks; using System.Windows.Threading; using Win32; using HaRepacker.GUI.Panels; using HaRepacker.GUI.Input; using HaRepacker.Configuration; namespace HaRepacker.GUI { public partial class MainForm : Form { /// <summary> /// Adds the WZ encryption types to ToolstripComboBox. /// Shared code between WzMapleVersionInputBox.cs /// </summary> /// <param name="encryptionBox"></param> public static void AddWzEncryptionTypesToComboBox(object encryptionBox) { string[] resources = { HaRepacker.Properties.Resources.EncTypeGMS, HaRepacker.Properties.Resources.EncTypeMSEA, HaRepacker.Properties.Resources.EncTypeNone }; if (encryptionBox is ToolStripComboBox) { foreach (string res in resources) { ((ToolStripComboBox)encryptionBox).Items.Add(res); } } else { foreach (string res in resources) { ((ComboBox)encryptionBox).Items.Add(res); } } } private bool mainFormLoaded = false; private MainPanel MainPanel = null; public MainForm(string wzToLoad, bool usingPipes, bool firstrun) { InitializeComponent(); AddTabsInternal("Default"); // Events Load += MainForm_Load1; #if DEBUG debugToolStripMenuItem.Visible = true; #endif // Sets theme color SetThemeColor(); // encryptions AddWzEncryptionTypesToComboBox(encryptionBox); WindowState = Program.ConfigurationManager.ApplicationSettings.WindowMaximized ? FormWindowState.Maximized : FormWindowState.Normal; Size = new Size( Program.ConfigurationManager.ApplicationSettings.Width, Program.ConfigurationManager.ApplicationSettings.Height); // Set default selected main panel UpdateSelectedMainPanelTab(); if (usingPipes) { try { Program.pipe = new NamedPipeServerStream(Program.pipeName, PipeDirection.In); Program.pipeThread = new Thread(new ThreadStart(PipeServer)); Program.pipeThread.IsBackground = true; Program.pipeThread.Start(); } catch (IOException) { if (wzToLoad != null) { try { NamedPipeClientStream clientPipe = new NamedPipeClientStream(".", Program.pipeName, PipeDirection.Out); clientPipe.Connect(0); StreamWriter sw = new StreamWriter(clientPipe); sw.WriteLine(wzToLoad); clientPipe.WaitForPipeDrain(); sw.Close(); Environment.Exit(0); } catch (TimeoutException) { } } } } if (wzToLoad != null && File.Exists(wzToLoad)) { short version; WzMapleVersion encVersion = WzTool.DetectMapleVersion(wzToLoad, out version); encryptionBox.SelectedIndex = (int)encVersion; LoadWzFileThreadSafe(wzToLoad, MainPanel, false); } ContextMenuManager manager = new ContextMenuManager(MainPanel, MainPanel.UndoRedoMan); WzNode.ContextMenuBuilder = new WzNode.ContextMenuBuilderDelegate(manager.CreateMenu); // Focus on the tab control tabControl_MainPanels.Focus(); // flag. loaded mainFormLoaded = true; } private void MainForm_Load1(object sender, EventArgs e) { } public void Interop_AddLoadedWzFileToManager(WzFile f) { Program.WzMan.InsertWzFileUnsafe(f, MainPanel); } #region Theme colors public void SetThemeColor() { if (Program.ConfigurationManager.UserSettings.ThemeColor == 0)//black { this.BackColor = Color.Black; mainMenu.BackColor = Color.Black; mainMenu.ForeColor = Color.White; /*for (int i = 0; i < mainMenu.Items.Count; i++) { try { foreach (ToolStripMenuItem item in ((ToolStripMenuItem)mainMenu.Items[i]).DropDownItems) { item.BackColor = Color.Black; item.ForeColor = Color.White; MessageBox.Show(item.Name); } } catch (Exception) { continue; //throw; } }*/ button_addTab.ForeColor = Color.White; button_addTab.BackColor = Color.Black; } else { this.BackColor = DefaultBackColor; mainMenu.BackColor = DefaultBackColor; mainMenu.ForeColor = Color.Black; button_addTab.ForeColor = Color.Black; button_addTab.BackColor = Color.White; } } #endregion private delegate void LoadWzFileDelegate(string path, MainPanel panel, bool detectMapleVersion); private void LoadWzFileCallback(string path, MainPanel panel, bool detectMapleVersion) { try { if (detectMapleVersion) Program.WzMan.LoadWzFile(path, panel); else Program.WzMan.LoadWzFile(path, (WzMapleVersion)encryptionBox.SelectedIndex, MainPanel); } catch { Warning.Error(string.Format(HaRepacker.Properties.Resources.MainCouldntOpenWZ, path)); } } private void LoadWzFileThreadSafe(string path, MainPanel panel, bool detectMapleVersion) { /* if (panel.InvokeRequired) panel.Invoke(new LoadWzFileDelegate(LoadWzFileCallback), path, panel, detectMapleVersion); else LoadWzFileCallback(path, panel, detectMapleVersion);*/ panel.Dispatcher.Invoke(() => { LoadWzFileCallback(path, panel, detectMapleVersion); }); } private delegate void SetWindowStateDelegate(FormWindowState state); private void SetWindowStateCallback(FormWindowState state) { WindowState = state; user32.SetWindowPos(Handle, user32.HWND_TOPMOST, 0, 0, 0, 0, user32.SWP_NOMOVE | user32.SWP_NOSIZE); user32.SetWindowPos(Handle, user32.HWND_NOTOPMOST, 0, 0, 0, 0, user32.SWP_NOMOVE | user32.SWP_NOSIZE); } private void SetWindowStateThreadSafe(FormWindowState state) { if (InvokeRequired) Invoke(new SetWindowStateDelegate(SetWindowStateCallback), state); else SetWindowStateCallback(state); } private string OnPipeRequest(string request) { if (File.Exists(request)) LoadWzFileThreadSafe(request, MainPanel, true); SetWindowStateThreadSafe(FormWindowState.Normal); return "OK"; } private void PipeServer() { try { while (true) { Program.pipe.WaitForConnection(); StreamReader sr = new StreamReader(Program.pipe); OnPipeRequest(sr.ReadLine()); Program.pipe.Disconnect(); } } catch { } } public static Thread updater = null; //a thread used by the updating feature private void UpdaterThread() { Thread.Sleep(60000); WebClient client = new WebClient(); try { int version = int.Parse( Encoding.ASCII.GetString( client.DownloadData( Program.ConfigurationManager.ApplicationSettings.UpdateServer + "version.txt" ))); string notice = Encoding.ASCII.GetString( client.DownloadData( Program.ConfigurationManager.ApplicationSettings.UpdateServer + "notice.txt" )); string url = Encoding.ASCII.GetString( client.DownloadData( Program.ConfigurationManager.ApplicationSettings.UpdateServer + "url.txt" )); if (version <= Program.Version_) return; if (MessageBox.Show(string.Format(HaRepacker.Properties.Resources.MainUpdateAvailable, notice.Replace("%URL%", url)), HaRepacker.Properties.Resources.MainUpdateTitle, MessageBoxButtons.YesNo) == DialogResult.Yes) Process.Start(url); } catch { } } #region Handlers private void MainForm_Load(object sender, EventArgs e) { encryptionBox.SelectedIndex = (int)Program.ConfigurationManager.ApplicationSettings.MapleVersion; if (Program.ConfigurationManager.UserSettings.AutoUpdate && Program.ConfigurationManager.ApplicationSettings.UpdateServer != "") { updater = new Thread(new ThreadStart(UpdaterThread)); updater.IsBackground = true; updater.Start(); } } /// <summary> /// Redocks the list of controls on the panel /// </summary> private void RedockControls() { /* int mainControlHeight = this.Size.Height; int mainControlWidth = this.Size.Width; foreach (TabPage page in tabControl_MainPanels.TabPages) { page.Size = new Size(mainControlWidth, mainControlHeight); }*/ } private void MainForm_SizeChanged(object sender, EventArgs e) { if (!mainFormLoaded) return; if (this.Size.Width * this.Size.Height != 0) { RedockControls(); Program.ConfigurationManager.ApplicationSettings.Height = this.Size.Height; Program.ConfigurationManager.ApplicationSettings.Width = this.Size.Width; Program.ConfigurationManager.ApplicationSettings.WindowMaximized = WindowState == FormWindowState.Maximized; } } /// <summary> /// When the selected tab in the MainForm change /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void tabControl_MainPanels_TabIndexChanged(object sender, EventArgs e) { UpdateSelectedMainPanelTab(); } /// <summary> /// On key up event for hotkeys /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void tabControl_MainPanels_KeyUp(object sender, KeyEventArgs e) { byte countTabs = Convert.ToByte(tabControl_MainPanels.TabCount); if (e.Control) { switch (e.KeyCode) { case Keys.T: // Open new tab AddTabsInternal(); break; case Keys.O: // Open new WZ file openToolStripMenuItem_Click(null, null); break; case Keys.N: // New newToolStripMenuItem_Click(null, null); break; case Keys.A: MainPanel.StartAnimateSelectedCanvas(); break; case Keys.P: MainPanel.StopCanvasAnimation(); break; // Switch between tabs case Keys.NumPad1: tabControl_MainPanels.SelectTab(0); break; case Keys.NumPad2: if (countTabs < 2) return; tabControl_MainPanels.SelectTab(1); break; case Keys.NumPad3: if (countTabs < 3) return; tabControl_MainPanels.SelectTab(2); break; case Keys.NumPad4: if (countTabs < 4) return; tabControl_MainPanels.SelectTab(3); break; case Keys.NumPad5: if (countTabs < 5) return; tabControl_MainPanels.SelectTab(4); break; case Keys.NumPad6: if (countTabs < 6) return; tabControl_MainPanels.SelectTab(5); break; case Keys.NumPad7: if (countTabs < 7) return; tabControl_MainPanels.SelectTab(6); break; case Keys.NumPad8: if (countTabs < 8) return; tabControl_MainPanels.SelectTab(7); break; case Keys.NumPad9: if (countTabs < 9) return; tabControl_MainPanels.SelectTab(8); break; case Keys.NumPad0: if (countTabs < 10) return; tabControl_MainPanels.SelectTab(9); break; } } } private void UpdateSelectedMainPanelTab() { TabPage selectedTab = tabControl_MainPanels.SelectedTab; if (selectedTab != null && selectedTab.Controls.Count > 0) { System.Windows.Forms.Integration.ElementHost elemntHost = (System.Windows.Forms.Integration.ElementHost)selectedTab.Controls[0]; MainPanel = (MainPanel)elemntHost?.Child; } } /// <summary> /// Add a new tab to the TabControl /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button_addTab_Click(object sender, EventArgs e) { AddTabsInternal(); } /// <summary> /// Prompts a window to add a new tab /// </summary> private void AddTabsInternal(string defaultName = null) { if (tabControl_MainPanels.TabCount > 10) { return; } TabPage tabPage = new TabPage() { Margin = new Padding(1, 1, 1, 1) }; System.Windows.Forms.Integration.ElementHost elemHost = new System.Windows.Forms.Integration.ElementHost(); elemHost.Dock = DockStyle.Fill; elemHost.Child = new MainPanel(); tabPage.Controls.Add(elemHost); string tabName = null; if (defaultName == null) { if (!NameInputBox.Show(Properties.Resources.MainAddTabTitle, 25, out tabName)) { return; } defaultName = tabName; } else { MainPanel = (MainPanel)elemHost.Child; } tabPage.Text = defaultName; tabControl_MainPanels.TabPages.Add(tabPage); // Focus on that tab control tabControl_MainPanels.Focus(); } private void encryptionBox_SelectedIndexChanged(object sender, EventArgs e) { Program.ConfigurationManager.ApplicationSettings.MapleVersion = (WzMapleVersion)encryptionBox.SelectedIndex; } /// <summary> /// Open file /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void openToolStripMenuItem_Click(object sender, EventArgs e) { using (OpenFileDialog dialog = new OpenFileDialog() { Title = HaRepacker.Properties.Resources.SelectWz, Filter = string.Format("{0}|*.wz", HaRepacker.Properties.Resources.WzFilter), Multiselect = true, }) { if (dialog.ShowDialog() != DialogResult.OK) return; bool errorOpeningFile_Admin = false; List<string> wzfilePathsToLoad = new List<string>(); WzMapleVersion MapleVersionEncryptionSelected = (WzMapleVersion)encryptionBox.SelectedIndex; foreach (string filePath in dialog.FileNames) { string filePathLowerCase = filePath.ToLower(); if (filePathLowerCase.EndsWith("data.wz") && WzTool.IsDataWzHotfixFile(filePath)) { WzImage img = Program.WzMan.LoadDataWzHotfixFile(filePath, MapleVersionEncryptionSelected, MainPanel); if (img == null) { errorOpeningFile_Admin = true; break; } } else if (WzTool.IsListFile(filePath)) { new ListEditor(filePath, MapleVersionEncryptionSelected).Show(); } else { wzfilePathsToLoad.Add(filePath); // add to list, so we can load it concurrently if (filePathLowerCase.EndsWith("map.wz")) { string[] otherMapWzFiles = Directory.GetFiles(filePath.Substring(0, filePath.LastIndexOf("\\")), "Map*.wz"); foreach (string filePath_Others in otherMapWzFiles) { if (filePath_Others != filePath && (filePath_Others.EndsWith("Map001.wz") || filePath_Others.EndsWith("Map2.wz"))) // damn, ugly hack to only whitelist those that Nexon uses. but someone could be saving as say Map_bak.wz in their folder. { wzfilePathsToLoad.Add(filePath_Others); } } } else if (filePathLowerCase.EndsWith("mob.wz")) // Now pre-load the other part of Mob.wz { string[] otherMobWzFiles = Directory.GetFiles(filePath.Substring(0, filePath.LastIndexOf("\\")), "Mob*.wz"); foreach (string filePath_Others in otherMobWzFiles) { if (filePath_Others != filePath && filePath_Others.EndsWith("Mob2.wz")) { wzfilePathsToLoad.Add(filePath_Others); } } } } } Dispatcher currentDispatcher = Dispatcher.CurrentDispatcher; // Load all original WZ files Parallel.ForEach(wzfilePathsToLoad, filePath => { WzFile f = Program.WzMan.LoadWzFile(filePath, MapleVersionEncryptionSelected, MainPanel, currentDispatcher); if (f == null) { errorOpeningFile_Admin = true; } }); // error opening one of the files if (errorOpeningFile_Admin) { MessageBox.Show(HaRepacker.Properties.Resources.MainFileOpenFail, HaRepacker.Properties.Resources.Error); } } } private void unloadAllToolStripMenuItem_Click(object sender, EventArgs e) { if (Warning.Warn(HaRepacker.Properties.Resources.MainUnloadAll)) Program.WzMan.UnloadAll(); } private void reloadAllToolStripMenuItem_Click(object sender, EventArgs e) { if (Warning.Warn(HaRepacker.Properties.Resources.MainReloadAll)) Program.WzMan.ReloadAll(MainPanel); } private void renderMapToolStripMenuItem_Click(object sender, EventArgs e) { if (MainPanel.DataTree.SelectedNode == null) return; if (MainPanel.DataTree.SelectedNode.Tag is WzImage) { double zoomLevel = double.Parse(zoomTextBox.TextBox.Text); WzImage img = (WzImage)MainPanel.DataTree.SelectedNode.Tag; string mapName = img.Name.Substring(0, img.Name.Length - 4); if (!Directory.Exists("Renders\\" + mapName)) { Directory.CreateDirectory("Renders\\" + mapName); } try { List<string> renderErrorList = new List<string>(); FHMapper.FHMapper mapper = new FHMapper.FHMapper(MainPanel); mapper.ParseSettings(); bool rendered = mapper.TryRenderMapAndSave(img, zoomLevel, ref renderErrorList); if (!rendered) { StringBuilder sb = new StringBuilder(); int i = 1; foreach (string error in renderErrorList) { sb.Append("[").Append(i).Append("] ").Append(error); sb.AppendLine(); i++; } MessageBox.Show(sb.ToString(), "Error rendering map"); } } catch (ArgumentException argExp) { MessageBox.Show(argExp.Message, "Error rendering map"); } } } private void settingsToolStripMenuItem_Click(object sender, EventArgs e) { FHMapper.FHMapper mapper = new FHMapper.FHMapper(MainPanel); mapper.ParseSettings(); Settings settingsDialog = new Settings(); settingsDialog.settings = mapper.settings; settingsDialog.main = mapper; settingsDialog.ShowDialog(); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { new AboutForm().ShowDialog(); } private void optionsToolStripMenuItem_Click(object sender, EventArgs e) { new OptionsForm(MainPanel).ShowDialog(); } /// <summary> /// New WZ /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void newToolStripMenuItem_Click(object sender, EventArgs e) { new NewForm(MainPanel).ShowDialog(); } /// <summary> /// Save tool strip menu button clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void saveToolStripMenuItem_Click(object sender, EventArgs e) { WzNode node; if (MainPanel.DataTree.SelectedNode == null) { if (MainPanel.DataTree.Nodes.Count == 1) node = (WzNode)MainPanel.DataTree.Nodes[0]; else { MessageBox.Show(HaRepacker.Properties.Resources.MainSelectWzFolder, HaRepacker.Properties.Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } else { if (MainPanel.DataTree.SelectedNode.Tag is WzFile) node = (WzNode)MainPanel.DataTree.SelectedNode; else node = ((WzNode)MainPanel.DataTree.SelectedNode).TopLevelNode; } // Save to file. if (node.Tag is WzFile || node.Tag is WzImage) { new SaveForm(MainPanel, node).ShowDialog(); } } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { Program.ConfigurationManager.ApplicationSettings.WindowMaximized = WindowState == FormWindowState.Maximized; e.Cancel = !Warning.Warn(HaRepacker.Properties.Resources.MainConfirmExit); } #endregion private void removeToolStripMenuItem_Click(object sender, EventArgs e) { RemoveSelectedNodes(); } private void RemoveSelectedNodes() { if (!Warning.Warn(HaRepacker.Properties.Resources.MainConfirmRemoveNode)) { return; } MainPanel.PromptRemoveSelectedTreeNodes(); } private void RunWzFilesExtraction(object param) { ChangeApplicationState(false); string[] wzFilesToDump = (string[])((object[])param)[0]; string baseDir = (string)((object[])param)[1]; WzMapleVersion version = (WzMapleVersion)((object[])param)[2]; IWzFileSerializer serializer = (IWzFileSerializer)((object[])param)[3]; UpdateProgressBar(MainPanel.mainProgressBar, 0, false, true); UpdateProgressBar(MainPanel.mainProgressBar, wzFilesToDump.Length, true, true); if (!Directory.Exists(baseDir)) { Directory.CreateDirectory(baseDir); } foreach (string wzpath in wzFilesToDump) { if (WzTool.IsListFile(wzpath)) { Warning.Error(string.Format(HaRepacker.Properties.Resources.MainListWzDetected, wzpath)); continue; } WzFile f = new WzFile(wzpath, version); f.ParseWzFile(); serializer.SerializeFile(f, Path.Combine(baseDir, f.Name)); f.Dispose(); UpdateProgressBar(MainPanel.mainProgressBar, 1, false, false); } threadDone = true; } private void RunWzImgDirsExtraction(object param) { ChangeApplicationState(false); List<WzDirectory> dirsToDump = (List<WzDirectory>)((object[])param)[0]; List<WzImage> imgsToDump = (List<WzImage>)((object[])param)[1]; string baseDir = (string)((object[])param)[2]; IWzImageSerializer serializer = (IWzImageSerializer)((object[])param)[3]; UpdateProgressBar(MainPanel.mainProgressBar, 0, false, true); UpdateProgressBar(MainPanel.mainProgressBar, dirsToDump.Count + imgsToDump.Count, true, true); if (!Directory.Exists(baseDir)) { Directory.CreateDirectory(baseDir); } foreach (WzImage img in imgsToDump) { serializer.SerializeImage(img, Path.Combine(baseDir, img.Name)); UpdateProgressBar(MainPanel.mainProgressBar, 1, false, false); } foreach (WzDirectory dir in dirsToDump) { serializer.SerializeDirectory(dir, Path.Combine(baseDir, dir.Name)); UpdateProgressBar(MainPanel.mainProgressBar, 1, false, false); } threadDone = true; } private void RunWzObjExtraction(object param) { ChangeApplicationState(false); List<WzObject> objsToDump = (List<WzObject>)((object[])param)[0]; string path = (string)((object[])param)[1]; ProgressingWzSerializer serializer = (ProgressingWzSerializer)((object[])param)[2]; UpdateProgressBar(MainPanel.mainProgressBar, 0, false, true); if (serializer is IWzObjectSerializer) { UpdateProgressBar(MainPanel.mainProgressBar, objsToDump.Count, true, true); foreach (WzObject obj in objsToDump) { ((IWzObjectSerializer)serializer).SerializeObject(obj, path); UpdateProgressBar(MainPanel.mainProgressBar, 1, false, false); } } else if (serializer is WzNewXmlSerializer) { UpdateProgressBar(MainPanel.mainProgressBar, 1, true, true); ((WzNewXmlSerializer)serializer).ExportCombinedXml(objsToDump, path); UpdateProgressBar(MainPanel.mainProgressBar, 1, false, false); } threadDone = true; } //yes I know this is a stupid way to synchronize threads, I'm just too lazy to use events or locks private bool threadDone = false; private Thread runningThread = null; private delegate void ChangeAppStateDelegate(bool enabled); private void ChangeApplicationStateCallback(bool enabled) { mainMenu.Enabled = enabled; MainPanel.IsEnabled = enabled; AbortButton.Visible = !enabled; } private void ChangeApplicationState(bool enabled) { Invoke(new ChangeAppStateDelegate(ChangeApplicationStateCallback), new object[] { enabled }); } private void xMLToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog() { Title = HaRepacker.Properties.Resources.SelectWz, Filter = string.Format("{0}|*.wz", HaRepacker.Properties.Resources.WzFilter), Multiselect = true }; if (dialog.ShowDialog() != DialogResult.OK) return; FolderBrowserDialog folderDialog = new FolderBrowserDialog() { Description = HaRepacker.Properties.Resources.SelectOutDir }; if (folderDialog.ShowDialog() != DialogResult.OK) return; WzClassicXmlSerializer serializer = new WzClassicXmlSerializer( Program.ConfigurationManager.UserSettings.Indentation, Program.ConfigurationManager.UserSettings.LineBreakType, false); threadDone = false; new Thread(new ParameterizedThreadStart(RunWzFilesExtraction)).Start((object)new object[] { dialog.FileNames, folderDialog.SelectedPath, encryptionBox.SelectedIndex, serializer }); new Thread(new ParameterizedThreadStart(ProgressBarThread)).Start(serializer); } private delegate void UpdateProgressBarDelegate(ToolStripProgressBar pbar, int value, bool max, bool absolute); //max for .Maximum, !max for .Value private void UpdateProgressBarCallback(System.Windows.Controls.ProgressBar pbar, int value, bool max, bool absolute) { if (max) { if (absolute) pbar.Maximum = value; else pbar.Maximum += value; } else { if (absolute) pbar.Value = value; else pbar.Value += value; } } private void UpdateProgressBar(System.Windows.Controls.ProgressBar pbar, int value, bool max, bool absolute) { pbar.Dispatcher.Invoke(() => { UpdateProgressBarCallback(pbar, value, max, absolute); }); /* if (pbar.ProgressBar.InvokeRequired) pbar.ProgressBar.Invoke(new UpdateProgressBarDelegate(UpdateProgressBarCallback), new object[] { pbar, value, max, absolute }); else UpdateProgressBarCallback(pbar, value, max, absolute);*/ } private void ProgressBarThread(object param) { ProgressingWzSerializer serializer = (ProgressingWzSerializer)param; while (!threadDone) { int total = serializer.Total; UpdateProgressBar(MainPanel.secondaryProgressBar, total, true, true); UpdateProgressBar(MainPanel.secondaryProgressBar, Math.Min(total, serializer.Current), false, true); Thread.Sleep(500); } UpdateProgressBar(MainPanel.mainProgressBar, 0, true, true); UpdateProgressBar(MainPanel.secondaryProgressBar, 0, false, true); ChangeApplicationState(true); threadDone = false; } private string GetOutputDirectory() { return Program.ConfigurationManager.UserSettings.DefaultXmlFolder == "" ? SavedFolderBrowser.Show(HaRepacker.Properties.Resources.SelectOutDir) : Program.ConfigurationManager.UserSettings.DefaultXmlFolder; } private void rawDataToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog() { Title = HaRepacker.Properties.Resources.SelectWz, Filter = string.Format("{0}|*.wz", HaRepacker.Properties.Resources.WzFilter), Multiselect = true }; if (dialog.ShowDialog() != DialogResult.OK) return; string outPath = GetOutputDirectory(); if (outPath == string.Empty) { MessageBox.Show(Properties.Resources.MainWzExportError, Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } WzPngMp3Serializer serializer = new WzPngMp3Serializer(); threadDone = false; runningThread = new Thread(new ParameterizedThreadStart(RunWzFilesExtraction)); runningThread.Start((object)new object[] { dialog.FileNames, outPath, encryptionBox.SelectedIndex, serializer }); new Thread(new ParameterizedThreadStart(ProgressBarThread)).Start(serializer); } private void imgToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog() { Title = HaRepacker.Properties.Resources.SelectWz, Filter = string.Format("{0}|*.wz", HaRepacker.Properties.Resources.WzFilter), Multiselect = true }; if (dialog.ShowDialog() != DialogResult.OK) return; string outPath = GetOutputDirectory(); if (outPath == string.Empty) { MessageBox.Show(Properties.Resources.MainWzExportError, Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } WzImgSerializer serializer = new WzImgSerializer(); threadDone = false; runningThread = new Thread(new ParameterizedThreadStart(RunWzFilesExtraction)); runningThread.Start((object)new object[] { dialog.FileNames, outPath, encryptionBox.SelectedIndex, serializer }); new Thread(new ParameterizedThreadStart(ProgressBarThread)).Start(serializer); } private void imgToolStripMenuItem1_Click(object sender, EventArgs e) { string outPath = GetOutputDirectory(); if (outPath == string.Empty) { MessageBox.Show(Properties.Resources.MainWzExportError, Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } List<WzDirectory> dirs = new List<WzDirectory>(); List<WzImage> imgs = new List<WzImage>(); foreach (WzNode node in MainPanel.DataTree.SelectedNodes) { if (node.Tag is WzDirectory) { dirs.Add((WzDirectory)node.Tag); } else if (node.Tag is WzImage) { imgs.Add((WzImage)node.Tag); } } WzImgSerializer serializer = new WzImgSerializer(); threadDone = false; runningThread = new Thread(new ParameterizedThreadStart(RunWzImgDirsExtraction)); runningThread.Start((object)new object[] { dirs, imgs, outPath, serializer }); new Thread(new ParameterizedThreadStart(ProgressBarThread)).Start(serializer); } private void pNGsToolStripMenuItem_Click(object sender, EventArgs e) { string outPath = GetOutputDirectory(); if (outPath == string.Empty) { MessageBox.Show(Properties.Resources.MainWzExportError, Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } List<WzObject> objs = new List<WzObject>(); foreach (WzNode node in MainPanel.DataTree.SelectedNodes) { if (node.Tag is WzObject) { objs.Add((WzObject)node.Tag); } } WzPngMp3Serializer serializer = new WzPngMp3Serializer(); threadDone = false; runningThread = new Thread(new ParameterizedThreadStart(RunWzObjExtraction)); runningThread.Start((object)new object[] { objs, outPath, serializer }); new Thread(new ParameterizedThreadStart(ProgressBarThread)).Start(serializer); } /// <summary> /// Export to private server toolstrip /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void privateServerToolStripMenuItem_Click(object sender, EventArgs e) { string outPath = GetOutputDirectory(); if (outPath == string.Empty) { MessageBox.Show(Properties.Resources.MainWzExportError, Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } List<WzDirectory> dirs = new List<WzDirectory>(); List<WzImage> imgs = new List<WzImage>(); foreach (WzNode node in MainPanel.DataTree.SelectedNodes) { if (node.Tag is WzDirectory) dirs.Add((WzDirectory)node.Tag); else if (node.Tag is WzImage) imgs.Add((WzImage)node.Tag); else if (node.Tag is WzFile) { dirs.Add(((WzFile)node.Tag).WzDirectory); } } WzClassicXmlSerializer serializer = new WzClassicXmlSerializer( Program.ConfigurationManager.UserSettings.Indentation, Program.ConfigurationManager.UserSettings.LineBreakType, false); threadDone = false; runningThread = new Thread(new ParameterizedThreadStart(RunWzImgDirsExtraction)); runningThread.Start((object)new object[] { dirs, imgs, outPath, serializer }); new Thread(new ParameterizedThreadStart(ProgressBarThread)).Start(serializer); } private void classicToolStripMenuItem_Click(object sender, EventArgs e) { string outPath = GetOutputDirectory(); if (outPath == string.Empty) { MessageBox.Show(Properties.Resources.MainWzExportError, Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } List<WzDirectory> dirs = new List<WzDirectory>(); List<WzImage> imgs = new List<WzImage>(); foreach (WzNode node in MainPanel.DataTree.SelectedNodes) { if (node.Tag is WzDirectory) dirs.Add((WzDirectory)node.Tag); else if (node.Tag is WzImage) imgs.Add((WzImage)node.Tag); else if (node.Tag is WzFile) { dirs.Add(((WzFile)node.Tag).WzDirectory); } } WzClassicXmlSerializer serializer = new WzClassicXmlSerializer( Program.ConfigurationManager.UserSettings.Indentation, Program.ConfigurationManager.UserSettings.LineBreakType, true); threadDone = false; runningThread = new Thread(new ParameterizedThreadStart(RunWzImgDirsExtraction)); runningThread.Start((object)new object[] { dirs, imgs, outPath, serializer }); new Thread(new ParameterizedThreadStart(ProgressBarThread)).Start(serializer); } private void newToolStripMenuItem1_Click(object sender, EventArgs e) { SaveFileDialog dialog = new SaveFileDialog() { Title = HaRepacker.Properties.Resources.SelectOutXml, Filter = string.Format("{0}|*.xml", HaRepacker.Properties.Resources.XmlFilter) }; if (dialog.ShowDialog() != DialogResult.OK) return; List<WzObject> objs = new List<WzObject>(); foreach (WzNode node in MainPanel.DataTree.SelectedNodes) { if (node.Tag is WzObject) objs.Add((WzObject)node.Tag); } WzNewXmlSerializer serializer = new WzNewXmlSerializer( Program.ConfigurationManager.UserSettings.Indentation, Program.ConfigurationManager.UserSettings.LineBreakType); threadDone = false; runningThread = new Thread(new ParameterizedThreadStart(RunWzObjExtraction)); runningThread.Start((object)new object[] { objs, dialog.FileName, serializer }); new Thread(new ParameterizedThreadStart(ProgressBarThread)).Start(serializer); } private void AbortButton_Click(object sender, EventArgs e) { if (Warning.Warn(HaRepacker.Properties.Resources.MainConfirmAbort)) { threadDone = true; runningThread.Abort(); } } #region Extras private bool ValidAnimation(WzObject prop) { if (!(prop is WzSubProperty)) return false; WzSubProperty castedProp = (WzSubProperty)prop; List<WzCanvasProperty> props = new List<WzCanvasProperty>(castedProp.WzProperties.Count); int foo; foreach (WzImageProperty subprop in castedProp.WzProperties) { if (!(subprop is WzCanvasProperty)) continue; if (!int.TryParse(subprop.Name, out foo)) return false; props.Add((WzCanvasProperty)subprop); } if (props.Count < 2) return false; props.Sort(new Comparison<WzCanvasProperty>(AnimationBuilder.PropertySorter)); for (int i = 0; i < props.Count; i++) if (i.ToString() != props[i].Name) return false; return true; } private void aPNGToolStripMenuItem_Click(object sender, EventArgs e) { if (MainPanel.DataTree.SelectedNode == null) return; if (!ValidAnimation((WzObject)MainPanel.DataTree.SelectedNode.Tag)) Warning.Error(HaRepacker.Properties.Resources.MainAnimationFail); else { SaveFileDialog dialog = new SaveFileDialog() { Title = HaRepacker.Properties.Resources.SelectOutApng, Filter = string.Format("{0}|*.png", HaRepacker.Properties.Resources.ApngFilter) }; if (dialog.ShowDialog() != DialogResult.OK) { return; } AnimationBuilder.ExtractAnimation((WzSubProperty)MainPanel.DataTree.SelectedNode.Tag, dialog.FileName, Program.ConfigurationManager.UserSettings.UseApngIncompatibilityFrame); } } /// <summary> /// Wz string searcher tool /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void toolStripMenuItem_searchWzStrings_Click(object sender, EventArgs e) { // Map name load string loadedWzVersion; WzStringSearchFormDataCache dataCache = new WzStringSearchFormDataCache((WzMapleVersion)encryptionBox.SelectedIndex); if (dataCache.OpenBaseWZFile(out loadedWzVersion)) { WzStringSearchForm form = new WzStringSearchForm(dataCache, loadedWzVersion); form.Show(); } } /// <summary> /// Get packet encryption keys from ZLZ.dll /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void toolStripMenuItem_WzEncryption_Click(object sender, EventArgs e) { ZLZPacketEncryptionKeyForm form = new ZLZPacketEncryptionKeyForm(); bool opened = form.OpenZLZDllFile(); if (opened) form.Show(); } #endregion #region Image directory add /// <summary> /// Add WzDirectory /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void wzDirectoryToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.AddWzDirectoryToSelectedNode(MainPanel.DataTree.SelectedNode); } /// <summary> /// Add WzImage /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void wzImageToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.AddWzImageToSelectedNode(MainPanel.DataTree.SelectedNode); } /// <summary> /// Add WzByte /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void wzByteFloatPropertyToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.AddWzByteFloatToSelectedNode(MainPanel.DataTree.SelectedNode); } /// <summary> /// Add new canvas toolstrip /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void wzCanvasPropertyToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.AddWzCanvasToSelectedNode(MainPanel.DataTree.SelectedNode); } /// <summary> /// Add WzIntProperty /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void wzCompressedIntPropertyToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.AddWzCompressedIntToSelectedNode(MainPanel.DataTree.SelectedNode); } /// <summary> /// Add WzLongProperty /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void wzLongPropertyToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.AddWzLongToSelectedNode(MainPanel.DataTree.SelectedNode); } /// <summary> /// Add WzConvexProperty /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void wzConvexPropertyToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.AddWzConvexPropertyToSelectedNode(MainPanel.DataTree.SelectedNode); } /// <summary> /// Add WzDoubleProperty /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void wzDoublePropertyToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.AddWzDoublePropertyToSelectedNode(MainPanel.DataTree.SelectedNode); } /// <summary> /// Add WzNullProperty /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void wzNullPropertyToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.AddWzNullPropertyToSelectedNode(MainPanel.DataTree.SelectedNode); } /// <summary> /// Add WzSoundProperty /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void wzSoundPropertyToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.AddWzSoundPropertyToSelectedNode(MainPanel.DataTree.SelectedNode); } /// <summary> /// Add WzStringProperty /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void wzStringPropertyToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.AddWzStringPropertyToSelectedIndex(MainPanel.DataTree.SelectedNode); } /// <summary> /// Add WzSubProperty /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void wzSubPropertyToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.AddWzSubPropertyToSelectedIndex(MainPanel.DataTree.SelectedNode); } /// <summary> /// Add WzShortProperty /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void wzUnsignedShortPropertyToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.AddWzUnsignedShortPropertyToSelectedIndex(MainPanel.DataTree.SelectedNode); } /// <summary> /// Add WzUOLProperty /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void wzUolPropertyToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.AddWzUOLPropertyToSelectedIndex(MainPanel.DataTree.SelectedNode); } /// <summary> /// Add WzVectorProperty /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void wzVectorPropertyToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.AddWzVectorPropertyToSelectedIndex(MainPanel.DataTree.SelectedNode); } #endregion private void expandAllToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.DataTree.ExpandAll(); } private void collapseAllToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.DataTree.CollapseAll(); } private void xMLToolStripMenuItem2_Click(object sender, EventArgs e) { if (MainPanel.DataTree.SelectedNode == null || (!(MainPanel.DataTree.SelectedNode.Tag is WzDirectory) && !(MainPanel.DataTree.SelectedNode.Tag is WzFile) && !(MainPanel.DataTree.SelectedNode.Tag is IPropertyContainer))) return; WzFile wzFile = ((WzObject)MainPanel.DataTree.SelectedNode.Tag).WzFileParent; if (!(wzFile is WzFile)) return; OpenFileDialog dialog = new OpenFileDialog() { Title = HaRepacker.Properties.Resources.SelectXml, Filter = string.Format("{0}|*.xml", HaRepacker.Properties.Resources.XmlFilter), Multiselect = true }; if (dialog.ShowDialog() != DialogResult.OK) return; WzXmlDeserializer deserializer = new WzXmlDeserializer(true, WzTool.GetIvByMapleVersion(wzFile.MapleVersion)); yesToAll = false; noToAll = false; threadDone = false; runningThread = new Thread(new ParameterizedThreadStart(WzImporterThread)); runningThread.Start(new object[] { deserializer, dialog.FileNames, MainPanel.DataTree.SelectedNode, null }); new Thread(new ParameterizedThreadStart(ProgressBarThread)).Start(deserializer); } private delegate void InsertWzNode(WzNode node, WzNode parent); private void InsertWzNodeCallback(WzNode node, WzNode parent) { WzNode child = WzNode.GetChildNode(parent, node.Text); if (child != null) { if (ShowReplaceDialog(node.Text)) child.Delete(); else return; } parent.AddNode(node); } private void InsertWzNodeThreadSafe(WzNode node, WzNode parent) { MainPanel.Dispatcher.Invoke(() => { InsertWzNodeCallback(node, parent); }); /* if (MainPanel.InvokeRequired) MainPanel.Invoke(new InsertWzNode(InsertWzNodeCallback), node, parent); else InsertWzNodeCallback(node, parent);*/ } private bool yesToAll = false; private bool noToAll = false; private ReplaceResult result; private bool ShowReplaceDialog(string name) { if (yesToAll) return true; else if (noToAll) return false; else { ReplaceBox.Show(name, out result); switch (result) { case ReplaceResult.NoToAll: noToAll = true; return false; case ReplaceResult.No: return false; case ReplaceResult.YesToAll: yesToAll = true; return true; case ReplaceResult.Yes: return true; } } throw new Exception("cant get here anyway"); } private void WzImporterThread(object param) { ChangeApplicationState(false); object[] arr = (object[])param; ProgressingWzSerializer deserializer = (ProgressingWzSerializer)arr[0]; string[] files = (string[])arr[1]; WzNode parent = (WzNode)arr[2]; byte[] iv = (byte[])arr[3]; WzObject parentObj = (WzObject)parent.Tag; if (parentObj is WzFile) parentObj = ((WzFile)parentObj).WzDirectory; UpdateProgressBar(MainPanel.mainProgressBar, files.Length, true, true); foreach (string file in files) { List<WzObject> objs; try { if (deserializer is WzXmlDeserializer) objs = ((WzXmlDeserializer)deserializer).ParseXML(file); else { bool successfullyParsedImage; objs = new List<WzObject> { ((WzImgDeserializer)deserializer).WzImageFromIMGFile(file, iv, Path.GetFileName(file), out successfullyParsedImage) }; if (!successfullyParsedImage) { MessageBox.Show( string.Format(HaRepacker.Properties.Resources.MainErrorImportingWzImageFile, file), HaRepacker.Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning); continue; } } } catch (ThreadAbortException) { return; } catch (Exception e) { Warning.Error(string.Format(HaRepacker.Properties.Resources.MainInvalidFileError, file, e.Message)); UpdateProgressBar(MainPanel.mainProgressBar, 1, false, false); continue; } foreach (WzObject obj in objs) { if (((obj is WzDirectory || obj is WzImage) && parentObj is WzDirectory) || (obj is WzImageProperty && parentObj is IPropertyContainer)) { WzNode node = new WzNode(obj, true); InsertWzNodeThreadSafe(node, parent); } } UpdateProgressBar(MainPanel.mainProgressBar, 1, false, false); } threadDone = true; } private void iMGToolStripMenuItem2_Click(object sender, EventArgs e) { if (MainPanel.DataTree.SelectedNode == null || (!(MainPanel.DataTree.SelectedNode.Tag is WzDirectory) && !(MainPanel.DataTree.SelectedNode.Tag is WzFile) && !(MainPanel.DataTree.SelectedNode.Tag is IPropertyContainer))) return; WzFile wzFile = ((WzObject)MainPanel.DataTree.SelectedNode.Tag).WzFileParent; if (!(wzFile is WzFile)) return; OpenFileDialog dialog = new OpenFileDialog() { Title = HaRepacker.Properties.Resources.SelectWzImg, Filter = string.Format("{0}|*.img", HaRepacker.Properties.Resources.WzImgFilter), Multiselect = true }; if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK) return; WzMapleVersion wzImageImportVersion = WzMapleVersion.BMS; bool input = WzMapleVersionInputBox.Show(HaRepacker.Properties.Resources.InteractionWzMapleVersionTitle, out wzImageImportVersion); if (!input) return; byte[] iv = WzTool.GetIvByMapleVersion(wzImageImportVersion); WzImgDeserializer deserializer = new WzImgDeserializer(true); yesToAll = false; noToAll = false; threadDone = false; runningThread = new Thread(new ParameterizedThreadStart(WzImporterThread)); runningThread.Start( new object[] { deserializer, dialog.FileNames, MainPanel.DataTree.SelectedNode, iv }); new Thread(new ParameterizedThreadStart(ProgressBarThread)).Start(deserializer); } private void searchToolStripMenuItem_Click(object sender, EventArgs e) { //MainPanel.findStrip.Visible = true; } private static readonly string HelpFile = "Help.htm"; private void viewHelpToolStripMenuItem_Click(object sender, EventArgs e) { string helpPath = Path.Combine(Application.StartupPath, HelpFile); if (File.Exists(helpPath)) Help.ShowHelp(this, HelpFile); else Warning.Error(string.Format(HaRepacker.Properties.Resources.MainHelpOpenFail, HelpFile)); } private void copyToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.DoCopy(); } private void pasteToolStripMenuItem_Click(object sender, EventArgs e) { MainPanel.DoPaste(); } } }
39.416181
238
0.547736
[ "MPL-2.0" ]
Riremito/HaRepackerJ
HaRepacker/GUI/MainForm.cs
60,900
C#
namespace PCMgr.WorkWindow { partial class FormDetalsistHeaders { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormDetalsistHeaders)); this.labelTip = new System.Windows.Forms.Label(); this.buttonCancel = new System.Windows.Forms.Button(); this.buttonOk = new System.Windows.Forms.Button(); this.listItems = new System.Windows.Forms.ListView(); this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.SuspendLayout(); // // labelTip // resources.ApplyResources(this.labelTip, "labelTip"); this.labelTip.Name = "labelTip"; // // buttonCancel // resources.ApplyResources(this.buttonCancel, "buttonCancel"); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.UseVisualStyleBackColor = true; this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); // // buttonOk // resources.ApplyResources(this.buttonOk, "buttonOk"); this.buttonOk.Name = "buttonOk"; this.buttonOk.UseVisualStyleBackColor = true; this.buttonOk.Click += new System.EventHandler(this.buttonOk_Click); // // listItems // resources.ApplyResources(this.listItems, "listItems"); this.listItems.CheckBoxes = true; this.listItems.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1}); this.listItems.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; this.listItems.Name = "listItems"; this.listItems.UseCompatibleStateImageBehavior = false; this.listItems.View = System.Windows.Forms.View.Details; // // columnHeader1 // resources.ApplyResources(this.columnHeader1, "columnHeader1"); // // FormDetalsistHeaders // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.listItems); this.Controls.Add(this.buttonOk); this.Controls.Add(this.buttonCancel); this.Controls.Add(this.labelTip); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FormDetalsistHeaders"; this.ShowIcon = false; this.ShowInTaskbar = false; this.Load += new System.EventHandler(this.FormDetalsistHeaders_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label labelTip; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.Button buttonOk; private System.Windows.Forms.ListView listItems; private System.Windows.Forms.ColumnHeader columnHeader1; } }
41.079208
152
0.596288
[ "MIT" ]
717021/PCMgr
TaskMgr/WorkWindow/FormDetalsistHeaders.Designer.cs
4,151
C#
//------------------------------------------------------------ // Game Framework // Copyright © 2013-2020 Jiang Yin. All rights reserved. // Homepage: https://gameframework.cn/ // Feedback: mailto:ellan@gameframework.cn //------------------------------------------------------------ using GameFramework.FileSystem; using GameFramework.ObjectPool; using System; using System.Collections.Generic; using System.IO; namespace GameFramework.Resource { internal sealed partial class ResourceManager : GameFrameworkModule, IResourceManager { /// <summary> /// 加载资源器。 /// </summary> private sealed partial class ResourceLoader { private const int CachedHashBytesLength = 4; private readonly ResourceManager m_ResourceManager; private readonly TaskPool<LoadResourceTaskBase> m_TaskPool; private readonly Dictionary<object, int> m_AssetDependencyCount; private readonly Dictionary<object, int> m_ResourceDependencyCount; private readonly Dictionary<object, object> m_AssetToResourceMap; private readonly Dictionary<string, object> m_SceneToAssetMap; private readonly LoadBytesCallbacks m_LoadBytesCallbacks; private readonly byte[] m_CachedHashBytes; private IObjectPool<AssetObject> m_AssetPool; private IObjectPool<ResourceObject> m_ResourcePool; /// <summary> /// 初始化加载资源器的新实例。 /// </summary> /// <param name="resourceManager">资源管理器。</param> public ResourceLoader(ResourceManager resourceManager) { m_ResourceManager = resourceManager; m_TaskPool = new TaskPool<LoadResourceTaskBase>(); m_AssetDependencyCount = new Dictionary<object, int>(); m_ResourceDependencyCount = new Dictionary<object, int>(); m_AssetToResourceMap = new Dictionary<object, object>(); m_SceneToAssetMap = new Dictionary<string, object>(StringComparer.Ordinal); m_LoadBytesCallbacks = new LoadBytesCallbacks(OnLoadBinarySuccess, OnLoadBinaryFailure); m_CachedHashBytes = new byte[CachedHashBytesLength]; m_AssetPool = null; m_ResourcePool = null; } /// <summary> /// 获取加载资源代理总数量。 /// </summary> public int TotalAgentCount { get { return m_TaskPool.TotalAgentCount; } } /// <summary> /// 获取可用加载资源代理数量。 /// </summary> public int FreeAgentCount { get { return m_TaskPool.FreeAgentCount; } } /// <summary> /// 获取工作中加载资源代理数量。 /// </summary> public int WorkingAgentCount { get { return m_TaskPool.WorkingAgentCount; } } /// <summary> /// 获取等待加载资源任务数量。 /// </summary> public int WaitingTaskCount { get { return m_TaskPool.WaitingTaskCount; } } /// <summary> /// 获取或设置资源对象池自动释放可释放对象的间隔秒数。 /// </summary> public float AssetAutoReleaseInterval { get { return m_AssetPool.AutoReleaseInterval; } set { m_AssetPool.AutoReleaseInterval = value; } } /// <summary> /// 获取或设置资源对象池的容量。 /// </summary> public int AssetCapacity { get { return m_AssetPool.Capacity; } set { m_AssetPool.Capacity = value; } } /// <summary> /// 获取或设置资源对象池对象过期秒数。 /// </summary> public float AssetExpireTime { get { return m_AssetPool.ExpireTime; } set { m_AssetPool.ExpireTime = value; } } /// <summary> /// 获取或设置资源对象池的优先级。 /// </summary> public int AssetPriority { get { return m_AssetPool.Priority; } set { m_AssetPool.Priority = value; } } /// <summary> /// 获取或设置资源对象池自动释放可释放对象的间隔秒数。 /// </summary> public float ResourceAutoReleaseInterval { get { return m_ResourcePool.AutoReleaseInterval; } set { m_ResourcePool.AutoReleaseInterval = value; } } /// <summary> /// 获取或设置资源对象池的容量。 /// </summary> public int ResourceCapacity { get { return m_ResourcePool.Capacity; } set { m_ResourcePool.Capacity = value; } } /// <summary> /// 获取或设置资源对象池对象过期秒数。 /// </summary> public float ResourceExpireTime { get { return m_ResourcePool.ExpireTime; } set { m_ResourcePool.ExpireTime = value; } } /// <summary> /// 获取或设置资源对象池的优先级。 /// </summary> public int ResourcePriority { get { return m_ResourcePool.Priority; } set { m_ResourcePool.Priority = value; } } /// <summary> /// 加载资源器轮询。 /// </summary> /// <param name="elapseSeconds">逻辑流逝时间,以秒为单位。</param> /// <param name="realElapseSeconds">真实流逝时间,以秒为单位。</param> public void Update(float elapseSeconds, float realElapseSeconds) { m_TaskPool.Update(elapseSeconds, realElapseSeconds); } /// <summary> /// 关闭并清理加载资源器。 /// </summary> public void Shutdown() { m_TaskPool.Shutdown(); m_AssetDependencyCount.Clear(); m_ResourceDependencyCount.Clear(); m_AssetToResourceMap.Clear(); m_SceneToAssetMap.Clear(); LoadResourceAgent.Clear(); } /// <summary> /// 设置对象池管理器。 /// </summary> /// <param name="objectPoolManager">对象池管理器。</param> public void SetObjectPoolManager(IObjectPoolManager objectPoolManager) { m_AssetPool = objectPoolManager.CreateMultiSpawnObjectPool<AssetObject>("Asset Pool"); m_ResourcePool = objectPoolManager.CreateMultiSpawnObjectPool<ResourceObject>("Resource Pool"); } /// <summary> /// 增加加载资源代理辅助器。 /// </summary> /// <param name="loadResourceAgentHelper">要增加的加载资源代理辅助器。</param> /// <param name="resourceHelper">资源辅助器。</param> /// <param name="readOnlyPath">资源只读区路径。</param> /// <param name="readWritePath">资源读写区路径。</param> /// <param name="decryptResourceCallback">要设置的解密资源回调函数。</param> public void AddLoadResourceAgentHelper(ILoadResourceAgentHelper loadResourceAgentHelper, IResourceHelper resourceHelper, string readOnlyPath, string readWritePath, DecryptResourceCallback decryptResourceCallback) { if (m_AssetPool == null || m_ResourcePool == null) { throw new GameFrameworkException("You must set object pool manager first."); } LoadResourceAgent agent = new LoadResourceAgent(loadResourceAgentHelper, resourceHelper, this, readOnlyPath, readWritePath, decryptResourceCallback ?? DefaultDecryptResourceCallback); m_TaskPool.AddAgent(agent); } /// <summary> /// 检查资源是否存在。 /// </summary> /// <param name="assetName">要检查资源的名称。</param> /// <returns>检查资源是否存在的结果。</returns> public HasAssetResult HasAsset(string assetName) { ResourceInfo resourceInfo = GetResourceInfo(assetName); if (resourceInfo == null) { return HasAssetResult.NotExist; } if (!resourceInfo.Ready && m_ResourceManager.m_ResourceMode != ResourceMode.UpdatableWhilePlaying) { return HasAssetResult.NotReady; } if (resourceInfo.UseFileSystem) { return resourceInfo.IsLoadFromBinary ? HasAssetResult.BinaryOnFileSystem : HasAssetResult.AssetOnFileSystem; } else { return resourceInfo.IsLoadFromBinary ? HasAssetResult.BinaryOnDisk : HasAssetResult.AssetOnDisk; } } /// <summary> /// 异步加载资源。 /// </summary> /// <param name="assetName">要加载资源的名称。</param> /// <param name="assetType">要加载资源的类型。</param> /// <param name="priority">加载资源的优先级。</param> /// <param name="loadAssetCallbacks">加载资源回调函数集。</param> /// <param name="userData">用户自定义数据。</param> public void LoadAsset(string assetName, Type assetType, int priority, LoadAssetCallbacks loadAssetCallbacks, object userData) { ResourceInfo resourceInfo = null; string[] dependencyAssetNames = null; if (!CheckAsset(assetName, out resourceInfo, out dependencyAssetNames)) { string errorMessage = Utility.Text.Format("Can not load asset '{0}'.", assetName); if (loadAssetCallbacks.LoadAssetFailureCallback != null) { loadAssetCallbacks.LoadAssetFailureCallback(assetName, resourceInfo != null && !resourceInfo.Ready ? LoadResourceStatus.NotReady : LoadResourceStatus.NotExist, errorMessage, userData); return; } throw new GameFrameworkException(errorMessage); } if (resourceInfo.IsLoadFromBinary) { string errorMessage = Utility.Text.Format("Can not load asset '{0}' which is a binary asset.", assetName); if (loadAssetCallbacks.LoadAssetFailureCallback != null) { loadAssetCallbacks.LoadAssetFailureCallback(assetName, LoadResourceStatus.TypeError, errorMessage, userData); return; } throw new GameFrameworkException(errorMessage); } LoadAssetTask mainTask = LoadAssetTask.Create(assetName, assetType, priority, resourceInfo, dependencyAssetNames, loadAssetCallbacks, userData); foreach (string dependencyAssetName in dependencyAssetNames) { if (!LoadDependencyAsset(dependencyAssetName, priority, mainTask, userData)) { string errorMessage = Utility.Text.Format("Can not load dependency asset '{0}' when load asset '{1}'.", dependencyAssetName, assetName); if (loadAssetCallbacks.LoadAssetFailureCallback != null) { loadAssetCallbacks.LoadAssetFailureCallback(assetName, LoadResourceStatus.DependencyError, errorMessage, userData); return; } throw new GameFrameworkException(errorMessage); } } m_TaskPool.AddTask(mainTask); if (!resourceInfo.Ready) { m_ResourceManager.UpdateResource(resourceInfo.ResourceName); } } /// <summary> /// 卸载资源。 /// </summary> /// <param name="asset">要卸载的资源。</param> public void UnloadAsset(object asset) { m_AssetPool.Unspawn(asset); } /// <summary> /// 异步加载场景。 /// </summary> /// <param name="sceneAssetName">要加载场景资源的名称。</param> /// <param name="priority">加载场景资源的优先级。</param> /// <param name="loadSceneCallbacks">加载场景回调函数集。</param> /// <param name="userData">用户自定义数据。</param> public void LoadScene(string sceneAssetName, int priority, LoadSceneCallbacks loadSceneCallbacks, object userData) { ResourceInfo resourceInfo = null; string[] dependencyAssetNames = null; if (!CheckAsset(sceneAssetName, out resourceInfo, out dependencyAssetNames)) { string errorMessage = Utility.Text.Format("Can not load scene '{0}'.", sceneAssetName); if (loadSceneCallbacks.LoadSceneFailureCallback != null) { loadSceneCallbacks.LoadSceneFailureCallback(sceneAssetName, resourceInfo != null && !resourceInfo.Ready ? LoadResourceStatus.NotReady : LoadResourceStatus.NotExist, errorMessage, userData); return; } throw new GameFrameworkException(errorMessage); } if (resourceInfo.IsLoadFromBinary) { string errorMessage = Utility.Text.Format("Can not load scene asset '{0}' which is a binary asset.", sceneAssetName); if (loadSceneCallbacks.LoadSceneFailureCallback != null) { loadSceneCallbacks.LoadSceneFailureCallback(sceneAssetName, LoadResourceStatus.TypeError, errorMessage, userData); return; } throw new GameFrameworkException(errorMessage); } LoadSceneTask mainTask = LoadSceneTask.Create(sceneAssetName, priority, resourceInfo, dependencyAssetNames, loadSceneCallbacks, userData); foreach (string dependencyAssetName in dependencyAssetNames) { if (!LoadDependencyAsset(dependencyAssetName, priority, mainTask, userData)) { string errorMessage = Utility.Text.Format("Can not load dependency asset '{0}' when load scene '{1}'.", dependencyAssetName, sceneAssetName); if (loadSceneCallbacks.LoadSceneFailureCallback != null) { loadSceneCallbacks.LoadSceneFailureCallback(sceneAssetName, LoadResourceStatus.DependencyError, errorMessage, userData); return; } throw new GameFrameworkException(errorMessage); } } m_TaskPool.AddTask(mainTask); if (!resourceInfo.Ready) { m_ResourceManager.UpdateResource(resourceInfo.ResourceName); } } /// <summary> /// 异步卸载场景。 /// </summary> /// <param name="sceneAssetName">要卸载场景资源的名称。</param> /// <param name="unloadSceneCallbacks">卸载场景回调函数集。</param> /// <param name="userData">用户自定义数据。</param> public void UnloadScene(string sceneAssetName, UnloadSceneCallbacks unloadSceneCallbacks, object userData) { if (m_ResourceManager.m_ResourceHelper == null) { throw new GameFrameworkException("You must set resource helper first."); } object asset = null; if (m_SceneToAssetMap.TryGetValue(sceneAssetName, out asset)) { m_SceneToAssetMap.Remove(sceneAssetName); m_AssetPool.Unspawn(asset); } else { throw new GameFrameworkException(Utility.Text.Format("Can not find asset of scene '{0}'.", sceneAssetName)); } m_ResourceManager.m_ResourceHelper.UnloadScene(sceneAssetName, unloadSceneCallbacks, userData); } /// <summary> /// 获取二进制资源的实际路径。 /// </summary> /// <param name="binaryAssetName">要获取实际路径的二进制资源的名称。</param> /// <returns>二进制资源的实际路径。</returns> /// <remarks>此方法仅适用于二进制资源存储在磁盘(而非文件系统)中的情况。若二进制资源存储在文件系统中时,返回值将始终为空。</remarks> public string GetBinaryPath(string binaryAssetName) { ResourceInfo resourceInfo = GetResourceInfo(binaryAssetName); if (resourceInfo == null) { return null; } if (!resourceInfo.Ready) { return null; } if (!resourceInfo.IsLoadFromBinary) { return null; } if (resourceInfo.UseFileSystem) { return null; } return Utility.Path.GetRegularPath(Path.Combine(resourceInfo.StorageInReadOnly ? m_ResourceManager.m_ReadOnlyPath : m_ResourceManager.m_ReadWritePath, resourceInfo.ResourceName.FullName)); } /// <summary> /// 获取二进制资源的实际路径。 /// </summary> /// <param name="binaryAssetName">要获取实际路径的二进制资源的名称。</param> /// <param name="storageInReadOnly">二进制资源是否存储在只读区中。</param> /// <param name="storageInFileSystem">二进制资源是否存储在文件系统中。</param> /// <param name="relativePath">二进制资源或存储二进制资源的文件系统,相对于只读区或者读写区的相对路径。</param> /// <param name="fileName">若二进制资源存储在文件系统中,则指示二进制资源在文件系统中的名称,否则此参数返回空。</param> /// <returns>是否获取二进制资源的实际路径成功。</returns> public bool GetBinaryPath(string binaryAssetName, out bool storageInReadOnly, out bool storageInFileSystem, out string relativePath, out string fileName) { storageInReadOnly = false; storageInFileSystem = false; relativePath = null; fileName = null; ResourceInfo resourceInfo = GetResourceInfo(binaryAssetName); if (resourceInfo == null) { return false; } if (!resourceInfo.Ready) { return false; } if (!resourceInfo.IsLoadFromBinary) { return false; } storageInReadOnly = resourceInfo.StorageInReadOnly; if (resourceInfo.UseFileSystem) { storageInFileSystem = true; relativePath = Utility.Text.Format("{0}.{1}", resourceInfo.FileSystemName, DefaultExtension); fileName = resourceInfo.ResourceName.FullName; } else { relativePath = resourceInfo.ResourceName.FullName; } return true; } /// <summary> /// 获取二进制资源的长度。 /// </summary> /// <param name="binaryAssetName">要获取长度的二进制资源的名称。</param> /// <returns>二进制资源的长度。</returns> public int GetBinaryLength(string binaryAssetName) { ResourceInfo resourceInfo = GetResourceInfo(binaryAssetName); if (resourceInfo == null) { return -1; } if (!resourceInfo.Ready) { return -1; } if (!resourceInfo.IsLoadFromBinary) { return -1; } return resourceInfo.Length; } /// <summary> /// 异步加载二进制资源。 /// </summary> /// <param name="binaryAssetName">要加载二进制资源的名称。</param> /// <param name="loadBinaryCallbacks">加载二进制资源回调函数集。</param> /// <param name="userData">用户自定义数据。</param> public void LoadBinary(string binaryAssetName, LoadBinaryCallbacks loadBinaryCallbacks, object userData) { ResourceInfo resourceInfo = GetResourceInfo(binaryAssetName); if (resourceInfo == null) { string errorMessage = Utility.Text.Format("Can not load binary '{0}' which is not exist.", binaryAssetName); if (loadBinaryCallbacks.LoadBinaryFailureCallback != null) { loadBinaryCallbacks.LoadBinaryFailureCallback(binaryAssetName, LoadResourceStatus.NotExist, errorMessage, userData); return; } throw new GameFrameworkException(errorMessage); } if (!resourceInfo.Ready) { string errorMessage = Utility.Text.Format("Can not load binary '{0}' which is not ready.", binaryAssetName); if (loadBinaryCallbacks.LoadBinaryFailureCallback != null) { loadBinaryCallbacks.LoadBinaryFailureCallback(binaryAssetName, LoadResourceStatus.NotReady, errorMessage, userData); return; } throw new GameFrameworkException(errorMessage); } if (!resourceInfo.IsLoadFromBinary) { string errorMessage = Utility.Text.Format("Can not load binary '{0}' which is not a binary asset.", binaryAssetName); if (loadBinaryCallbacks.LoadBinaryFailureCallback != null) { loadBinaryCallbacks.LoadBinaryFailureCallback(binaryAssetName, LoadResourceStatus.TypeError, errorMessage, userData); return; } throw new GameFrameworkException(errorMessage); } if (resourceInfo.UseFileSystem) { loadBinaryCallbacks.LoadBinarySuccessCallback(binaryAssetName, LoadBinaryFromFileSystem(binaryAssetName), 0f, userData); } else { string path = Utility.Path.GetRemotePath(Path.Combine(resourceInfo.StorageInReadOnly ? m_ResourceManager.m_ReadOnlyPath : m_ResourceManager.m_ReadWritePath, resourceInfo.ResourceName.FullName)); m_ResourceManager.m_ResourceHelper.LoadBytes(path, m_LoadBytesCallbacks, LoadBinaryInfo.Create(binaryAssetName, resourceInfo, loadBinaryCallbacks, userData)); } } /// <summary> /// 从文件系统中加载二进制资源。 /// </summary> /// <param name="binaryAssetName">要加载二进制资源的名称。</param> /// <returns>存储加载二进制资源的二进制流。</returns> public byte[] LoadBinaryFromFileSystem(string binaryAssetName) { ResourceInfo resourceInfo = GetResourceInfo(binaryAssetName); if (resourceInfo == null) { throw new GameFrameworkException(Utility.Text.Format("Can not load binary '{0}' from file system which is not exist.", binaryAssetName)); } if (!resourceInfo.Ready) { throw new GameFrameworkException(Utility.Text.Format("Can not load binary '{0}' from file system which is not ready.", binaryAssetName)); } if (!resourceInfo.IsLoadFromBinary) { throw new GameFrameworkException(Utility.Text.Format("Can not load binary '{0}' from file system which is not a binary asset.", binaryAssetName)); } if (!resourceInfo.UseFileSystem) { throw new GameFrameworkException(Utility.Text.Format("Can not load binary '{0}' from file system which is not use file system.", binaryAssetName)); } IFileSystem fileSystem = m_ResourceManager.GetFileSystem(resourceInfo.FileSystemName, resourceInfo.StorageInReadOnly); byte[] bytes = fileSystem.ReadFile(resourceInfo.ResourceName.FullName); if (bytes == null) { return null; } if (resourceInfo.LoadType == LoadType.LoadFromBinaryAndQuickDecrypt || resourceInfo.LoadType == LoadType.LoadFromBinaryAndDecrypt) { DecryptResourceCallback decryptResourceCallback = m_ResourceManager.m_DecryptResourceCallback ?? DefaultDecryptResourceCallback; decryptResourceCallback(bytes, 0, bytes.Length, resourceInfo.ResourceName.Name, resourceInfo.ResourceName.Variant, resourceInfo.ResourceName.Extension, resourceInfo.StorageInReadOnly, resourceInfo.FileSystemName, (byte)resourceInfo.LoadType, resourceInfo.Length, resourceInfo.HashCode); } return bytes; } /// <summary> /// 从文件系统中加载二进制资源。 /// </summary> /// <param name="binaryAssetName">要加载二进制资源的名称。</param> /// <param name="buffer">存储加载二进制资源的二进制流。</param> /// <param name="startIndex">存储加载二进制资源的二进制流的起始位置。</param> /// <param name="length">存储加载二进制资源的二进制流的长度。</param> /// <returns>实际加载了多少字节。</returns> public int LoadBinaryFromFileSystem(string binaryAssetName, byte[] buffer, int startIndex, int length) { ResourceInfo resourceInfo = GetResourceInfo(binaryAssetName); if (resourceInfo == null) { throw new GameFrameworkException(Utility.Text.Format("Can not load binary '{0}' from file system which is not exist.", binaryAssetName)); } if (!resourceInfo.Ready) { throw new GameFrameworkException(Utility.Text.Format("Can not load binary '{0}' from file system which is not ready.", binaryAssetName)); } if (!resourceInfo.IsLoadFromBinary) { throw new GameFrameworkException(Utility.Text.Format("Can not load binary '{0}' from file system which is not a binary asset.", binaryAssetName)); } if (!resourceInfo.UseFileSystem) { throw new GameFrameworkException(Utility.Text.Format("Can not load binary '{0}' from file system which is not use file system.", binaryAssetName)); } IFileSystem fileSystem = m_ResourceManager.GetFileSystem(resourceInfo.FileSystemName, resourceInfo.StorageInReadOnly); int bytesRead = fileSystem.ReadFile(resourceInfo.ResourceName.FullName, buffer, startIndex, length); if (resourceInfo.LoadType == LoadType.LoadFromBinaryAndQuickDecrypt || resourceInfo.LoadType == LoadType.LoadFromBinaryAndDecrypt) { DecryptResourceCallback decryptResourceCallback = m_ResourceManager.m_DecryptResourceCallback ?? DefaultDecryptResourceCallback; decryptResourceCallback(buffer, startIndex, bytesRead, resourceInfo.ResourceName.Name, resourceInfo.ResourceName.Variant, resourceInfo.ResourceName.Extension, resourceInfo.StorageInReadOnly, resourceInfo.FileSystemName, (byte)resourceInfo.LoadType, resourceInfo.Length, resourceInfo.HashCode); } return bytesRead; } /// <summary> /// 从文件系统中加载二进制资源的片段。 /// </summary> /// <param name="binaryAssetName">要加载片段的二进制资源的名称。</param> /// <param name="offset">要加载片段的偏移。</param> /// <param name="length">要加载片段的长度。</param> /// <returns>存储加载二进制资源片段内容的二进制流。</returns> public byte[] LoadBinarySegmentFromFileSystem(string binaryAssetName, int offset, int length) { ResourceInfo resourceInfo = GetResourceInfo(binaryAssetName); if (resourceInfo == null) { throw new GameFrameworkException(Utility.Text.Format("Can not load binary '{0}' from file system which is not exist.", binaryAssetName)); } if (!resourceInfo.Ready) { throw new GameFrameworkException(Utility.Text.Format("Can not load binary '{0}' from file system which is not ready.", binaryAssetName)); } if (!resourceInfo.IsLoadFromBinary) { throw new GameFrameworkException(Utility.Text.Format("Can not load binary '{0}' from file system which is not a binary asset.", binaryAssetName)); } if (!resourceInfo.UseFileSystem) { throw new GameFrameworkException(Utility.Text.Format("Can not load binary '{0}' from file system which is not use file system.", binaryAssetName)); } IFileSystem fileSystem = m_ResourceManager.GetFileSystem(resourceInfo.FileSystemName, resourceInfo.StorageInReadOnly); byte[] bytes = fileSystem.ReadFileSegment(resourceInfo.ResourceName.FullName, offset, length); if (bytes == null) { return null; } if (resourceInfo.LoadType == LoadType.LoadFromBinaryAndQuickDecrypt || resourceInfo.LoadType == LoadType.LoadFromBinaryAndDecrypt) { DecryptResourceCallback decryptResourceCallback = m_ResourceManager.m_DecryptResourceCallback ?? DefaultDecryptResourceCallback; decryptResourceCallback(bytes, 0, bytes.Length, resourceInfo.ResourceName.Name, resourceInfo.ResourceName.Variant, resourceInfo.ResourceName.Extension, resourceInfo.StorageInReadOnly, resourceInfo.FileSystemName, (byte)resourceInfo.LoadType, resourceInfo.Length, resourceInfo.HashCode); } return bytes; } /// <summary> /// 从文件系统中加载二进制资源的片段。 /// </summary> /// <param name="binaryAssetName">要加载片段的二进制资源的名称。</param> /// <param name="offset">要加载片段的偏移。</param> /// <param name="buffer">存储加载二进制资源片段内容的二进制流。</param> /// <param name="startIndex">存储加载二进制资源片段内容的二进制流的起始位置。</param> /// <param name="length">要加载片段的长度。</param> /// <returns>实际加载了多少字节。</returns> public int LoadBinarySegmentFromFileSystem(string binaryAssetName, int offset, byte[] buffer, int startIndex, int length) { ResourceInfo resourceInfo = GetResourceInfo(binaryAssetName); if (resourceInfo == null) { throw new GameFrameworkException(Utility.Text.Format("Can not load binary '{0}' from file system which is not exist.", binaryAssetName)); } if (!resourceInfo.Ready) { throw new GameFrameworkException(Utility.Text.Format("Can not load binary '{0}' from file system which is not ready.", binaryAssetName)); } if (!resourceInfo.IsLoadFromBinary) { throw new GameFrameworkException(Utility.Text.Format("Can not load binary '{0}' from file system which is not a binary asset.", binaryAssetName)); } if (!resourceInfo.UseFileSystem) { throw new GameFrameworkException(Utility.Text.Format("Can not load binary '{0}' from file system which is not use file system.", binaryAssetName)); } IFileSystem fileSystem = m_ResourceManager.GetFileSystem(resourceInfo.FileSystemName, resourceInfo.StorageInReadOnly); int bytesRead = fileSystem.ReadFileSegment(resourceInfo.ResourceName.FullName, offset, buffer, startIndex, length); if (resourceInfo.LoadType == LoadType.LoadFromBinaryAndQuickDecrypt || resourceInfo.LoadType == LoadType.LoadFromBinaryAndDecrypt) { DecryptResourceCallback decryptResourceCallback = m_ResourceManager.m_DecryptResourceCallback ?? DefaultDecryptResourceCallback; decryptResourceCallback(buffer, startIndex, bytesRead, resourceInfo.ResourceName.Name, resourceInfo.ResourceName.Variant, resourceInfo.ResourceName.Extension, resourceInfo.StorageInReadOnly, resourceInfo.FileSystemName, (byte)resourceInfo.LoadType, resourceInfo.Length, resourceInfo.HashCode); } return bytesRead; } /// <summary> /// 获取所有加载资源任务的信息。 /// </summary> /// <returns>所有加载资源任务的信息。</returns> public TaskInfo[] GetAllLoadAssetInfos() { return m_TaskPool.GetAllTaskInfos(); } private bool LoadDependencyAsset(string assetName, int priority, LoadResourceTaskBase mainTask, object userData) { if (mainTask == null) { throw new GameFrameworkException("Main task is invalid."); } ResourceInfo resourceInfo = null; string[] dependencyAssetNames = null; if (!CheckAsset(assetName, out resourceInfo, out dependencyAssetNames)) { return false; } if (resourceInfo.IsLoadFromBinary) { return false; } LoadDependencyAssetTask dependencyTask = LoadDependencyAssetTask.Create(assetName, priority, resourceInfo, dependencyAssetNames, mainTask, userData); foreach (string dependencyAssetName in dependencyAssetNames) { if (!LoadDependencyAsset(dependencyAssetName, priority, dependencyTask, userData)) { return false; } } m_TaskPool.AddTask(dependencyTask); if (!resourceInfo.Ready) { m_ResourceManager.UpdateResource(resourceInfo.ResourceName); } return true; } private ResourceInfo GetResourceInfo(string assetName) { if (string.IsNullOrEmpty(assetName)) { return null; } AssetInfo assetInfo = m_ResourceManager.GetAssetInfo(assetName); if (assetInfo == null) { return null; } return m_ResourceManager.GetResourceInfo(assetInfo.ResourceName); } private bool CheckAsset(string assetName, out ResourceInfo resourceInfo, out string[] dependencyAssetNames) { resourceInfo = null; dependencyAssetNames = null; if (string.IsNullOrEmpty(assetName)) { return false; } AssetInfo assetInfo = m_ResourceManager.GetAssetInfo(assetName); if (assetInfo == null) { return false; } resourceInfo = m_ResourceManager.GetResourceInfo(assetInfo.ResourceName); if (resourceInfo == null) { return false; } dependencyAssetNames = assetInfo.GetDependencyAssetNames(); return m_ResourceManager.m_ResourceMode == ResourceMode.UpdatableWhilePlaying ? true : resourceInfo.Ready; } private void DefaultDecryptResourceCallback(byte[] bytes, int startIndex, int count, string name, string variant, string extension, bool storageInReadOnly, string fileSystem, byte loadType, int length, int hashCode) { Utility.Converter.GetBytes(hashCode, m_CachedHashBytes); switch ((LoadType)loadType) { case LoadType.LoadFromMemoryAndQuickDecrypt: case LoadType.LoadFromBinaryAndQuickDecrypt: Utility.Encryption.GetQuickSelfXorBytes(bytes, m_CachedHashBytes); break; case LoadType.LoadFromMemoryAndDecrypt: case LoadType.LoadFromBinaryAndDecrypt: Utility.Encryption.GetSelfXorBytes(bytes, m_CachedHashBytes); break; default: throw new GameFrameworkException("Not supported load type when decrypt resource."); } Array.Clear(m_CachedHashBytes, 0, CachedHashBytesLength); } private void OnLoadBinarySuccess(string fileUri, byte[] bytes, float duration, object userData) { LoadBinaryInfo loadBinaryInfo = (LoadBinaryInfo)userData; if (loadBinaryInfo == null) { throw new GameFrameworkException("Load binary info is invalid."); } ResourceInfo resourceInfo = loadBinaryInfo.ResourceInfo; if (resourceInfo.LoadType == LoadType.LoadFromBinaryAndQuickDecrypt || resourceInfo.LoadType == LoadType.LoadFromBinaryAndDecrypt) { DecryptResourceCallback decryptResourceCallback = m_ResourceManager.m_DecryptResourceCallback ?? DefaultDecryptResourceCallback; decryptResourceCallback(bytes, 0, bytes.Length, resourceInfo.ResourceName.Name, resourceInfo.ResourceName.Variant, resourceInfo.ResourceName.Extension, resourceInfo.StorageInReadOnly, resourceInfo.FileSystemName, (byte)resourceInfo.LoadType, resourceInfo.Length, resourceInfo.HashCode); } loadBinaryInfo.LoadBinaryCallbacks.LoadBinarySuccessCallback(loadBinaryInfo.BinaryAssetName, bytes, duration, loadBinaryInfo.UserData); ReferencePool.Release(loadBinaryInfo); } private void OnLoadBinaryFailure(string fileUri, string errorMessage, object userData) { LoadBinaryInfo loadBinaryInfo = (LoadBinaryInfo)userData; if (loadBinaryInfo == null) { throw new GameFrameworkException("Load binary info is invalid."); } if (loadBinaryInfo.LoadBinaryCallbacks.LoadBinaryFailureCallback != null) { loadBinaryInfo.LoadBinaryCallbacks.LoadBinaryFailureCallback(loadBinaryInfo.BinaryAssetName, LoadResourceStatus.AssetError, errorMessage, loadBinaryInfo.UserData); } ReferencePool.Release(loadBinaryInfo); } } } }
43.197002
313
0.543201
[ "MIT" ]
297496732/GameFramework
GameFramework/Resource/ResourceManager.ResourceLoader.cs
42,701
C#
#region Copyright // <<<<<<< HEAD <<<<<<< HEAD ======= ======= >>>>>>> update form orginal repo // DotNetNuke® - https://www.dnnsoftware.com // Copyright (c) 2002-2018 // by DotNetNuke Corporation // // 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. #endregion <<<<<<< HEAD >>>>>>> Merges latest changes from release/9.4.x into development (#3178) ======= >>>>>>> update form orginal repo using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.IO; using System.Linq; using DotNetNuke.Common; using DotNetNuke.ExtensionPoints.Filters; namespace DotNetNuke.ExtensionPoints { public class ExtensionPointManager { private static readonly object SyncRoot = new object(); #pragma warning disable 649 [ImportMany] private IEnumerable<Lazy<IScriptItemExtensionPoint, IExtensionPointData>> _scripts; [ImportMany] private IEnumerable<Lazy<IEditPageTabExtensionPoint, IExtensionPointData>> _editPageTabExtensionPoint; [ImportMany] private IEnumerable<Lazy<IToolBarButtonExtensionPoint, IExtensionPointData>> _toolbarButtonExtensionPoints; [ImportMany] private IEnumerable<Lazy<IEditPagePanelExtensionPoint, IExtensionPointData>> _editPagePanelExtensionPoints; [ImportMany] private IEnumerable<Lazy<IContextMenuItemExtensionPoint, IExtensionPointData>> _ctxMenuItemExtensionPoints; [ImportMany] private IEnumerable<Lazy<IUserControlExtensionPoint, IExtensionPointData>> _userControlExtensionPoints; [ImportMany] private IEnumerable<Lazy<IMenuItemExtensionPoint, IExtensionPointData>> _menuItems; [ImportMany] private IEnumerable<Lazy<IGridColumnExtensionPoint, IExtensionPointData>> _gridColumns; #pragma warning restore 649 public ExtensionPointManager() { ComposeParts(this); } private static readonly CompositionContainer MefCompositionContainer = InitializeMefCompositionContainer(); private static CompositionContainer InitializeMefCompositionContainer() { var catalog = new AggregateCatalog(); var path = Path.Combine(Globals.ApplicationMapPath, "bin"); catalog.Catalogs.Add(new SafeDirectoryCatalog(path)); return new CompositionContainer(catalog, true); } public static void ComposeParts(params object[] attributeParts) { lock (SyncRoot) { MefCompositionContainer.ComposeParts(attributeParts); } } public IEnumerable<IEditPageTabExtensionPoint> GetEditPageTabExtensionPoints(string module) { return GetEditPageTabExtensionPoints(module, null); } public IEnumerable<IEditPageTabExtensionPoint> GetEditPageTabExtensionPoints(string module, string group) { return from e in _editPageTabExtensionPoint where e.Metadata.Module == module && (string.IsNullOrEmpty(@group) || e.Metadata.Group == @group) orderby e.Value.Order select e.Value; } public IEnumerable<IToolBarButtonExtensionPoint> GetToolBarButtonExtensionPoints(string module) { return GetToolBarButtonExtensionPoints(module, null); } public IEnumerable<IToolBarButtonExtensionPoint> GetToolBarButtonExtensionPoints(string module, string group) { return GetToolBarButtonExtensionPoints(module, group, new NoFilter()); } public IEnumerable<IToolBarButtonExtensionPoint> GetToolBarButtonExtensionPoints(string module, string group, IExtensionPointFilter filter) { return from e in _toolbarButtonExtensionPoints where FilterCondition(e.Metadata, module, @group) && filter.Condition(e.Metadata) orderby e.Value.Order select e.Value; } public IToolBarButtonExtensionPoint GetToolBarButtonExtensionPointFirstByPriority(string module, string name) { return (from e in _toolbarButtonExtensionPoints where e.Metadata.Module == module && e.Metadata.Name == name orderby e.Metadata.Priority select e.Value).FirstOrDefault(); } public IEnumerable<IScriptItemExtensionPoint> GetScriptItemExtensionPoints(string module) { return GetScriptItemExtensionPoints(module, null); } public IEnumerable<IScriptItemExtensionPoint> GetScriptItemExtensionPoints(string module, string group) { return from e in _scripts where e.Metadata.Module == module && (string.IsNullOrEmpty(@group) || e.Metadata.Group == @group) orderby e.Value.Order select e.Value; } public IEnumerable<IEditPagePanelExtensionPoint> GetEditPagePanelExtensionPoints(string module) { return GetEditPagePanelExtensionPoints(module, null); } public IEnumerable<IEditPagePanelExtensionPoint> GetEditPagePanelExtensionPoints(string module, string group) { return from e in _editPagePanelExtensionPoints where e.Metadata.Module == module && (string.IsNullOrEmpty(@group) || e.Metadata.Group == @group) orderby e.Value.Order select e.Value; } public IEditPagePanelExtensionPoint GetEditPagePanelExtensionPointFirstByPriority(string module, string name) { return (from e in _editPagePanelExtensionPoints where e.Metadata.Module == module && e.Metadata.Name == name orderby e.Metadata.Priority select e.Value).FirstOrDefault(); } public IEnumerable<IContextMenuItemExtensionPoint> GetContextMenuItemExtensionPoints(string module) { return GetContextMenuItemExtensionPoints(module, null); } public IEnumerable<IContextMenuItemExtensionPoint> GetContextMenuItemExtensionPoints(string module, string group) { return from e in _ctxMenuItemExtensionPoints where e.Metadata.Module == module && (string.IsNullOrEmpty(@group) || e.Metadata.Group == @group) orderby e.Value.Order select e.Value; } public IUserControlExtensionPoint GetUserControlExtensionPointFirstByPriority(string module, string name) { return (from e in _userControlExtensionPoints where e.Metadata.Module == module && e.Metadata.Name == name orderby e.Metadata.Priority select e.Value).FirstOrDefault(); } public IEnumerable<IUserControlExtensionPoint> GetUserControlExtensionPoints(string module, string group) { return from e in _userControlExtensionPoints where e.Metadata.Module == module && e.Metadata.Group == @group orderby e.Value.Order select e.Value; } public IEnumerable<IMenuItemExtensionPoint> GetMenuItemExtensionPoints(string module) { return GetMenuItemExtensionPoints(module, null); } public IEnumerable<IMenuItemExtensionPoint> GetMenuItemExtensionPoints(string module, string group) { return GetMenuItemExtensionPoints(module, group, new NoFilter()); } public IEnumerable<IMenuItemExtensionPoint> GetMenuItemExtensionPoints(string module, string group, IExtensionPointFilter filter) { return from e in _menuItems where FilterCondition(e.Metadata, module, @group) && filter.Condition(e.Metadata) orderby e.Value.Order select e.Value; } public IEnumerable<IGridColumnExtensionPoint> GetGridColumnExtensionPoints(string module) { return GetGridColumnExtensionPoints(module, null); } public IEnumerable<IGridColumnExtensionPoint> GetGridColumnExtensionPoints(string module, string group) { return GetGridColumnExtensionPoints(module, group, new NoFilter()); } public IEnumerable<IGridColumnExtensionPoint> GetGridColumnExtensionPoints(string module, string group, IExtensionPointFilter filter) { return from e in _gridColumns where FilterCondition(e.Metadata, module, @group) && filter.Condition(e.Metadata) orderby e.Value.Order select e.Value; } private bool FilterCondition(IExtensionPointData data, string module, string group) { return data.Module == module && (string.IsNullOrEmpty(@group) || data.Group == @group); } } }
41.47561
147
0.659218
[ "MIT" ]
DnnSoftwarePersian/Dnn.Platform
DNN Platform/Library/ExtensionPoints/ExtensionPointManager.cs
10,206
C#
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Aiursoft.Colossus.Controllers { public class ErrorController : Controller { public IActionResult Code404() { return View(); } public IActionResult ServerException() { return View(); } } }
19.666667
46
0.627119
[ "MIT" ]
asxuen/Nexus
Colossus/Controllers/ErrorController.cs
415
C#
using System; using System.Drawing; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Diagnostics; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using System.IO; using System.Text; using System.Xml; using System.Reflection; using System.Deployment.Application; using DigitalPlatform; using DigitalPlatform.GUI; using DigitalPlatform.Xml; using DigitalPlatform.rms.Client; using DigitalPlatform.IO; using DigitalPlatform.Range; using DigitalPlatform.Marc; using DigitalPlatform.Library; using DigitalPlatform.Script; using DigitalPlatform.MarcDom; using DigitalPlatform.Text; namespace dp2Batch { /// <summary> /// Summary description for MainForm. /// </summary> public class MainForm : System.Windows.Forms.Form { public string DataDir = ""; Assembly AssemblyMain = null; Assembly AssemblyFilter = null; MyFilterDocument MarcFilter = null; int m_nAssemblyVersion = 0; Batch batchObj = null; int m_nRecordCount = 0; ScriptManager scriptManager = new ScriptManager(); Hashtable m_tableMarcSyntax = new Hashtable(); // 数据库全路径和MARC格式的对照表 string CurMarcSyntax = ""; // 当前MARC格式 bool OutputCrLf = false; // ISO2709文件记录尾部是否加入回车换行符号 bool AddG01 = false; // ISO2709文件中的记录内是否加入-01字段?(不加时就要去除原有的,以免误会) bool Remove998 = false; // 输出 ISO2709 文件的时候是否删除 998 字段? public CfgCache cfgCache = new CfgCache(); // 不知道为什么要使用事件?难道在 this 里面直接调用函数不是更简单么? public event CheckTargetDbEventHandler CheckTargetDb = null; public DigitalPlatform.StopManager stopManager = new DigitalPlatform.StopManager(); public ServerCollection Servers = null; //保存界面信息 public ApplicationInfo AppInfo = new ApplicationInfo("dp2batch.xml"); RmsChannel channel = null; // 临时使用的channel对象 public AutoResetEvent eventClose = new AutoResetEvent(false); RmsChannelCollection Channels = new RmsChannelCollection(); // 拥有 DigitalPlatform.Stop stop = null; string strLastOutputFileName = ""; int nLastOutputFilterIndex = 1; // double ProgressRatio = 1.0; bool bNotAskTimestampMismatchWhenOverwrite = false; // 当转入数据的时候,如果发生时间戳不匹配,是否不询问就强行覆盖 private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.MenuItem menuItem_exit; private System.Windows.Forms.TabControl tabControl_main; private System.Windows.Forms.TabPage tabPage_range; private System.Windows.Forms.Panel panel_range; private System.Windows.Forms.Panel panel_resdirtree; private System.Windows.Forms.Splitter splitter_range; private System.Windows.Forms.Panel panel_rangeParams; private System.Windows.Forms.CheckBox checkBox_verifyNumber; public System.Windows.Forms.TextBox textBox_dbPath; private System.Windows.Forms.Label label1; private System.Windows.Forms.GroupBox groupBox1; public System.Windows.Forms.TextBox textBox_endNo; private System.Windows.Forms.Label label3; public System.Windows.Forms.TextBox textBox_startNo; private System.Windows.Forms.Label label2; private System.Windows.Forms.RadioButton radioButton_startEnd; private System.Windows.Forms.RadioButton radioButton_all; private System.Windows.Forms.CheckBox checkBox_forceLoop; private System.Windows.Forms.TabPage tabPage_resultset; private System.Windows.Forms.MenuItem menuItem_file; private System.Windows.Forms.MenuItem menuItem_help; private System.Windows.Forms.MenuItem menuItem_copyright; private System.Windows.Forms.MenuItem menuItem_cfg; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.ToolBar toolBar_main; private System.Windows.Forms.ToolBarButton toolBarButton_stop; private System.Windows.Forms.ImageList imageList_toolbar; private System.Windows.Forms.ToolBarButton toolBarButton_begin; private System.Windows.Forms.TabPage tabPage_import; private System.Windows.Forms.Label label4; private System.Windows.Forms.Button button_import_findFileName; private System.Windows.Forms.TextBox textBox_import_fileName; private System.Windows.Forms.Label label5; private ResTree treeView_rangeRes; private System.Windows.Forms.CheckBox checkBox_export_delete; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox textBox_import_range; private System.Windows.Forms.MenuItem menuItem_serversCfg; private System.Windows.Forms.MenuItem menuItem_projectManage; private System.Windows.Forms.MenuItem menuItem_run; private System.Windows.Forms.MenuItem menuItem2; private System.Windows.Forms.TextBox textBox_import_dbMap; private System.Windows.Forms.Button button_import_dbMap; private MenuItem menuItem_openDataFolder; private MenuItem menuItem3; private MenuItem menuItem_rebuildKeys; private MenuItem menuItem_rebuildKeysByDbnames; private StatusStrip statusStrip_main; private ToolStripStatusLabel toolStripStatusLabel_main; private ToolStripProgressBar toolStripProgressBar_main; private CheckBox checkBox_export_fastMode; private CheckBox checkBox_import_fastMode; private System.ComponentModel.IContainer components; public MainForm() { InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } if (this.Channels != null) this.Channels.Dispose(); this.eventClose.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components); this.menuItem_file = new System.Windows.Forms.MenuItem(); this.menuItem_run = new System.Windows.Forms.MenuItem(); this.menuItem2 = new System.Windows.Forms.MenuItem(); this.menuItem_projectManage = new System.Windows.Forms.MenuItem(); this.menuItem_cfg = new System.Windows.Forms.MenuItem(); this.menuItem_serversCfg = new System.Windows.Forms.MenuItem(); this.menuItem3 = new System.Windows.Forms.MenuItem(); this.menuItem_rebuildKeys = new System.Windows.Forms.MenuItem(); this.menuItem_rebuildKeysByDbnames = new System.Windows.Forms.MenuItem(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.menuItem_exit = new System.Windows.Forms.MenuItem(); this.menuItem_help = new System.Windows.Forms.MenuItem(); this.menuItem_copyright = new System.Windows.Forms.MenuItem(); this.menuItem_openDataFolder = new System.Windows.Forms.MenuItem(); this.tabControl_main = new System.Windows.Forms.TabControl(); this.tabPage_range = new System.Windows.Forms.TabPage(); this.panel_range = new System.Windows.Forms.Panel(); this.panel_resdirtree = new System.Windows.Forms.Panel(); this.treeView_rangeRes = new DigitalPlatform.rms.Client.ResTree(); this.splitter_range = new System.Windows.Forms.Splitter(); this.panel_rangeParams = new System.Windows.Forms.Panel(); this.checkBox_export_fastMode = new System.Windows.Forms.CheckBox(); this.checkBox_export_delete = new System.Windows.Forms.CheckBox(); this.checkBox_verifyNumber = new System.Windows.Forms.CheckBox(); this.textBox_dbPath = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.textBox_endNo = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.textBox_startNo = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.radioButton_startEnd = new System.Windows.Forms.RadioButton(); this.radioButton_all = new System.Windows.Forms.RadioButton(); this.checkBox_forceLoop = new System.Windows.Forms.CheckBox(); this.tabPage_resultset = new System.Windows.Forms.TabPage(); this.tabPage_import = new System.Windows.Forms.TabPage(); this.checkBox_import_fastMode = new System.Windows.Forms.CheckBox(); this.textBox_import_range = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.button_import_findFileName = new System.Windows.Forms.Button(); this.textBox_import_fileName = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.button_import_dbMap = new System.Windows.Forms.Button(); this.textBox_import_dbMap = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.toolBar_main = new System.Windows.Forms.ToolBar(); this.toolBarButton_stop = new System.Windows.Forms.ToolBarButton(); this.toolBarButton_begin = new System.Windows.Forms.ToolBarButton(); this.imageList_toolbar = new System.Windows.Forms.ImageList(this.components); this.statusStrip_main = new System.Windows.Forms.StatusStrip(); this.toolStripStatusLabel_main = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripProgressBar_main = new System.Windows.Forms.ToolStripProgressBar(); this.tabControl_main.SuspendLayout(); this.tabPage_range.SuspendLayout(); this.panel_range.SuspendLayout(); this.panel_resdirtree.SuspendLayout(); this.panel_rangeParams.SuspendLayout(); this.groupBox1.SuspendLayout(); this.tabPage_import.SuspendLayout(); this.statusStrip_main.SuspendLayout(); this.SuspendLayout(); // // mainMenu1 // this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem_file, this.menuItem_help}); // // menuItem_file // this.menuItem_file.Index = 0; this.menuItem_file.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem_run, this.menuItem2, this.menuItem_projectManage, this.menuItem_cfg, this.menuItem_serversCfg, this.menuItem3, this.menuItem_rebuildKeys, this.menuItem_rebuildKeysByDbnames, this.menuItem1, this.menuItem_exit}); this.menuItem_file.Text = "文件(&F)"; // // menuItem_run // this.menuItem_run.Index = 0; this.menuItem_run.Text = "运行(&R)..."; this.menuItem_run.Click += new System.EventHandler(this.menuItem_run_Click); // // menuItem2 // this.menuItem2.Index = 1; this.menuItem2.Text = "-"; // // menuItem_projectManage // this.menuItem_projectManage.Index = 2; this.menuItem_projectManage.Text = "方案管理(&M)..."; this.menuItem_projectManage.Click += new System.EventHandler(this.menuItem_projectManage_Click); // // menuItem_cfg // this.menuItem_cfg.Enabled = false; this.menuItem_cfg.Index = 3; this.menuItem_cfg.Text = "配置(&C)..."; this.menuItem_cfg.Click += new System.EventHandler(this.menuItem_cfg_Click); // // menuItem_serversCfg // this.menuItem_serversCfg.Index = 4; this.menuItem_serversCfg.Text = "缺省帐户管理(&A)..."; this.menuItem_serversCfg.Click += new System.EventHandler(this.menuItem_serversCfg_Click); // // menuItem3 // this.menuItem3.Index = 5; this.menuItem3.Text = "-"; // // menuItem_rebuildKeys // this.menuItem_rebuildKeys.Index = 6; this.menuItem_rebuildKeys.Text = "重建检索点(&B)"; this.menuItem_rebuildKeys.Click += new System.EventHandler(this.menuItem_rebuildKeys_Click); // // menuItem_rebuildKeysByDbnames // this.menuItem_rebuildKeysByDbnames.Index = 7; this.menuItem_rebuildKeysByDbnames.Text = "重建检索点[根据剪贴板内的数据库路径](&R)..."; this.menuItem_rebuildKeysByDbnames.Click += new System.EventHandler(this.menuItem_rebuildKeysByDbnames_Click); // // menuItem1 // this.menuItem1.Index = 8; this.menuItem1.Text = "-"; // // menuItem_exit // this.menuItem_exit.Index = 9; this.menuItem_exit.Text = "退出(&X)"; this.menuItem_exit.Click += new System.EventHandler(this.menuItem_exit_Click); // // menuItem_help // this.menuItem_help.Index = 1; this.menuItem_help.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem_copyright, this.menuItem_openDataFolder}); this.menuItem_help.Text = "帮助(&H)"; // // menuItem_copyright // this.menuItem_copyright.Index = 0; this.menuItem_copyright.Text = "版权(&C)..."; this.menuItem_copyright.Click += new System.EventHandler(this.menuItem_copyright_Click); // // menuItem_openDataFolder // this.menuItem_openDataFolder.Index = 1; this.menuItem_openDataFolder.Text = "打开数据文件夹(&D)..."; this.menuItem_openDataFolder.Click += new System.EventHandler(this.menuItem_openDataFolder_Click); // // tabControl_main // this.tabControl_main.Controls.Add(this.tabPage_range); this.tabControl_main.Controls.Add(this.tabPage_resultset); this.tabControl_main.Controls.Add(this.tabPage_import); this.tabControl_main.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl_main.Location = new System.Drawing.Point(0, 32); this.tabControl_main.Name = "tabControl_main"; this.tabControl_main.SelectedIndex = 0; this.tabControl_main.Size = new System.Drawing.Size(634, 273); this.tabControl_main.TabIndex = 1; this.tabControl_main.SelectedIndexChanged += new System.EventHandler(this.tabControl_main_SelectedIndexChanged); // // tabPage_range // this.tabPage_range.BackColor = System.Drawing.Color.Transparent; this.tabPage_range.Controls.Add(this.panel_range); this.tabPage_range.Location = new System.Drawing.Point(8, 43); this.tabPage_range.Name = "tabPage_range"; this.tabPage_range.Padding = new System.Windows.Forms.Padding(6); this.tabPage_range.Size = new System.Drawing.Size(618, 222); this.tabPage_range.TabIndex = 0; this.tabPage_range.Text = "按记录ID导出"; this.tabPage_range.UseVisualStyleBackColor = true; // // panel_range // this.panel_range.Controls.Add(this.panel_resdirtree); this.panel_range.Controls.Add(this.splitter_range); this.panel_range.Controls.Add(this.panel_rangeParams); this.panel_range.Dock = System.Windows.Forms.DockStyle.Fill; this.panel_range.Location = new System.Drawing.Point(6, 6); this.panel_range.Name = "panel_range"; this.panel_range.Size = new System.Drawing.Size(606, 210); this.panel_range.TabIndex = 8; // // panel_resdirtree // this.panel_resdirtree.Controls.Add(this.treeView_rangeRes); this.panel_resdirtree.Dock = System.Windows.Forms.DockStyle.Fill; this.panel_resdirtree.Location = new System.Drawing.Point(317, 0); this.panel_resdirtree.Name = "panel_resdirtree"; this.panel_resdirtree.Padding = new System.Windows.Forms.Padding(0, 4, 4, 4); this.panel_resdirtree.Size = new System.Drawing.Size(289, 210); this.panel_resdirtree.TabIndex = 6; // // treeView_rangeRes // this.treeView_rangeRes.Dock = System.Windows.Forms.DockStyle.Fill; this.treeView_rangeRes.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.treeView_rangeRes.HideSelection = false; this.treeView_rangeRes.ImageIndex = 0; this.treeView_rangeRes.Location = new System.Drawing.Point(0, 4); this.treeView_rangeRes.Name = "treeView_rangeRes"; this.treeView_rangeRes.SelectedImageIndex = 0; this.treeView_rangeRes.Size = new System.Drawing.Size(285, 202); this.treeView_rangeRes.TabIndex = 0; this.treeView_rangeRes.AfterCheck += new System.Windows.Forms.TreeViewEventHandler(this.treeView_rangeRes_AfterCheck); this.treeView_rangeRes.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView_rangeRes_AfterSelect); // // splitter_range // this.splitter_range.Location = new System.Drawing.Point(309, 0); this.splitter_range.Name = "splitter_range"; this.splitter_range.Size = new System.Drawing.Size(8, 210); this.splitter_range.TabIndex = 8; this.splitter_range.TabStop = false; // // panel_rangeParams // this.panel_rangeParams.AutoScroll = true; this.panel_rangeParams.Controls.Add(this.checkBox_export_fastMode); this.panel_rangeParams.Controls.Add(this.checkBox_export_delete); this.panel_rangeParams.Controls.Add(this.checkBox_verifyNumber); this.panel_rangeParams.Controls.Add(this.textBox_dbPath); this.panel_rangeParams.Controls.Add(this.label1); this.panel_rangeParams.Controls.Add(this.groupBox1); this.panel_rangeParams.Controls.Add(this.checkBox_forceLoop); this.panel_rangeParams.Dock = System.Windows.Forms.DockStyle.Left; this.panel_rangeParams.Location = new System.Drawing.Point(0, 0); this.panel_rangeParams.Name = "panel_rangeParams"; this.panel_rangeParams.Size = new System.Drawing.Size(309, 210); this.panel_rangeParams.TabIndex = 7; // // checkBox_export_fastMode // this.checkBox_export_fastMode.AutoSize = true; this.checkBox_export_fastMode.Location = new System.Drawing.Point(144, 198); this.checkBox_export_fastMode.Name = "checkBox_export_fastMode"; this.checkBox_export_fastMode.Size = new System.Drawing.Size(172, 33); this.checkBox_export_fastMode.TabIndex = 7; this.checkBox_export_fastMode.Text = "快速模式(&F)"; this.checkBox_export_fastMode.UseVisualStyleBackColor = true; // // checkBox_export_delete // this.checkBox_export_delete.Location = new System.Drawing.Point(9, 195); this.checkBox_export_delete.Name = "checkBox_export_delete"; this.checkBox_export_delete.Size = new System.Drawing.Size(117, 24); this.checkBox_export_delete.TabIndex = 6; this.checkBox_export_delete.Text = "删除记录(&D)"; this.checkBox_export_delete.CheckedChanged += new System.EventHandler(this.checkBox_export_delete_CheckedChanged); // // checkBox_verifyNumber // this.checkBox_verifyNumber.Location = new System.Drawing.Point(9, 171); this.checkBox_verifyNumber.Name = "checkBox_verifyNumber"; this.checkBox_verifyNumber.Size = new System.Drawing.Size(124, 18); this.checkBox_verifyNumber.TabIndex = 4; this.checkBox_verifyNumber.Text = "校准首尾ID(&V)"; // // textBox_dbPath // this.textBox_dbPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox_dbPath.Location = new System.Drawing.Point(75, 6); this.textBox_dbPath.Name = "textBox_dbPath"; this.textBox_dbPath.ReadOnly = true; this.textBox_dbPath.Size = new System.Drawing.Size(193, 36); this.textBox_dbPath.TabIndex = 2; this.textBox_dbPath.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // label1 // this.label1.Location = new System.Drawing.Point(7, 6); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(62, 18); this.label1.TabIndex = 1; this.label1.Text = "数据库:"; // // groupBox1 // this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox1.Controls.Add(this.textBox_endNo); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.textBox_startNo); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.radioButton_startEnd); this.groupBox1.Controls.Add(this.radioButton_all); this.groupBox1.Location = new System.Drawing.Point(7, 32); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(260, 134); this.groupBox1.TabIndex = 3; this.groupBox1.TabStop = false; this.groupBox1.Text = " 输出记录范围 "; // // textBox_endNo // this.textBox_endNo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox_endNo.Location = new System.Drawing.Point(165, 95); this.textBox_endNo.Name = "textBox_endNo"; this.textBox_endNo.Size = new System.Drawing.Size(81, 36); this.textBox_endNo.TabIndex = 5; this.textBox_endNo.TextChanged += new System.EventHandler(this.textBox_endNo_TextChanged); // // label3 // this.label3.Location = new System.Drawing.Point(69, 97); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(85, 19); this.label3.TabIndex = 4; this.label3.Text = "结束记录ID:"; // // textBox_startNo // this.textBox_startNo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox_startNo.Location = new System.Drawing.Point(165, 63); this.textBox_startNo.Name = "textBox_startNo"; this.textBox_startNo.Size = new System.Drawing.Size(81, 36); this.textBox_startNo.TabIndex = 3; this.textBox_startNo.TextChanged += new System.EventHandler(this.textBox_startNo_TextChanged); // // label2 // this.label2.Location = new System.Drawing.Point(69, 65); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(85, 18); this.label2.TabIndex = 2; this.label2.Text = "起始记录ID:"; // // radioButton_startEnd // this.radioButton_startEnd.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.radioButton_startEnd.Checked = true; this.radioButton_startEnd.Location = new System.Drawing.Point(21, 38); this.radioButton_startEnd.Name = "radioButton_startEnd"; this.radioButton_startEnd.Size = new System.Drawing.Size(150, 19); this.radioButton_startEnd.TabIndex = 1; this.radioButton_startEnd.TabStop = true; this.radioButton_startEnd.Text = "起止ID(&S) "; // // radioButton_all // this.radioButton_all.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.radioButton_all.Location = new System.Drawing.Point(21, 19); this.radioButton_all.Name = "radioButton_all"; this.radioButton_all.Size = new System.Drawing.Size(63, 19); this.radioButton_all.TabIndex = 0; this.radioButton_all.Text = "全部(&A)"; this.radioButton_all.CheckedChanged += new System.EventHandler(this.radioButton_all_CheckedChanged); // // checkBox_forceLoop // this.checkBox_forceLoop.Location = new System.Drawing.Point(144, 171); this.checkBox_forceLoop.Name = "checkBox_forceLoop"; this.checkBox_forceLoop.Size = new System.Drawing.Size(158, 18); this.checkBox_forceLoop.TabIndex = 5; this.checkBox_forceLoop.Text = "未命中时继续循环(&C)"; // // tabPage_resultset // this.tabPage_resultset.BackColor = System.Drawing.Color.Transparent; this.tabPage_resultset.Location = new System.Drawing.Point(8, 43); this.tabPage_resultset.Name = "tabPage_resultset"; this.tabPage_resultset.Size = new System.Drawing.Size(618, 222); this.tabPage_resultset.TabIndex = 1; this.tabPage_resultset.Text = "按结果集导出"; this.tabPage_resultset.UseVisualStyleBackColor = true; this.tabPage_resultset.Visible = false; // // tabPage_import // this.tabPage_import.AutoScroll = true; this.tabPage_import.BackColor = System.Drawing.Color.Transparent; this.tabPage_import.Controls.Add(this.checkBox_import_fastMode); this.tabPage_import.Controls.Add(this.textBox_import_range); this.tabPage_import.Controls.Add(this.label6); this.tabPage_import.Controls.Add(this.button_import_findFileName); this.tabPage_import.Controls.Add(this.textBox_import_fileName); this.tabPage_import.Controls.Add(this.label5); this.tabPage_import.Controls.Add(this.button_import_dbMap); this.tabPage_import.Controls.Add(this.textBox_import_dbMap); this.tabPage_import.Controls.Add(this.label4); this.tabPage_import.Location = new System.Drawing.Point(8, 43); this.tabPage_import.Name = "tabPage_import"; this.tabPage_import.Size = new System.Drawing.Size(618, 222); this.tabPage_import.TabIndex = 2; this.tabPage_import.Text = "导入"; this.tabPage_import.UseVisualStyleBackColor = true; // // checkBox_import_fastMode // this.checkBox_import_fastMode.AutoSize = true; this.checkBox_import_fastMode.Location = new System.Drawing.Point(119, 61); this.checkBox_import_fastMode.Name = "checkBox_import_fastMode"; this.checkBox_import_fastMode.Size = new System.Drawing.Size(172, 33); this.checkBox_import_fastMode.TabIndex = 8; this.checkBox_import_fastMode.Text = "快速模式(&F)"; this.checkBox_import_fastMode.UseVisualStyleBackColor = true; // // textBox_import_range // this.textBox_import_range.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox_import_range.Location = new System.Drawing.Point(119, 33); this.textBox_import_range.Name = "textBox_import_range"; this.textBox_import_range.Size = new System.Drawing.Size(379, 36); this.textBox_import_range.TabIndex = 7; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(9, 36); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(150, 29); this.label6.TabIndex = 6; this.label6.Text = "导入范围(&R):"; // // button_import_findFileName // this.button_import_findFileName.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.button_import_findFileName.Location = new System.Drawing.Point(504, 8); this.button_import_findFileName.Name = "button_import_findFileName"; this.button_import_findFileName.Size = new System.Drawing.Size(46, 22); this.button_import_findFileName.TabIndex = 5; this.button_import_findFileName.Text = "..."; this.button_import_findFileName.Click += new System.EventHandler(this.button_import_findFileName_Click); // // textBox_import_fileName // this.textBox_import_fileName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox_import_fileName.Location = new System.Drawing.Point(119, 8); this.textBox_import_fileName.Name = "textBox_import_fileName"; this.textBox_import_fileName.Size = new System.Drawing.Size(379, 36); this.textBox_import_fileName.TabIndex = 4; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(9, 10); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(124, 29); this.label5.TabIndex = 3; this.label5.Text = "文件名(&F):"; // // button_import_dbMap // this.button_import_dbMap.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.button_import_dbMap.Location = new System.Drawing.Point(504, 102); this.button_import_dbMap.Name = "button_import_dbMap"; this.button_import_dbMap.Size = new System.Drawing.Size(46, 23); this.button_import_dbMap.TabIndex = 2; this.button_import_dbMap.Text = "..."; this.button_import_dbMap.Click += new System.EventHandler(this.button_import_dbMap_Click); // // textBox_import_dbMap // this.textBox_import_dbMap.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox_import_dbMap.Location = new System.Drawing.Point(12, 104); this.textBox_import_dbMap.Multiline = true; this.textBox_import_dbMap.Name = "textBox_import_dbMap"; this.textBox_import_dbMap.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textBox_import_dbMap.Size = new System.Drawing.Size(489, 139); this.textBox_import_dbMap.TabIndex = 1; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(9, 87); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(197, 29); this.label4.TabIndex = 0; this.label4.Text = "库名映射规则(&T):"; // // toolBar_main // this.toolBar_main.Appearance = System.Windows.Forms.ToolBarAppearance.Flat; this.toolBar_main.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] { this.toolBarButton_stop, this.toolBarButton_begin}); this.toolBar_main.Divider = false; this.toolBar_main.DropDownArrows = true; this.toolBar_main.ImageList = this.imageList_toolbar; this.toolBar_main.Location = new System.Drawing.Point(0, 0); this.toolBar_main.Name = "toolBar_main"; this.toolBar_main.ShowToolTips = true; this.toolBar_main.Size = new System.Drawing.Size(634, 32); this.toolBar_main.TabIndex = 2; this.toolBar_main.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick); // // toolBarButton_stop // this.toolBarButton_stop.Enabled = false; this.toolBarButton_stop.ImageIndex = 0; this.toolBarButton_stop.Name = "toolBarButton_stop"; this.toolBarButton_stop.ToolTipText = "停止"; // // toolBarButton_begin // this.toolBarButton_begin.ImageIndex = 1; this.toolBarButton_begin.Name = "toolBarButton_begin"; this.toolBarButton_begin.ToolTipText = "开始"; // // imageList_toolbar // this.imageList_toolbar.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList_toolbar.ImageStream"))); this.imageList_toolbar.TransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(193))))); this.imageList_toolbar.Images.SetKeyName(0, ""); this.imageList_toolbar.Images.SetKeyName(1, ""); // // statusStrip_main // this.statusStrip_main.ImageScalingSize = new System.Drawing.Size(32, 32); this.statusStrip_main.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripStatusLabel_main, this.toolStripProgressBar_main}); this.statusStrip_main.Location = new System.Drawing.Point(0, 305); this.statusStrip_main.Name = "statusStrip_main"; this.statusStrip_main.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional; this.statusStrip_main.Size = new System.Drawing.Size(634, 22); this.statusStrip_main.TabIndex = 4; this.statusStrip_main.Text = "statusStrip1"; // // toolStripStatusLabel_main // this.toolStripStatusLabel_main.Name = "toolStripStatusLabel_main"; this.toolStripStatusLabel_main.Size = new System.Drawing.Size(445, 17); this.toolStripStatusLabel_main.Spring = true; // // toolStripProgressBar_main // this.toolStripProgressBar_main.Name = "toolStripProgressBar_main"; this.toolStripProgressBar_main.Size = new System.Drawing.Size(172, 16); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(13F, 29F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(634, 327); this.Controls.Add(this.tabControl_main); this.Controls.Add(this.statusStrip_main); this.Controls.Add(this.toolBar_main); this.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Menu = this.mainMenu1; this.Name = "MainForm"; this.Text = "dp2batch V3 -- 批处理"; this.Closing += new System.ComponentModel.CancelEventHandler(this.MainForm_Closing); this.Closed += new System.EventHandler(this.MainForm_Closed); this.Load += new System.EventHandler(this.MainForm_Load); this.tabControl_main.ResumeLayout(false); this.tabPage_range.ResumeLayout(false); this.panel_range.ResumeLayout(false); this.panel_resdirtree.ResumeLayout(false); this.panel_rangeParams.ResumeLayout(false); this.panel_rangeParams.PerformLayout(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.tabPage_import.ResumeLayout(false); this.tabPage_import.PerformLayout(); this.statusStrip_main.ResumeLayout(false); this.statusStrip_main.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } private void MainForm_Load(object sender, System.EventArgs e) { if (ApplicationDeployment.IsNetworkDeployed == true) { // MessageBox.Show(this, "network"); DataDir = Application.LocalUserAppDataPath; } else { // MessageBox.Show(this, "no network"); DataDir = Environment.CurrentDirectory; } // 从文件中装载创建一个ServerCollection对象 // parameters: // bIgnorFileNotFound 是否不抛出FileNotFoundException异常。 // 如果==true,函数直接返回一个新的空ServerCollection对象 // Exception: // FileNotFoundException 文件没找到 // SerializationException 版本迁移时容易出现 try { Servers = ServerCollection.Load(this.DataDir + "\\dp2batch_servers.bin", true); Servers.ownerForm = this; } catch (SerializationException ex) { MessageBox.Show(this, ex.Message); Servers = new ServerCollection(); // 设置文件名,以便本次运行结束时覆盖旧文件 Servers.FileName = this.DataDir + "\\dp2batch_servers.bin"; } this.Servers.ServerChanged += new ServerChangedEventHandle(Servers_ServerChanged); string strError = ""; int nRet = cfgCache.Load(this.DataDir + "\\cfgcache.xml", out strError); if (nRet == -1) { if (IsFirstRun == false) MessageBox.Show(strError + "\r\n\r\n程序稍后会尝试自动创建这个文件"); } cfgCache.TempDir = this.DataDir + "\\cfgcache"; cfgCache.InstantSave = true; // 设置窗口尺寸状态 if (AppInfo != null) { /* // 首次运行,尽量利用“微软雅黑”字体 if (this.IsFirstRun == true) { SetFirstDefaultFont(); } * */ SetFirstDefaultFont(); MainForm.SetControlFont(this, this.DefaultFont); AppInfo.LoadFormStates(this, "mainformstate"); } stopManager.Initial(this.toolBarButton_stop, this.toolStripStatusLabel_main, this.toolStripProgressBar_main); stopManager.LinkReverseButton(this.toolBarButton_begin); // //////////////// stop = new DigitalPlatform.Stop(); stop.Register(this.stopManager, true); // 和容器关联 this.Channels.AskAccountInfo += new AskAccountInfoEventHandle(this.Servers.OnAskAccountInfo); /* this.Channels.procAskAccountInfo = new Delegate_AskAccountInfo(this.Servers.AskAccountInfo); */ // 简单检索界面准备工作 treeView_rangeRes.stopManager = this.stopManager; treeView_rangeRes.Servers = this.Servers; // 引用 treeView_rangeRes.Channels = this.Channels; // 引用 treeView_rangeRes.AppInfo = this.AppInfo; // 2013/2/15 treeView_rangeRes.Fill(null); this.textBox_import_fileName.Text = AppInfo.GetString( "page_import", "source_file_name", ""); this.textBox_import_range.Text = AppInfo.GetString( "page_import", "range", ""); this.textBox_import_dbMap.Text = AppInfo.GetString( "page_import", "dbmap", "").Replace(";", "\r\n"); this.checkBox_import_fastMode.Checked = AppInfo.GetBoolean( "page_import", "fastmode", true); textBox_startNo.Text = AppInfo.GetString( "rangePage", "startNumber", ""); textBox_endNo.Text = AppInfo.GetString( "rangePage", "endNumber", ""); checkBox_verifyNumber.Checked = Convert.ToBoolean( AppInfo.GetInt( "rangePage", "verifyrange", 0) ); checkBox_forceLoop.Checked = Convert.ToBoolean( AppInfo.GetInt( "rangePage", "forceloop", 0) ); checkBox_export_delete.Checked = Convert.ToBoolean( AppInfo.GetInt( "rangePage", "delete", 0) ); this.checkBox_export_fastMode.Checked = AppInfo.GetBoolean( "rangePage", "fastmode", true); this.radioButton_all.Checked = Convert.ToBoolean( AppInfo.GetInt( "rangePage", "all", 0) ); strLastOutputFileName = AppInfo.GetString( "rangePage", "lastoutputfilename", ""); nLastOutputFilterIndex = AppInfo.GetInt( "rangePage", "lastoutputfilterindex", 1); scriptManager.applicationInfo = AppInfo; scriptManager.CfgFilePath = this.DataDir + "\\projects.xml"; scriptManager.DataDir = this.DataDir; scriptManager.CreateDefaultContent -= new CreateDefaultContentEventHandler(scriptManager_CreateDefaultContent); scriptManager.CreateDefaultContent += new CreateDefaultContentEventHandler(scriptManager_CreateDefaultContent); // 按照上次保存的路径展开resdircontrol树 string strResDirPath = AppInfo.GetString( "rangePage", "resdirpath", ""); if (strResDirPath != null) { object[] pList = { strResDirPath }; this.BeginInvoke(new Delegate_ExpandResDir(ExpandResDir), pList); } checkBox_export_delete_CheckedChanged(null, null); } void Servers_ServerChanged(object sender, ServerChangedEventArgs e) { this.treeView_rangeRes.Refresh(ResTree.RefreshStyle.All); } public delegate void Delegate_ExpandResDir(string strResDirPath); void ExpandResDir(string strResDirPath) { this.toolStripStatusLabel_main.Text = "正在展开资源目录 " + strResDirPath + ", 请稍候..."; this.Update(); ResPath respath = new ResPath(strResDirPath); EnableControls(false); // 展开到指定的节点 treeView_rangeRes.ExpandPath(respath); EnableControls(true); /* //Cursor.Current = Cursors.WaitCursor; dtlpResDirControl.ExpandPath(strResDirPath); //Cursor.Current = Cursors.Default; */ toolStripStatusLabel_main.Text = ""; } private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if (stop != null) { if (stop.State == 0 || stop.State == 1) { this.channel.Abort(); e.Cancel = true; } } } private void MainForm_Closed(object sender, System.EventArgs e) { this.Channels.AskAccountInfo -= new AskAccountInfoEventHandle(this.Servers.OnAskAccountInfo); this.Servers.ServerChanged -= new ServerChangedEventHandle(Servers_ServerChanged); // 保存到文件 // parameters: // strFileName 文件名。如果==null,表示使用装载时保存的那个文件名 Servers.Save(null); Servers = null; string strError; int nRet = cfgCache.Save(null, out strError); if (nRet == -1) MessageBox.Show(this, strError); // 保存窗口尺寸状态 if (AppInfo != null) { AppInfo.SaveFormStates(this, "mainformstate"); } AppInfo.SetString( "page_import", "source_file_name", this.textBox_import_fileName.Text); AppInfo.SetString( "page_import", "dbmap", this.textBox_import_dbMap.Text.Replace("\r\n", ";")); AppInfo.SetString( "page_import", "range", this.textBox_import_range.Text); AppInfo.SetBoolean( "page_import", "fastmode", this.checkBox_import_fastMode.Checked); AppInfo.SetString( "rangePage", "startNumber", textBox_startNo.Text); AppInfo.SetString( "rangePage", "endNumber", textBox_endNo.Text); AppInfo.SetInt( "rangePage", "verifyrange", Convert.ToInt32(checkBox_verifyNumber.Checked)); AppInfo.SetInt( "rangePage", "forceloop", Convert.ToInt32(checkBox_forceLoop.Checked)); AppInfo.SetInt( "rangePage", "delete", Convert.ToInt32(checkBox_export_delete.Checked)); AppInfo.SetBoolean( "rangePage", "fastmode", this.checkBox_export_fastMode.Checked); AppInfo.SetInt( "rangePage", "all", Convert.ToInt32(this.radioButton_all.Checked)); AppInfo.SetString( "rangePage", "lastoutputfilename", strLastOutputFileName); AppInfo.SetInt( "rangePage", "lastoutputfilterindex", nLastOutputFilterIndex); // 保存resdircontrol最后的选择 ResPath respath = new ResPath(treeView_rangeRes.SelectedNode); AppInfo.SetString( "rangePage", "resdirpath", respath.FullPath); //记住save,保存信息XML文件 AppInfo.Save(); AppInfo = null; // 避免后面再用这个对象 } #region 菜单命令 private void menuItem_cfg_Click(object sender, System.EventArgs e) { } private void menuItem_exit_Click(object sender, System.EventArgs e) { this.Close(); } #endregion private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e) { string strError = ""; if (e.Button == toolBarButton_stop) { stopManager.DoStopActive(); } if (e.Button == toolBarButton_begin) { // 出现对话框,询问Project名字 GetProjectNameDlg dlg = new GetProjectNameDlg(); MainForm.SetControlFont(dlg, this.DefaultFont); dlg.scriptManager = this.scriptManager; dlg.ProjectName = AppInfo.GetString( "main", "lastUsedProject", ""); dlg.NoneProject = Convert.ToBoolean(AppInfo.GetInt( "main", "lastNoneProjectState", 0)); this.AppInfo.LinkFormState(dlg, "GetProjectNameDlg_state"); dlg.ShowDialog(this); this.AppInfo.UnlinkFormState(dlg); if (dlg.DialogResult != DialogResult.OK) return; string strProjectName = ""; string strLocate = ""; // 方案文件目录 if (dlg.NoneProject == false) { // string strWarning = ""; strProjectName = dlg.ProjectName; // 获得方案参数 // strProjectNamePath 方案名,或者路径 // return: // -1 error // 0 not found project // 1 found int nRet = scriptManager.GetProjectData( strProjectName, out strLocate); if (nRet == 0) { strError = "方案 " + strProjectName + " 没有找到..."; goto ERROR1; } if (nRet == -1) { strError = "scriptManager.GetProjectData() error ..."; goto ERROR1; } } AppInfo.SetString( "main", "lastUsedProject", strProjectName); AppInfo.SetInt( "main", "lastNoneProjectState", Convert.ToInt32(dlg.NoneProject)); if (tabControl_main.SelectedTab == this.tabPage_range) { this.DoExport(strProjectName, strLocate); } else if (tabControl_main.SelectedTab == this.tabPage_import) { this.DoImport(strProjectName, strLocate); } } return; ERROR1: MessageBox.Show(this, strError); } void DoImport(string strProjectName, string strProjectLocate) { string strError = ""; int nRet = 0; Assembly assemblyMain = null; MyFilterDocument filter = null; this.MarcFilter = null; batchObj = null; m_nRecordCount = -1; // 准备脚本 if (strProjectName != "" && strProjectName != null) { nRet = PrepareScript(strProjectName, strProjectLocate, out assemblyMain, out filter, out batchObj, out strError); if (nRet == -1) goto ERROR1; this.AssemblyMain = assemblyMain; if (filter != null) this.AssemblyFilter = filter.Assembly; else this.AssemblyFilter = null; this.MarcFilter = filter; } // 执行脚本的OnInitial() // 触发Script中OnInitial()代码 // OnInitial()和OnBegin的本质区别, 在于OnInitial()适合检查和设置面板参数 if (batchObj != null) { BatchEventArgs args = new BatchEventArgs(); batchObj.OnInitial(this, args); /* if (args.Continue == ContinueType.SkipBeginMiddle) goto END1; if (args.Continue == ContinueType.SkipMiddle) { strError = "OnInitial()中args.Continue不能使用ContinueType.SkipMiddle.应使用ContinueType.SkipBeginMiddle"; goto ERROR1; } */ if (args.Continue == ContinueType.SkipAll) goto END1; } if (this.textBox_import_fileName.Text == "") { strError = "尚未指定输入文件名..."; goto ERROR1; } FileInfo fi = new FileInfo(this.textBox_import_fileName.Text); if (fi.Exists == false) { strError = "文件" + this.textBox_import_fileName.Text + "不存在..."; goto ERROR1; } OpenMarcFileDlg dlg = null; // ISO2709文件需要预先准备条件 if (String.Compare(fi.Extension, ".iso", true) == 0 || String.Compare(fi.Extension, ".mrc", true) == 0) { // 询问encoding和marcsyntax dlg = new OpenMarcFileDlg(); MainForm.SetControlFont(dlg, this.DefaultFont); dlg.Text = "请指定要导入的 ISO2709 文件属性"; dlg.FileName = this.textBox_import_fileName.Text; this.AppInfo.LinkFormState(dlg, "OpenMarcFileDlg_input_state"); dlg.ShowDialog(this); this.AppInfo.UnlinkFormState(dlg); if (dlg.DialogResult != DialogResult.OK) return; this.textBox_import_fileName.Text = dlg.FileName; this.CurMarcSyntax = dlg.MarcSyntax; } // 触发Script中OnBegin()代码 // OnBegin()中仍然有修改MainForm面板的自由 if (batchObj != null) { BatchEventArgs args = new BatchEventArgs(); batchObj.OnBegin(this, args); /* if (args.Continue == ContinueType.SkipMiddle) goto END1; if (args.Continue == ContinueType.SkipBeginMiddle) goto END1; */ if (args.Continue == ContinueType.SkipAll) goto END1; } if (String.Compare(fi.Extension, ".dp2bak", true) == 0) nRet = this.DoImportBackup(this.textBox_import_fileName.Text, out strError); else if (String.Compare(fi.Extension, ".xml", true) == 0) nRet = this.DoImportXml(this.textBox_import_fileName.Text, out strError); else if (String.Compare(fi.Extension, ".iso", true) == 0 || String.Compare(fi.Extension, ".mrc", true) == 0) { this.m_tableMarcSyntax.Clear(); // 2015/5/29 this.CheckTargetDb += new CheckTargetDbEventHandler(CheckTargetDbCallBack); try { nRet = this.DoImportIso2709(dlg.FileName, dlg.MarcSyntax, dlg.Encoding, out strError); } finally { this.CheckTargetDb -= new CheckTargetDbEventHandler(CheckTargetDbCallBack); } } else { strError = "未知的文件类型..."; goto ERROR1; } END1: // 触发Script的OnEnd()代码 if (batchObj != null) { BatchEventArgs args = new BatchEventArgs(); batchObj.OnEnd(this, args); } // END2: this.AssemblyMain = null; this.AssemblyFilter = null; if (filter != null) filter.Assembly = null; if (strError != "") MessageBox.Show(this, strError); this.MarcFilter = null; return; ERROR1: this.AssemblyMain = null; this.AssemblyFilter = null; if (filter != null) filter.Assembly = null; this.MarcFilter = null; MessageBox.Show(this, strError); } // 导入XML数据 // parameter: // strFileName: 要导入的源XML文件 // 说明: 导入数据是一个连续的过程, // 只要依据流的自然顺序依次上载每个记录就可以了。 int DoImportXml(string strFileName, out string strError) { int nRet; strError = ""; bool bFastMode = this.checkBox_import_fastMode.Checked; this.bNotAskTimestampMismatchWhenOverwrite = false; // 要询问 // 准备库名对照表 DbNameMap map = DbNameMap.Build(this.textBox_import_dbMap.Text.Replace("\r\n", ";"), out strError); if (map == null) return -1; int nReadRet = 0; using (Stream file = File.Open(strFileName, FileMode.Open, FileAccess.Read)) using (XmlTextReader reader = new XmlTextReader(file)) { // RangeList rl = null; long lMax = 0; long lMin = 0; long lSkipCount = 0; string strCount = ""; //范围 if (textBox_import_range.Text != "") { rl = new RangeList(textBox_import_range.Text); rl.Sort(); rl.Merge(); lMin = rl.min(); lMax = rl.max(); } stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在导入"); stop.BeginLoop(); stop.SetProgressRange(0, file.Length); EnableControls(false); WriteLog("开始导入XML数据"); bool bRet = false; // 移动到根元素 while (true) { bRet = reader.Read(); if (bRet == false) { strError = "没有根元素"; goto ERROR1; } if (reader.NodeType == XmlNodeType.Element) break; } // 移动到其下级第一个element while (true) { bRet = reader.Read(); if (bRet == false) { strError = "没有第一个记录元素"; goto END1; } if (reader.NodeType == XmlNodeType.Element) break; } this.m_nRecordCount = 0; for (long lCount = 0; ; lCount++) { bool bSkip = false; nReadRet = 0; Application.DoEvents(); // 出让界面控制权 if (stop.State != 0) { DialogResult result = MessageBox.Show(this, "确实要中断当前批处理操作?", "dp2batch", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResult.Yes) { strError = "用户中断"; nReadRet = 100; goto ERROR1; } else { stop.Continue(); } } //检索当前记录是否在处理范围内 if (rl != null) { if (lMax != -1) // -1:不确定 { if (lCount > lMax) nReadRet = 2; // 后面看到这个状态将会break。为什么不在这里break,就是为了后面显示label信息 } if (rl.IsInRange(lCount, true) == false) { bSkip = true; } } // progressBar_main.Value = (int)((file.Position)/ProgressRatio); stop.SetProgressValue(file.Position); // 显示信息 if (bSkip == true) { stop.SetMessage(((bSkip == true) ? "正在跳过 " : "正在处理") + Convert.ToString(lCount + 1)); } /* if (nReadRet == 2) goto CONTINUE; if (bSkip == true) goto CONTINUE; */ /* // 防止一条记录也没有的情况,所以把这个句写到前面 if (file.Position >= file.Length) break; */ // 上载一个Item nRet = DoXmlItemUpload( bFastMode, reader, map, bSkip == true || nReadRet == 2, strCount, out strError); if (nRet == -1) goto ERROR1; if (nRet == 1) break; strCount = "处理数 " + Convert.ToString(lCount - lSkipCount) + " / 跳过数 " + Convert.ToString(lSkipCount); if (bSkip) lSkipCount++; if (nReadRet == 1 || nReadRet == 2) //判断大文件结束 break; } } WriteLog("结束导入XML数据"); // TODO: 是否要放入 finally 中 END1: stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); EnableControls(true); strError = "恢复数据文件 '" + strFileName + "' 完成。"; return 0; ERROR1: stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); EnableControls(true); if (nReadRet == 100) strError = "恢复数据文件 '" + strFileName + "' 被中断。原因: " + strError; else strError = "恢复数据文件 '" + strFileName + "' 失败。原因: " + strError; return -1; } // 导入ISO2709数据 // parameter: // strFileName: 要导入的源ISO2709文件 int DoImportIso2709(string strFileName, string strMarcSyntax, Encoding encoding, out string strError) { int nRet; strError = ""; bool bFastMode = this.checkBox_import_fastMode.Checked; this.CurMarcSyntax = strMarcSyntax; // 为C#脚本调用GetMarc()等函数提供条件 this.bNotAskTimestampMismatchWhenOverwrite = false; // 要询问 // 准备库名对照表 DbNameMap map = DbNameMap.Build(this.textBox_import_dbMap.Text.Replace("\r\n", ";"), out strError); if (map == null) { strError = "根据库名映射规则创建库名对照表时出错: " + strError; return -1; } Stream file = File.Open(strFileName, FileMode.Open, FileAccess.Read); // RangeList rl = null; long lMax = 0; long lMin = 0; long lSkipCount = 0; int nReadRet = 0; string strCount = ""; //范围 if (textBox_import_range.Text != "") { rl = new RangeList(textBox_import_range.Text); rl.Sort(); rl.Merge(); lMin = rl.min(); lMax = rl.max(); } stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在导入"); stop.BeginLoop(); stop.SetProgressRange(0, file.Length); EnableControls(false); WriteLog("开始导入ISO2709格式数据"); try { // bool bRet = false; this.m_nRecordCount = 0; for (long lCount = 0; ; lCount++) { bool bSkip = false; nReadRet = 0; Application.DoEvents(); // 出让界面控制权 if (stop.State != 0) { DialogResult result = MessageBox.Show(this, "确实要中断当前批处理操作?", "dp2batch", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResult.Yes) { strError = "用户中断"; nReadRet = 100; goto ERROR1; } else { stop.Continue(); } } //检索当前记录是否在处理范围内 if (rl != null) { if (lMax != -1) // -1:不确定 { if (lCount > lMax) nReadRet = 2; // 后面看到这个状态将会break。为什么不在这里break,就是为了后面显示label信息 } if (rl.IsInRange(lCount, true) == false) { bSkip = true; } } // progressBar_main.Value = (int)((file.Position)/ProgressRatio); stop.SetProgressValue(file.Position); // 显示信息 if (bSkip == true) { stop.SetMessage(((bSkip == true) ? "正在跳过 " : "正在处理") + Convert.ToString(lCount + 1)); } /* // 防止一条记录也没有的情况,所以把这个句写到前面 if (file.Position >= file.Length) break; */ string strMARC = ""; // 从ISO2709文件中读入一条MARC记录 // return: // -2 MARC格式错 // -1 出错 // 0 正确 // 1 结束(当前返回的记录有效) // 2 结束(当前返回的记录无效) nRet = MarcUtil.ReadMarcRecord(file, encoding, true, // bRemoveEndCrLf, true, // bForce, out strMARC, out strError); if (nRet == -2 || nRet == -1) { DialogResult result = MessageBox.Show(this, "读入MARC记录(" + lCount.ToString() + ")出错: " + strError + "\r\n\r\n确实要中断当前批处理操作?", "dp2batch", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResult.Yes) { break; } else continue; } if (nRet != 0 && nRet != 1) break; if (this.batchObj != null) { batchObj.MarcRecord = strMARC; batchObj.MarcRecordChanged = false; batchObj.MarcSyntax = strMarcSyntax; } string strXml = ""; // 将MARC记录转换为xml格式 nRet = MarcUtil.Marc2Xml(strMARC, strMarcSyntax, out strXml, out strError); if (nRet == -1) goto ERROR1; // TODO: 能利用MARC记录中的-01字段,进行覆盖操作 // 难点有两个:1)原来有若干个-01,要根据条件(指定的目标库)筛选出一个 2) dt1000的-01中只能库名,无法容纳web service url名 // 上载一个Item nRet = DoXmlItemUpload( bFastMode, strXml, map, bSkip == true || nReadRet == 2, strCount, out strError); if (nRet == -1) goto ERROR1; if (nRet == 1) break; strCount = "处理数 " + Convert.ToString(lCount - lSkipCount) + " / 跳过数 " + Convert.ToString(lSkipCount); if (bSkip) lSkipCount++; if (nReadRet == 1 || nReadRet == 2) //判断大文件结束 break; } } finally { file.Close(); WriteLog("结束导入ISO2709格式数据"); } stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); EnableControls(true); strError = "恢复数据文件 '" + strFileName + "' 完成。"; return 0; ERROR1: stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); EnableControls(true); if (nReadRet == 100) strError = "恢复数据文件 '" + strFileName + "' 被中断: " + strError; else strError = "恢复数据文件 '" + strFileName + "' 出错: " + strError; return -1; } // 上载一个item // parameter: // strError: error info // return: // -1 出错 // 0 正常 // 1 结束 public int DoXmlItemUpload( bool bFastMode, XmlTextReader reader, DbNameMap map, bool bSkip, string strCount, out string strError) { strError = ""; bool bRet = false; while (true) { if (reader.NodeType == XmlNodeType.Element) break; bRet = reader.Read(); if (bRet == false) return 1; } /* if (bRet == false) return 1; // 结束 * */ string strXml = reader.ReadOuterXml(); return DoXmlItemUpload( bFastMode, strXml, map, bSkip, strCount, out strError); } public SearchPanel SearchPanel { get { SearchPanel searchpanel = new SearchPanel(); searchpanel.Initial(this.Servers, this.cfgCache); // 此时searchpanel.ServerUrl未定 return searchpanel; } } // 检查目标库事件 void CheckTargetDbCallBack(object sender, CheckTargetDbEventArgs e) { string strMarcSyntax = (string)m_tableMarcSyntax[e.DbFullPath]; if (strMarcSyntax == null) { string strError = ""; // 从marcdef配置文件中获得marc格式定义 // return: // -1 出错 // 0 没有找到 // 1 找到 int nRet = this.SearchPanel.GetMarcSyntax(e.DbFullPath, out strMarcSyntax, out strError); if (nRet == 0 || nRet == -1) { e.Cancel = true; e.ErrorInfo = strError; return; } m_tableMarcSyntax[e.DbFullPath] = strMarcSyntax; } // if (String.Compare(this.CurMarcSyntax, strMarcSyntax, true) != 0) if (String.Compare(e.CurrentMarcSyntax, strMarcSyntax, true) != 0) { e.Cancel = true; // e.ErrorInfo = "您选择的 MARC 格式 '" + this.CurMarcSyntax + "' 和目标库 '" + e.DbFullPath + "' 中的 cfgs/marcdef 配置文件中定义的 MARC 格式 '" + strMarcSyntax + "' 不吻合, 操作被迫中断"; e.ErrorInfo = "您选择的 MARC 格式 '" + e.CurrentMarcSyntax + "' 和目标库 '" + e.DbFullPath + "' 中的 cfgs/marcdef 配置文件中定义的 MARC 格式 '" + strMarcSyntax + "' 不吻合, 操作被迫中断"; return; } } // 覆盖一条XML记录 int DoOverwriteXmlRecord( bool bFastMode, string strRecFullPath, string strXmlBody, byte[] timestamp, out string strError) { strError = ""; ResPath respath = new ResPath(strRecFullPath); RmsChannel channelSave = channel; channel = this.Channels.GetChannel(respath.Url); try { string strWarning = ""; byte[] output_timestamp = null; string strOutputPath = ""; REDOSAVE: // 保存Xml记录 long lRet = channel.DoSaveTextRes(respath.Path, strXmlBody, false, // bIncludePreamble bFastMode == true ? "fastmode" : "",//strStyle, timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { if (stop != null) stop.Continue(); if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { string strDisplayRecPath = strOutputPath; if (string.IsNullOrEmpty(strDisplayRecPath) == true) strDisplayRecPath = respath.Path; if (this.bNotAskTimestampMismatchWhenOverwrite == true) { timestamp = new byte[output_timestamp.Length]; Array.Copy(output_timestamp, 0, timestamp, 0, output_timestamp.Length); strWarning = " (时间戳不匹配, 自动重试)"; goto REDOSAVE; } DialogResult result = MessageDlg.Show(this, "上载 '" + strDisplayRecPath + " 时发现时间戳不匹配。详细情况如下:\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 = " (时间戳不匹配, 应用户要求重试)"; goto REDOSAVE; } if (result == DialogResult.No) { return 0; // 继续作后面的资源 } if (result == DialogResult.Cancel) { strError = "用户中断"; goto ERROR1; // 中断整个处理 } } // 询问是否重试 DialogResult result1 = MessageBox.Show(this, "上载 '" + respath.Path + " 时发生错误。详细情况如下:\r\n---\r\n" + strError + "\r\n---\r\n\r\n是否重试?\r\n注:(是)重试 (否)不重试,但继续后面的处理 (取消)中断整个批处理", "dp2batch", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (result1 == DialogResult.Yes) goto REDOSAVE; if (result1 == DialogResult.No) return 0; // 继续作后面的资源 goto ERROR1; } return 0; ERROR1: return -1; } finally { channel = channelSave; } } // 上载一个item // parameter: // strError: error info // return: // -1 出错 // 0 正常 // 1 结束 public int DoXmlItemUpload( bool bFastMode, string strXml, DbNameMap map, bool bSkip, string strCount, out string strError) { strError = ""; int nRet = 0; // bool bRet = false; // MessageBox.Show(this, strXml); if (bSkip == true) return 0; XmlDocument dataDom = new XmlDocument(); try { dataDom.LoadXml(strXml); } catch (Exception ex) { strError = "加载数据到dom出错!\r\n" + ex.Message; goto ERROR1; } XmlNode node = dataDom.DocumentElement; string strResPath = DomUtil.GetAttr(DpNs.dprms, node, "path"); string strTargetPath = ""; string strSourceDbPath = ""; if (strResPath != "") { // 从map中查询覆盖还是追加? ResPath respath0 = new ResPath(strResPath); respath0.MakeDbName(); strSourceDbPath = respath0.FullPath; } REDO: DbNameMapItem mapItem = null; mapItem = map.MatchItem(strSourceDbPath/*strResPath*/); if (mapItem != null) goto MAPITEMOK; if (mapItem == null) { if (strSourceDbPath/*strResPath*/ == "") { string strText = "源数据文件中记录 " + Convert.ToString(this.m_nRecordCount) + " 没有来源数据库,对所有这样的数据,将作如何处理?"; WriteLog("打开对话框 '" + strText.Replace("\r\n", "\\n") + "'"); nRet = DbNameMapItemDlg.AskNullOriginBox( this, this.AppInfo, strText, this.SearchPanel, map); WriteLog("关闭对话框 '" + strText.Replace("\r\n", "\\n") + "'"); if (nRet == 0) { strError = "用户中断"; goto ERROR1; // 中断整个处理 } goto REDO; } else { string strText = "源数据文件中记录 " + Convert.ToString(this.m_nRecordCount) + " 的来源数据库 '" + strSourceDbPath/*strResPath*/ + "' 没有找到对应的目标库, 对所有这样的数据,将作如何处理?"; WriteLog("打开对话框 '" + strText.Replace("\r\n", "\\n") + "'"); nRet = DbNameMapItemDlg.AskNotMatchOriginBox( this, this.AppInfo, strText, this.SearchPanel, strSourceDbPath/*strResPath*/, map); WriteLog("关闭对话框 '" + strText.Replace("\r\n", "\\n") + "'"); if (nRet == 0) { strError = "用户中断"; goto ERROR1; // 中断整个处理 } goto REDO; } } MAPITEMOK: if (mapItem.Style == "skip") return 0; // 构造目标路径 // 1)从源路径中提取id。源路径来自备份文件数据 ResPath respath = new ResPath(strResPath); string strID = respath.GetRecordId(); if (strID == null || strID == "" || (mapItem.Style == "append") ) { strID = "?"; // 将来加一个对话框 } // 2)用目标库路径构造完整的记录路径 string strTargetFullPath = ""; if (mapItem.Target == "*") { // 此时target为*, 需要从strResPath中获得库名 if (strResPath == "") { Debug.Assert(false, "不可能出现的情况"); } respath = new ResPath(strResPath); respath.MakeDbName(); strTargetFullPath = respath.FullPath; } else { strTargetFullPath = mapItem.Target; } respath = new ResPath(strTargetFullPath); // 需要检查目标库所允许的MARC格式 if (CheckTargetDb != null) { CheckTargetDbEventArgs e = new CheckTargetDbEventArgs(); e.DbFullPath = strTargetFullPath; e.CurrentMarcSyntax = this.CurMarcSyntax; this.CheckTargetDb(this, e); if (e.Cancel == true) { if (e.ErrorInfo == "") strError = "CheckTargetDb 事件导致中断"; else strError = e.ErrorInfo; return -1; } } strTargetPath = respath.Path + "/" + strID; // strRecordPath = strTargetPath; channel = this.Channels.GetChannel(respath.Url); string strTimeStamp = DomUtil.GetAttr(DpNs.dprms, node, "timestamp"); byte[] timestamp = ByteArray.GetTimeStampByteArray(strTimeStamp); // 2012/5/29 string strOutMarcSyntax = ""; string strMARC = ""; // 将MARCXML格式的xml记录转换为marc机内格式字符串 // parameters: // bWarning ==true, 警告后继续转换,不严格对待错误; = false, 非常严格对待错误,遇到错误后不继续转换 // strMarcSyntax 指示marc语法,如果=="",则自动识别 // strOutMarcSyntax out参数,返回marc,如果strMarcSyntax == "",返回找到marc语法,否则返回与输入参数strMarcSyntax相同的值 nRet = MarcUtil.Xml2Marc(strXml, false, "", out strOutMarcSyntax, out strMARC, out strError); /* if (nRet == -1) return -1; * */ // 2012/5/30 if (batchObj != null) { batchObj.MarcSyntax = strOutMarcSyntax; batchObj.MarcRecord = strMARC; batchObj.MarcRecordChanged = false; // 为本轮Script运行准备初始状态 } if (this.MarcFilter != null) { // 触发filter中的Record相关动作 nRet = MarcFilter.DoRecord( null, batchObj.MarcRecord, m_nRecordCount, out strError); if (nRet == -1) goto ERROR1; } // C#脚本 -- Inputing if (this.AssemblyMain != null) { // 这些变量要先初始化,因为filter代码可能用到这些Batch成员. batchObj.SkipInput = false; batchObj.XmlRecord = strXml; //batchObj.MarcSyntax = this.CurMarcSyntax; //batchObj.MarcRecord = strMarc; // MARC记录体 //batchObj.MarcRecordChanged = false; // 为本轮Script运行准备初始状态 batchObj.SearchPanel.ServerUrl = channel.Url; batchObj.ServerUrl = channel.Url; batchObj.RecPath = strTargetPath; // 记录路径 batchObj.RecIndex = m_nRecordCount; // 当前记录在一批中的序号 batchObj.TimeStamp = timestamp; BatchEventArgs args = new BatchEventArgs(); batchObj.Inputing(this, args); if (args.Continue == ContinueType.SkipAll) { strError = "脚本中断SkipAll"; goto END2; } if (batchObj.SkipInput == true) return 0; // 继续处理后面的 } string strWarning = ""; byte[] output_timestamp = null; string strOutputPath = ""; REDOSAVE: if (stop != null) { if (strTargetPath.IndexOf("?") == -1) { stop.SetMessage("正在上载 " + strTargetPath + strWarning + " " + strCount); } } // 保存Xml记录 long lRet = channel.DoSaveTextRes(strTargetPath, strXml, false, // bIncludePreamble bFastMode == true ? "fastmode" : "",//strStyle, timestamp, out output_timestamp, out strOutputPath, out strError); if (lRet == -1) { if (stop != null) stop.Continue(); if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { string strDisplayRecPath = strOutputPath; if (string.IsNullOrEmpty(strDisplayRecPath) == true) strDisplayRecPath = strTargetPath; if (this.bNotAskTimestampMismatchWhenOverwrite == true) { timestamp = new byte[output_timestamp.Length]; Array.Copy(output_timestamp, 0, timestamp, 0, output_timestamp.Length); strWarning = " (时间戳不匹配, 自动重试)"; goto REDOSAVE; } string strText = "上载 '" + strDisplayRecPath + " 时发现时间戳不匹配。详细情况如下:\r\n---\r\n" + strError + "\r\n---\r\n\r\n是否以新时间戳强行上载?\r\n注:(是)强行上载 (否)忽略当前记录或资源上载,但继续后面的处理 (取消)中断整个批处理"; WriteLog("打开对话框 '" + strText.Replace("\r\n", "\\n") + "'"); DialogResult result = MessageDlg.Show(this, strText, "dp2batch", MessageBoxButtons.YesNoCancel, MessageBoxDefaultButton.Button1, ref this.bNotAskTimestampMismatchWhenOverwrite); WriteLog("关闭对话框 '" + strText.Replace("\r\n", "\\n") + "'"); if (result == DialogResult.Yes) { timestamp = new byte[output_timestamp.Length]; Array.Copy(output_timestamp, 0, timestamp, 0, output_timestamp.Length); strWarning = " (时间戳不匹配, 应用户要求重试)"; goto REDOSAVE; } if (result == DialogResult.No) { return 0; // 继续作后面的资源 } if (result == DialogResult.Cancel) { strError = "用户中断"; goto ERROR1; // 中断整个处理 } } // 询问是否重试 { string strText = "上载 '" + strTargetPath + " 时发生错误。详细情况如下:\r\n---\r\n" + strError + "\r\n---\r\n\r\n是否重试?\r\n注:(是)重试 (否)不重试,但继续后面的处理 (取消)中断整个批处理"; WriteLog("打开对话框 '" + strText.Replace("\r\n", "\\n") + "'"); DialogResult result1 = MessageBox.Show(this, strText, "dp2batch", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); WriteLog("关闭对话框 '" + strText.Replace("\r\n", "\\n") + "'"); if (result1 == DialogResult.Yes) goto REDOSAVE; if (result1 == DialogResult.No) return 0; // 继续作后面的资源 } goto ERROR1; } // C#脚本 -- Inputed() if (this.AssemblyMain != null) { // 大部分变量保留刚才Inputing()时的原样,只修改部分 batchObj.RecPath = strOutputPath; // 记录路径 batchObj.TimeStamp = output_timestamp; BatchEventArgs args = new BatchEventArgs(); batchObj.Inputed(this, args); /* if (args.Continue == ContinueType.SkipMiddle) { strError = "脚本中断SkipMiddle"; goto END1; } if (args.Continue == ContinueType.SkipBeginMiddle) { strError = "脚本中断SkipBeginMiddle"; goto END1; } */ if (args.Continue == ContinueType.SkipAll) { strError = "脚本中断SkipAll"; goto END1; } } this.m_nRecordCount++; if (stop != null) { stop.SetMessage("已上载成功 '" + strOutputPath + "' " + strCount); } // strRecordPath = strOutputPath; return 0; END1: END2: ERROR1: return -1; } // 导入数据 // parameter: // strFileName: 要恢复的源备份文件 // 说明: 导入数据是一个连续的过程, // 只要依据流的自然顺序依次上载每个记录就可以了。 int DoImportBackup(string strFileName, out string strError) { int nRet; strError = ""; this.bNotAskTimestampMismatchWhenOverwrite = false; // 要询问 // 准备库名对照表 DbNameMap map = DbNameMap.Build(this.textBox_import_dbMap.Text.Replace("\r\n", ";"), out strError); if (map == null) return -1; Stream file = File.Open(strFileName, FileMode.Open, FileAccess.Read); // RangeList rl = null; long lMax = 0; long lMin = 0; long lSkipCount = 0; int nReadRet = 0; string strCount = ""; //范围 if (textBox_import_range.Text != "") { rl = new RangeList(textBox_import_range.Text); rl.Sort(); rl.Merge(); lMin = rl.min(); lMax = rl.max(); } stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在导入"); stop.BeginLoop(); stop.SetProgressRange(0, file.Length); EnableControls(false); WriteLog("开始导入.dp2bak格式数据"); try { this.m_nRecordCount = 0; for (long lCount = 0; ; lCount++) { bool bSkip = false; nReadRet = 0; Application.DoEvents(); // 出让界面控制权 if (stop.State != 0) { DialogResult result = MessageBox.Show(this, "确实要中断当前批处理操作?", "dp2batch", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResult.Yes) { strError = "用户中断"; nReadRet = 100; goto ERROR1; } else { stop.Continue(); } } //检索当前记录是否在处理范围内 if (rl != null) { if (lMax != -1) // -1:不确定 { if (lCount > lMax) nReadRet = 2; // 后面看到这个状态将会break。为什么不在这里break,就是为了后面显示label信息 } if (rl.IsInRange(lCount, true) == false) { bSkip = true; } } // progressBar_main.Value = (int)((file.Position)/ProgressRatio); stop.SetProgressValue(file.Position); // 显示信息 if (bSkip == true) { stop.SetMessage(((bSkip == true) ? "正在跳过 " : "正在处理") + Convert.ToString(lCount + 1)); } // 防止一条记录也没有的情况,所以把这个句写到前面 if (file.Position >= file.Length) break; // 上载一个Item nRet = DoBackupItemUpload(file, ref map, bSkip == true || nReadRet == 2, strCount, out strError); if (nRet == -1) goto ERROR1; Debug.Assert(file.Position <= file.Length, "经过DoBackupItemUpload()方法后, file的当前位置处在非法位置"); if (bSkip) lSkipCount++; strCount = "处理数 " + Convert.ToString(lCount - lSkipCount) + " / 跳过数 " + Convert.ToString(lSkipCount); if (nReadRet == 1 || nReadRet == 2) //判断大文件结束 break; } } finally { file.Close(); WriteLog("结束导入.dp2bak格式数据"); } stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); EnableControls(true); strError = "恢复数据文件 '" + strFileName + "' 完成。"; return 0; ERROR1: stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); EnableControls(true); if (nReadRet == 100) strError = "恢复数据文件 '" + strFileName + "' 被中断: " + strError; else strError = "恢复数据文件 '" + strFileName + "' 出错: " + strError; return -1; } // 上载一个item // parameter: // file: 源数据文件流 // strError: error info // return: // -1: error // 0: successed public int DoBackupItemUpload(Stream file, ref DbNameMap map, // 2007/6/5 bool bSkip, string strCount, out string strError) { strError = ""; long lStart = file.Position; byte[] data = new byte[8]; int nRet = file.Read(data, 0, 8); if (nRet == 0) return 1; // 已经结束 if (nRet < 8) { strError = "read file error..."; return -1; } // 毛长度 long lLength = BitConverter.ToInt64(data, 0); // +8可能是一个bug!!! if (bSkip == true) { file.Seek(lLength, SeekOrigin.Current); return 0; } this.channel = null; string strRecordPath = ""; for (int i = 0; ; i++) { Application.DoEvents(); // 出让界面控制权 if (stop.State != 0) { DialogResult result = MessageBox.Show(this, "确实要中断当前批处理操作?", "dp2batch", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResult.Yes) { strError = "用户中断"; return -1; } else { stop.Continue(); } } // progressBar_main.Value = (int)((file.Position)/ProgressRatio); stop.SetProgressValue(file.Position); if (file.Position - lStart >= lLength + 8) // 2006/8/29 changed break; // 上载对象资源 nRet = this.DoResUpload( ref this.channel, ref strRecordPath, file, ref map, // 2007/6/5 ref i == 0 ? true : false, strCount, out strError); if (nRet == -1) return -1; } return 0; } // 上载一个res // parameter: // inputfile: 源流 // bIsFirstRes: 是否是第一个资源(xml) // strError: error info // return: // -2 片断中发现时间戳不匹配。本函数调主可重上载整个资源 // -1 error // 0 successed public int DoResUpload( ref RmsChannel channel, ref string strRecordPath, Stream inputfile, ref DbNameMap map, bool bIsFirstRes, string strCount, out string strError) { strError = ""; int nRet; long lBodyStart = 0; long lBodyLength = 0; // 1. 从输入流中得到strMetadata,与body(body放到一个临时文件里) string strMetaDataXml = ""; nRet = GetResInfo(inputfile, bIsFirstRes, out strMetaDataXml, out lBodyStart, out lBodyLength, out strError); if (nRet == -1) goto ERROR1; if (lBodyLength == 0) return 0; // 空包不需上载 // 2.为上载做准备 XmlDocument metadataDom = new XmlDocument(); try { metadataDom.LoadXml(strMetaDataXml); } catch (Exception ex) { strError = "加载元数据到dom出错!\r\n" + ex.Message; goto ERROR1; } XmlNode node = metadataDom.DocumentElement; string strResPath = DomUtil.GetAttr(node, "path"); string strTargetPath = ""; if (bIsFirstRes == true) // 第一个资源 { // 从map中查询覆盖还是追加? ResPath respath = new ResPath(strResPath); respath.MakeDbName(); REDO: DbNameMapItem mapItem = (DbNameMapItem)map["*"]; if (mapItem != null) { } else { mapItem = (DbNameMapItem)map[respath.FullPath.ToUpper()]; } if (mapItem == null) { OriginNotFoundDlg dlg = new OriginNotFoundDlg(); MainForm.SetControlFont(dlg, this.DefaultFont); dlg.Message = "数据中声明的数据库路径 '" + respath.FullPath + "' 在覆盖关系对照表中没有找到, 请选择覆盖方式: "; dlg.Origin = respath.FullPath.ToUpper(); dlg.Servers = this.Servers; dlg.Channels = this.Channels; dlg.Map = map; dlg.StartPosition = FormStartPosition.CenterScreen; dlg.ShowDialog(this); if (dlg.DialogResult != DialogResult.OK) { strError = "用户中断..."; goto ERROR1; } map = dlg.Map; goto REDO; } if (mapItem.Style == "skip") return 0; // 构造目标路径 // 1)从源路径中提取id。源路径来自备份文件数据 respath = new ResPath(strResPath); string strID = respath.GetRecordId(); if (strID == null || strID == "" || (mapItem.Style == "append") ) { strID = "?"; // 将来加一个对话框 } // 2)用目标库路径构造完整的记录路径 string strTargetFullPath = ""; if (mapItem.Target == "*") { respath = new ResPath(strResPath); respath.MakeDbName(); strTargetFullPath = respath.FullPath; } else { strTargetFullPath = mapItem.Target; } respath = new ResPath(strTargetFullPath); strTargetPath = respath.Path + "/" + strID; strRecordPath = strTargetPath; channel = this.Channels.GetChannel(respath.Url); } else // 第二个以后的资源 { if (channel == null) { strError = "当bIsFirstRes==false时,参数channel不应为null..."; goto ERROR1; } ResPath respath = new ResPath(strResPath); string strObjectId = respath.GetObjectId(); if (strObjectId == null || strObjectId == "") { strError = "object id为空..."; goto ERROR1; } strTargetPath = strRecordPath + "/object/" + strObjectId; if (strRecordPath == "") { strError = "strRecordPath参数值为空..."; goto ERROR1; } } // string strLocalPath = DomUtil.GetAttr(node,"localpath"); // string strMimeType = DomUtil.GetAttr(node,"mimetype"); string strTimeStamp = DomUtil.GetAttr(node, "timestamp"); // 注意,strLocalPath并不是要上载的body文件,它只用来作元数据\ // body文件为strBodyTempFileName // 3.将body文件拆分成片断进行上载 string[] ranges = null; if (lBodyLength == 0) { // 空文件 ranges = new string[1]; ranges[0] = ""; } else { string strRange = ""; strRange = "0-" + Convert.ToString(lBodyLength - 1); // 按照100K作为一个chunk ranges = RangeList.ChunkRange(strRange, 100 * 1024 ); } byte[] timestamp = ByteArray.GetTimeStampByteArray(strTimeStamp); byte[] output_timestamp = null; REDOWHOLESAVE: string strOutputPath = ""; string strWarning = ""; for (int j = 0; j < ranges.Length; j++) { REDOSINGLESAVE: Application.DoEvents(); // 出让界面控制权 if (stop.State != 0) { DialogResult result = MessageBox.Show(this, "确实要中断当前批处理操作?", "dp2batch", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResult.Yes) { strError = "用户中断"; goto ERROR1; } else { stop.Continue(); } } string strWaiting = ""; if (j == ranges.Length - 1) strWaiting = " 请耐心等待..."; string strPercent = ""; RangeList rl = new RangeList(ranges[j]); if (rl.Count >= 1) { double ratio = (double)((RangeItem)rl[0]).lStart / (double)lBodyLength; strPercent = String.Format("{0,3:N}", ratio * (double)100) + "%"; } if (stop != null) stop.SetMessage("正在上载 " + ranges[j] + "/" + Convert.ToString(lBodyLength) + " " + strPercent + " " + strTargetPath + strWarning + strWaiting + " " + strCount); inputfile.Seek(lBodyStart, SeekOrigin.Begin); long lRet = channel.DoSaveResObject(strTargetPath, inputfile, lBodyLength, "", // style strMetaDataXml, ranges[j], j == ranges.Length - 1 ? true : false, // 最尾一次操作,提醒底层注意设置特殊的WebService API超时时间 timestamp, out output_timestamp, out strOutputPath, out strError); // progressBar_main.Value = (int)((inputfile.Position)/ProgressRatio); stop.SetProgressValue(inputfile.Position); strWarning = ""; if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { string strDisplayRecPath = strOutputPath; if (string.IsNullOrEmpty(strDisplayRecPath) == true) strDisplayRecPath = strTargetPath; 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, "上载 '" + strDisplayRecPath + "' (片断:" + ranges[j] + "/总尺寸:" + Convert.ToString(lBodyLength) + ") 时发现时间戳不匹配。详细情况如下:\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) { if (output_timestamp != null) { timestamp = new byte[output_timestamp.Length]; Array.Copy(output_timestamp, 0, timestamp, 0, output_timestamp.Length); } else { timestamp = output_timestamp; } strWarning = " (时间戳不匹配, 应用户要求重试)"; if (ranges.Length == 1 || j == 0) goto REDOSINGLESAVE; goto REDOWHOLESAVE; } if (result == DialogResult.No) { return 0; // 继续作后面的资源 } if (result == DialogResult.Cancel) { strError = "用户中断"; goto ERROR1; // 中断整个处理 } } goto ERROR1; } timestamp = output_timestamp; } // 考虑到保存第一个资源的时候,id可能为“?”,因此需要得到实际的id值 if (bIsFirstRes) strRecordPath = strOutputPath; return 0; ERROR1: return -1; } // 从输入流中得到一个res的metadata和body // parameter: // inputfile: 源流 // bIsFirstRes: 是否是第一个资源 // strMetaDataXml: 返回metadata内容 // strError: error info // return: // -1: error // 0: successed public static int GetResInfo(Stream inputfile, bool bIsFirstRes, out string strMetaDataXml, out long lBodyStart, out long lBodyLength, out string strError) { strMetaDataXml = ""; strError = ""; lBodyStart = 0; lBodyLength = 0; byte[] length = new byte[8]; // 读入总长度 int nRet = inputfile.Read(length, 0, 8); if (nRet < 8) { strError = "读取res总长度部分出错..."; return -1; } long lTotalLength = BitConverter.ToInt64(length, 0); // 读入metadata长度 nRet = inputfile.Read(length, 0, 8); if (nRet < 8) { strError = "读取metadata长度部分出错..."; return -1; } long lMetaDataLength = BitConverter.ToInt64(length, 0); if (lMetaDataLength >= 100 * 1024) { strError = "metadata数据长度超过100K,似不是正确格式..."; return -1; } byte[] metadata = new byte[(int)lMetaDataLength]; int nReadLength = inputfile.Read(metadata, 0, (int)lMetaDataLength); if (nReadLength < (int)lMetaDataLength) { strError = "metadata声明的长度超过文件末尾,格式错误"; return -1; } strMetaDataXml = Encoding.UTF8.GetString(metadata); // ? 是否可能抛出异常 // 读body部分的长度 nRet = inputfile.Read(length, 0, 8); if (nRet < 8) { strError = "读取body长度部分出错..."; return -1; } lBodyStart = inputfile.Position; lBodyLength = BitConverter.ToInt64(length, 0); if (bIsFirstRes == true && lBodyLength >= 2000 * 1024) { strError = "第一个res中body的xml数据长度超过2000K,似不是正确格式..."; return -1; } return 0; } // 管理库名对照表 private void button_import_dbMap_Click(object sender, System.EventArgs e) { DbNameMapDlg dlg = new DbNameMapDlg(); MainForm.SetControlFont(dlg, this.DefaultFont); string strError = ""; dlg.SearchPanel = this.SearchPanel; dlg.DbNameMap = DbNameMap.Build(this.textBox_import_dbMap.Text.Replace("\r\n", ";"), out strError); if (dlg.DbNameMap == null) { MessageBox.Show(this, strError); return; } this.AppInfo.LinkFormState(dlg, "DbNameMapDlg_state"); dlg.ShowDialog(this); this.AppInfo.UnlinkFormState(dlg); if (dlg.DialogResult != DialogResult.OK) return; this.textBox_import_dbMap.Text = dlg.DbNameMap.ToString(true).Replace(";", "\r\n"); } /* void oldfindTargetDB() { OpenResDlg dlg = new OpenResDlg(); dlg.Text = "请选择目标数据库"; dlg.EnabledIndices = new int[] { ResTree.RESTYPE_DB }; dlg.ap = this.applicationInfo; dlg.ApCfgTitle = "pageimport_openresdlg"; dlg.MultiSelect = true; dlg.Paths = textBox_import_targetDB.Text; dlg.Initial( this.Servers, this.Channels); // dlg.StartPosition = FormStartPosition.CenterScreen; dlg.ShowDialog(this); if (dlg.DialogResult != DialogResult.OK) return; textBox_import_targetDB.Text = dlg.Paths; } */ void DoStop(object sender, StopEventArgs e) { if (this.channel != null) this.channel.Abort(); } private void button_import_findFileName_Click(object sender, System.EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.FileName = textBox_import_fileName.Text; dlg.Filter = "备份文件 (*.dp2bak)|*.dp2bak|XML文件 (*.xml)|*.xml|ISO2709文件 (*.iso;*.mrc)|*.iso;*.mrc|All files (*.*)|*.*"; dlg.RestoreDirectory = true; if (dlg.ShowDialog() != DialogResult.OK) { return; } textBox_import_fileName.Text = dlg.FileName; } // 准备脚本环境 int PrepareScript(string strProjectName, string strProjectLocate, out Assembly assemblyMain, out MyFilterDocument filter, out Batch batchObj, out string strError) { assemblyMain = null; Assembly assemblyFilter = null; filter = null; batchObj = null; string strWarning = ""; string strMainCsDllName = strProjectLocate + "\\~main_" + Convert.ToString(m_nAssemblyVersion++) + ".dll"; string strLibPaths = "\"" + this.DataDir + "\"" + "," + "\"" + strProjectLocate + "\""; string[] saAddRef = { Environment.CurrentDirectory + "\\digitalplatform.marcdom.dll", Environment.CurrentDirectory + "\\digitalplatform.marckernel.dll", Environment.CurrentDirectory + "\\digitalplatform.rms.Client.dll", Environment.CurrentDirectory + "\\digitalplatform.library.dll", // Environment.CurrentDirectory + "\\digitalplatform.statis.dll", Environment.CurrentDirectory + "\\digitalplatform.dll", Environment.CurrentDirectory + "\\digitalplatform.Text.dll", Environment.CurrentDirectory + "\\digitalplatform.IO.dll", Environment.CurrentDirectory + "\\digitalplatform.Xml.dll", // Environment.CurrentDirectory + "\\Interop.SHDocVw.dll", Environment.CurrentDirectory + "\\dp2batch.exe"}; // 创建Project中Script main.cs的Assembly // return: // -2 出错,但是已经提示过错误信息了。 // -1 出错 int nRet = scriptManager.BuildAssembly( "MainForm", strProjectName, "main.cs", saAddRef, strLibPaths, strMainCsDllName, out strError, out strWarning); if (nRet == -2) goto ERROR1; if (nRet == -1) { if (strWarning == "") goto ERROR1; MessageBox.Show(this, strWarning); } assemblyMain = Assembly.LoadFrom(strMainCsDllName); if (assemblyMain == null) { strError = "LoadFrom " + strMainCsDllName + " fail"; goto ERROR1; } // 得到Assembly中Batch派生类Type Type entryClassType = ScriptManager.GetDerivedClassType( assemblyMain, "dp2Batch.Batch"); // new一个Batch派生对象 batchObj = (Batch)entryClassType.InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, null); // 为Batch派生类设置参数 batchObj.MainForm = this; batchObj.ap = this.AppInfo; batchObj.ProjectDir = strProjectLocate; batchObj.DbPath = this.textBox_dbPath.Text; batchObj.SearchPanel = this.SearchPanel; /* batchObj.SearchPanel.InitialStopManager(this.toolBarButton_stop, this.statusBar_main); */ // batchObj.Channel = channel; //batchObj.GisIniFilePath = applicationInfo.GetString( // "preference", // "gisinifilepath", // ""); //////////////////////////// // 装载marfilter.fltx string strFilterFileName = strProjectLocate + "\\marcfilter.fltx"; if (FileUtil.FileExist(strFilterFileName) == true) { filter = new MyFilterDocument(); filter.Batch = batchObj; filter.strOtherDef = entryClassType.FullName + " Batch = null;"; filter.strPreInitial = " MyFilterDocument doc = (MyFilterDocument)this.Document;\r\n"; filter.strPreInitial += " Batch = (" + entryClassType.FullName + ")doc.Batch;\r\n"; filter.Load(strFilterFileName); nRet = filter.BuildScriptFile(strProjectLocate + "\\marcfilter.fltx.cs", out strError); if (nRet == -1) goto ERROR1; string[] saAddRef1 = { Environment.CurrentDirectory + "\\digitalplatform.marcdom.dll", Environment.CurrentDirectory + "\\digitalplatform.marckernel.dll", Environment.CurrentDirectory + "\\digitalplatform.rms.client.dll", Environment.CurrentDirectory + "\\digitalplatform.library.dll", // this.DataDir + "\\digitalplatform.statis.dll", Environment.CurrentDirectory + "\\digitalplatform.dll", Environment.CurrentDirectory + "\\digitalplatform.Text.dll", Environment.CurrentDirectory + "\\digitalplatform.IO.dll", Environment.CurrentDirectory + "\\digitalplatform.Xml.dll", // Environment.CurrentDirectory + "\\Interop.SHDocVw.dll", Environment.CurrentDirectory + "\\dp2batch.exe", strMainCsDllName}; string strfilterCsDllName = strProjectLocate + "\\~marcfilter_" + Convert.ToString(m_nAssemblyVersion++) + ".dll"; // 创建Project中Script的Assembly nRet = scriptManager.BuildAssembly( "MainForm", strProjectName, "marcfilter.fltx.cs", saAddRef1, strLibPaths, strfilterCsDllName, out strError, out strWarning); if (nRet == -2) goto ERROR1; if (nRet == -1) { if (strWarning == "") { goto ERROR1; } MessageBox.Show(this, strWarning); } assemblyFilter = Assembly.LoadFrom(strfilterCsDllName); if (assemblyFilter == null) { strError = "LoadFrom " + strfilterCsDllName + "fail"; goto ERROR1; } filter.Assembly = assemblyFilter; } return 0; ERROR1: return -1; } public void WriteLog(string strText) { FileUtil.WriteErrorLog( this, this.DataDir, strText); } // 输出 void DoExport(string strProjectName, string strProjectLocate) { string strError = ""; int nRet = 0; Assembly assemblyMain = null; MyFilterDocument filter = null; batchObj = null; m_nRecordCount = -1; // 准备脚本 if (strProjectName != "" && strProjectName != null) { nRet = PrepareScript(strProjectName, strProjectLocate, out assemblyMain, out filter, out batchObj, out strError); if (nRet == -1) goto ERROR1; this.AssemblyMain = assemblyMain; if (filter != null) this.AssemblyFilter = filter.Assembly; else this.AssemblyFilter = null; } // 执行脚本的OnInitial() // 触发Script中OnInitial()代码 // OnInitial()和OnBegin的本质区别, 在于OnInitial()适合检查和设置面板参数 if (batchObj != null) { BatchEventArgs args = new BatchEventArgs(); batchObj.OnInitial(this, args); /* if (args.Continue == ContinueType.SkipBeginMiddle) goto END1; if (args.Continue == ContinueType.SkipMiddle) { strError = "OnInitial()中args.Continue不能使用ContinueType.SkipMiddle.应使用ContinueType.SkipBeginMiddle"; goto ERROR1; } */ if (args.Continue == ContinueType.SkipAll) goto END1; } string strOutputFileName = ""; if (textBox_dbPath.Text == "") { MessageBox.Show(this, "尚未选择源库..."); return; } string[] dbpaths = this.textBox_dbPath.Text.Split(new char[] { ';' }); Debug.Assert(dbpaths.Length != 0, ""); // 如果为单库输出 if (dbpaths.Length == 1) { // 否则移到DoExportFile()函数里面去校验 ResPath respath = new ResPath(dbpaths[0]); channel = this.Channels.GetChannel(respath.Url); string strDbName = respath.Path; // 校验起止号 if (checkBox_verifyNumber.Checked == true) { nRet = VerifyRange(channel, strDbName, out strError); if (nRet == -1) MessageBox.Show(this, strError); } else { if (this.textBox_startNo.Text == "") { strError = "尚未指定起始号"; goto ERROR1; } if (this.textBox_endNo.Text == "") { strError = "尚未指定结束号"; goto ERROR1; } } } else { // 多库输出。修改界面要素,表示针对每个库都是全库处理 this.radioButton_all.Checked = true; this.textBox_startNo.Text = "1"; this.textBox_endNo.Text = "9999999999"; } SaveFileDialog dlg = null; if (checkBox_export_delete.Checked == true) { DialogResult result = MessageBox.Show(this, "确实要(在输出的同时)删除数据库记录?\r\n\r\n---------\r\n(确定)删除 (放弃)放弃批处理", "dp2batch", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result != DialogResult.OK) { strError = "放弃处理..."; goto ERROR1; } result = MessageBox.Show(this, "在删除记录的同时, 是否将记录输出到文件?\r\n\r\n--------\r\n(是)一边删除一边输出 (否)只删除不输出", "dp2batch", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (result != DialogResult.Yes) goto SKIPASKFILENAME; } // 获得输出文件名 dlg = new SaveFileDialog(); dlg.Title = "请指定要保存的备份文件名"; dlg.CreatePrompt = false; dlg.OverwritePrompt = false; dlg.FileName = strLastOutputFileName; dlg.FilterIndex = nLastOutputFilterIndex; dlg.Filter = "备份文件 (*.dp2bak)|*.dp2bak|XML文件 (*.xml)|*.xml|ISO2709文件 (*.iso;*.mrc)|*.iso;*.mrc|All files (*.*)|*.*"; dlg.RestoreDirectory = true; if (dlg.ShowDialog(this) != DialogResult.OK) { strError = "放弃处理..."; goto ERROR1; } strLastOutputFileName = dlg.FileName; nLastOutputFilterIndex = dlg.FilterIndex; strOutputFileName = dlg.FileName; SKIPASKFILENAME: // 触发Script中OnBegin()代码 // OnBegin()中仍然有修改MainForm面板的自由 if (batchObj != null) { BatchEventArgs args = new BatchEventArgs(); batchObj.OnBegin(this, args); /* if (args.Continue == ContinueType.SkipMiddle) goto END1; if (args.Continue == ContinueType.SkipBeginMiddle) goto END1; */ if (args.Continue == ContinueType.SkipAll) goto END1; } if (dlg == null || dlg.FilterIndex == 1) nRet = DoExportFile( dbpaths, strOutputFileName, ExportFileType.BackupFile, null, out strError); else if (dlg.FilterIndex == 2) nRet = DoExportFile( dbpaths, strOutputFileName, ExportFileType.XmlFile, null, out strError); else if (dlg.FilterIndex == 3) { ResPath respath = new ResPath(dbpaths[0]); string strMarcSyntax = ""; // 从marcdef配置文件中获得marc格式定义 // return: // -1 出错 // 0 没有找到 // 1 找到 nRet = this.SearchPanel.GetMarcSyntax(respath.FullPath, out strMarcSyntax, out strError); if (nRet == 0 || nRet == -1) { strError = "获取数据库 '" + dbpaths[0] + "' 的MARC格式时发生错误: " + strError; goto ERROR1; } // 如果多于一个数据库输出到一个文件,需要关心每个数据库的MARC格式是否相同,给与适当的警告 if (dbpaths.Length > 1) { string strWarning = ""; for (int i = 1; i < dbpaths.Length; i++) { ResPath current_respath = new ResPath(dbpaths[i]); string strPerMarcSyntax = ""; // 从marcdef配置文件中获得marc格式定义 // return: // -1 出错 // 0 没有找到 // 1 找到 nRet = this.SearchPanel.GetMarcSyntax(current_respath.FullPath, out strPerMarcSyntax, out strError); if (nRet == 0 || nRet == -1) { strError = "获取数据库 '" + dbpaths[i] + "' 的MARC格式时发生错误: " + strError; goto ERROR1; } if (strPerMarcSyntax != strMarcSyntax) { if (String.IsNullOrEmpty(strWarning) == false) strWarning += "\r\n"; strWarning += "数据库 '" + dbpaths[i] + "' (" + strPerMarcSyntax + ")"; } } if (String.IsNullOrEmpty(strWarning) == false) { strWarning = "所选择的数据库中,下列数据库的MARC格式和第一个数据库( '" + dbpaths[0] + "' (" + strMarcSyntax + "))的不同: \r\n---\r\n" + strWarning + "\r\n---\r\n\r\n如果把这些不同MARC格式的记录混合输出到一个文件中,可能会造成许多软件以后读取它时发生困难。\r\n\r\n确实要这样混合着转出到一个文件中?"; DialogResult result = MessageBox.Show(this, strWarning, "dp2batch", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResult.No) { strError = "放弃处理..."; goto ERROR1; } } } OpenMarcFileDlg marcdlg = new OpenMarcFileDlg(); MainForm.SetControlFont(marcdlg, this.DefaultFont); marcdlg.IsOutput = true; marcdlg.Text = "请指定要输出的 ISO2709 文件属性"; marcdlg.FileName = strOutputFileName; marcdlg.MarcSyntax = strMarcSyntax; marcdlg.EnableMarcSyntax = false; // 不允许用户选择marc syntax,因为这是数据库配置好了的属性 2007/8/18 marcdlg.CrLf = this.OutputCrLf; marcdlg.AddG01 = this.AddG01; marcdlg.RemoveField998 = this.Remove998; this.AppInfo.LinkFormState(marcdlg, "OpenMarcFileDlg_output_state"); marcdlg.ShowDialog(this); this.AppInfo.UnlinkFormState(marcdlg); if (marcdlg.DialogResult != DialogResult.OK) { strError = "放弃处理..."; goto ERROR1; } if (marcdlg.AddG01 == true) { MessageBox.Show(this, "您选择了在导出的ISO2709记录中加入-01字段。请注意dp2Batch在将来导入这样的ISO2709文件的时候,记录中-01字段***起不到***覆盖定位的作用。“加入-01字段”功能是为了将导出的ISO2709文件应用到dt1000系统而设计的。\r\n\r\n如果您这样做的目的是为了对dp2系统书目库中的数据进行备份,请改用.xml格式或.dp2bak格式。"); } strOutputFileName = marcdlg.FileName; this.CurMarcSyntax = strMarcSyntax; this.OutputCrLf = marcdlg.CrLf; this.AddG01 = marcdlg.AddG01; this.Remove998 = marcdlg.RemoveField998; nRet = DoExportFile( dbpaths, marcdlg.FileName, ExportFileType.ISO2709File, marcdlg.Encoding, out strError); } else { strError = "不支持的文件类型..."; goto ERROR1; } /* if (nRet == 1) goto END2; */ if (nRet == -1) goto ERROR1; END1: // 触发Script的OnEnd()代码 if (batchObj != null) { BatchEventArgs args = new BatchEventArgs(); batchObj.OnEnd(this, args); } // END2: this.AssemblyMain = null; this.AssemblyFilter = null; if (filter != null) filter.Assembly = null; this.MarcFilter = null; if (String.IsNullOrEmpty(strError) == false) MessageBox.Show(this, strError); return; ERROR1: this.AssemblyMain = null; this.AssemblyFilter = null; if (filter != null) filter.Assembly = null; this.MarcFilter = null; MessageBox.Show(this, strError); } #if NNNNN void DoExportXmlFile(string strOutputFileName) { string strError = ""; FileStream outputfile = null; XmlTextWriter writer = null; if (textBox_dbPath.Text == "") { MessageBox.Show(this, "尚未选择源库..."); return; } ResPath respath = new ResPath(textBox_dbPath.Text); channel = this.Channels.GetChannel(respath.Url); string strDbName = respath.Path; if (strOutputFileName != null && strOutputFileName != "") { // 探测文件是否存在 FileInfo fi = new FileInfo(strOutputFileName); if (fi.Exists == true && fi.Length > 0) { DialogResult result = MessageBox.Show(this, "文件 '" + strOutputFileName + "' 已存在,是否覆盖?\r\n\r\n--------------------\r\n注:(是)覆盖 (否)中断处理", "dp2batch", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result != DialogResult.Yes) { strError = "放弃处理..."; goto ERROR1; } } // 打开文件 outputfile = File.Create( strOutputFileName); writer = new XmlTextWriter(outputfile, Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.Indentation = 4; } try { Int64 nStart; Int64 nEnd; Int64 nCur; bool bAsc = GetDirection(out nStart, out nEnd); // 设置进度条范围 Int64 nMax = nEnd - nStart; if (nMax < 0) nMax *= -1; nMax ++; ProgressRatio = nMax / 10000; if (ProgressRatio < 1.0) ProgressRatio = 1.0; progressBar_main.Minimum = 0; progressBar_main.Maximum = (int)(nMax/ProgressRatio); progressBar_main.Value = 0; bool bFirst = true; // 是否为第一次取记录 string strID = this.textBox_startNo.Text; stop.Initial(new Delegate_doStop(this.DoStop), "正在导出数据"); stop.BeginLoop(); EnableControls(false); if (writer != null) { writer.WriteStartDocument(); writer.WriteStartElement("dprms","collection",DpNs.dprms); //writer.WriteStartElement("collection"); //writer.WriteAttributeString("xmlns:marc", // "http://www.loc.gov/MARC21/slim"); } // 循环 for(;;) { Application.DoEvents(); // 出让界面控制权 if (stop.State != 0) { strError = "用户中断"; goto ERROR1; } string strStyle = ""; if (outputfile != null) strStyle = "data,content,timestamp,outputpath"; else strStyle = "timestamp,outputpath"; // 优化 if (bFirst == true) strStyle += ""; else { if (bAsc == true) strStyle += ",next"; else strStyle += ",prev"; } string strPath = strDbName + "/" + strID; string strXmlBody = ""; string strMetaData = ""; byte[] baOutputTimeStamp = null; string strOutputPath = ""; bool bFoundRecord = false; // 获得资源 // return: // -1 出错。具体出错原因在this.ErrorCode中。this.ErrorInfo中有出错信息。 // 0 成功 long lRet = channel.GetRes(strPath, strStyle, out strXmlBody, out strMetaData, out baOutputTimeStamp, out strOutputPath, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) { if (checkBox_forceLoop.Checked == true && bFirst == true) { AutoCloseMessageBox.Show(this, "记录 " + strID + " 不存在。\r\n\r\n按 确认 继续。"); bFirst = false; goto CONTINUE; } else { if (bFirst == true) { strError = "记录 " + strID + " 不存在。处理结束。"; } else { if (bAsc == true) strError = "记录 " + strID + " 是最末一条记录。处理结束。"; else strError = "记录 " + strID + " 是最前一条记录。处理结束。"; } } } else if (channel.ErrorCode == ChannelErrorCode.EmptyRecord) { bFirst = false; bFoundRecord = false; // 把id解析出来 strID = ResPath.GetRecordId(strOutputPath); goto CONTINUE; } goto ERROR1; } bFirst = false; bFoundRecord = true; // 把id解析出来 strID = ResPath.GetRecordId(strOutputPath); CONTINUE: stop.SetMessage(strID); // 是否超过循环范围 try { nCur = Convert.ToInt64(strID); } catch { // ??? nCur = 0; } if (bAsc == true && nCur > nEnd) break; if (bAsc == false && nCur < nEnd) break; if (bFoundRecord == true && writer != null) { // 写磁盘 XmlDocument dom = new XmlDocument(); try { dom.LoadXml(strXmlBody); ResPath respathtemp = new ResPath(); respathtemp.Url = channel.Url; respathtemp.Path = strOutputPath; // DomUtil.SetAttr(dom.DocumentElement, "xmlns:dprms", DpNs.dprms); // 给根元素设置几个参数 DomUtil.SetAttr(dom.DocumentElement, "path", DpNs.dprms, respathtemp.FullPath); DomUtil.SetAttr(dom.DocumentElement, "timestamp", DpNs.dprms, ByteArray.GetHexTimeStampString(baOutputTimeStamp)); // DomUtil.SetAttr(dom.DocumentElement, "xmlns:marc", null); dom.DocumentElement.WriteTo(writer); } catch (Exception ex) { strError = ex.Message; // 询问是否继续 goto ERROR1; } /* if (nRet == -1) { // 询问是否继续 goto ERROR1; } */ } // 删除 if (checkBox_export_delete.Checked == true) { byte [] baOutputTimeStamp1 = null; strPath = strOutputPath; // 得到实际的路径 lRet = channel.DoDeleteRecord( strPath, baOutputTimeStamp, out baOutputTimeStamp1, out strError); if (lRet == -1) { // 询问是否继续 goto ERROR1; } } if (bAsc == true) { progressBar_main.Value = (int)((nCur-nStart + 1)/ProgressRatio); } else { // ? progressBar_main.Value = (int)((nStart-nCur + 1)/ProgressRatio); } // 对已经作过的进行判断 if (bAsc == true && nCur >= nEnd) break; if (bAsc == false && nCur <= nEnd) break; } stop.EndLoop(); stop.Initial(null, ""); EnableControls(true); } finally { if (writer != null) { writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); writer = null; } if (outputfile != null) { outputfile.Close(); outputfile = null; } } END1: channel = null; if (checkBox_export_delete.Checked == true) MessageBox.Show(this, "数据导出和删除完成。"); else MessageBox.Show(this, "数据导出完成。"); return; ERROR1: stop.EndLoop(); stop.Initial(null, ""); EnableControls(true); channel = null; MessageBox.Show(this, strError); return; } #endif // return: // -1 error // 0 正常结束 // 1 希望跳过后来的OnEnd() int DoExportFile( string[] dbpaths, string strOutputFileName, ExportFileType exportType, Encoding targetEncoding, out string strError) { strError = ""; int nRet = 0; string strDeleteStyle = ""; if (this.checkBox_export_fastMode.Checked == true) strDeleteStyle = "fastmode"; string strInfo = ""; // 汇总信息,在完成后显示 FileStream outputfile = null; // Backup和Xml格式输出都需要这个 XmlTextWriter writer = null; // Xml格式输出时需要这个 bool bAppend = true; Debug.Assert(dbpaths != null, ""); if (dbpaths.Length == 0) { strError = "尚未指定源库..."; goto ERROR1; } if (String.IsNullOrEmpty(strOutputFileName) == false) { // 探测输出文件是否已经存在 FileInfo fi = new FileInfo(strOutputFileName); bAppend = true; if (fi.Exists == true && fi.Length > 0) { if (exportType == ExportFileType.BackupFile || exportType == ExportFileType.ISO2709File) { DialogResult result = MessageBox.Show(this, "文件 '" + strOutputFileName + "' 已存在,是否追加?\r\n\r\n--------------------\r\n注:(是)追加 (否)覆盖 (取消)中断处理", "dp2batch", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (result == DialogResult.Yes) { bAppend = true; } if (result == DialogResult.No) { bAppend = false; } if (result == DialogResult.Cancel) { strError = "放弃处理..."; goto ERROR1; } } else if (exportType == ExportFileType.XmlFile) { DialogResult result = MessageBox.Show(this, "文件 '" + strOutputFileName + "' 已存在,是否覆盖?\r\n\r\n--------------------\r\n注:(是)覆盖 (否)中断处理", "dp2batch", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result != DialogResult.Yes) { strError = "放弃处理..."; goto ERROR1; } } } // 打开文件 if (exportType == ExportFileType.BackupFile || exportType == ExportFileType.ISO2709File) { outputfile = File.Open( strOutputFileName, FileMode.OpenOrCreate, // 原来是Open,后来修改为OpenOrCreate。这样对临时文件被系统管理员手动意外删除(但是xml文件中仍然记载了任务)的情况能够适应。否则会抛出FileNotFoundException异常 FileAccess.Write, FileShare.ReadWrite); } else if (exportType == ExportFileType.XmlFile) { outputfile = File.Create( strOutputFileName); writer = new XmlTextWriter(outputfile, Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.Indentation = 4; } } if ((exportType == ExportFileType.BackupFile || exportType == ExportFileType.ISO2709File) && outputfile != null) { if (bAppend == true) outputfile.Seek(0, SeekOrigin.End); // 具有追加的能力 else outputfile.SetLength(0); } WriteLog("开始输出"); try { // string[] dbpaths = textBox_dbPath.Text.Split(new char[] { ';' }); for (int f = 0; f < dbpaths.Length; f++) { string strOneDbPath = dbpaths[f]; ResPath respath = new ResPath(strOneDbPath); channel = this.Channels.GetChannel(respath.Url); string strDbName = respath.Path; if (String.IsNullOrEmpty(strInfo) == false) strInfo += "\r\n"; strInfo += "" + strDbName; // 实际处理的首尾号 string strRealStartNo = ""; string strRealEndNo = ""; /* DialogResult result; if (checkBox_export_delete.Checked == true) { result = MessageBox.Show(this, "确实要删除 '" + respath.Path + "' 内指定范围的记录?\r\n\r\n---------\r\n(是)删除 (否)放弃批处理", "dp2batch", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result != DialogResult.Yes) continue; } * * */ //channel = this.Channels.GetChannel(respath.Url); //string strDbName = respath.Path; // 如果为多库输出 if (dbpaths.Length > 0) { // 如果为全选 if (this.radioButton_all.Checked == true) { // 恢复为最大范围 this.textBox_startNo.Text = "1"; this.textBox_endNo.Text = "9999999999"; } // 校验起止号 if (checkBox_verifyNumber.Checked == true) { nRet = VerifyRange(channel, strDbName, out strError); if (nRet == -1) MessageBox.Show(this, strError); if (nRet == 0) { // 库中无记录 AutoCloseMessageBox.Show(this, "数据库 " + strDbName + " 中无记录。"); strInfo += "(无记录)"; WriteLog("发现数据库 " + strDbName + " 中无记录"); continue; } } else { if (this.textBox_startNo.Text == "") { strError = "尚未指定起始号"; goto ERROR1; } if (this.textBox_endNo.Text == "") { strError = "尚未指定结束号"; goto ERROR1; } } } string strOutputStartNo = ""; string strOutputEndNo = ""; // 虽然界面不让校验起止号,但是也要校验,为了设置好进度条 if (checkBox_verifyNumber.Checked == false) { // 校验起止号 // return: // 0 不存在记录 // 1 存在记录 nRet = VerifyRange(channel, strDbName, this.textBox_startNo.Text, this.textBox_endNo.Text, out strOutputStartNo, out strOutputEndNo, out strError); } //try //{ Int64 nStart = 0; Int64 nEnd = 0; Int64 nCur = 0; bool bAsc = true; bAsc = GetDirection( this.textBox_startNo.Text, this.textBox_endNo.Text, out nStart, out nEnd); // 探测到的号码 long nOutputEnd = 0; long nOutputStart = 0; if (checkBox_verifyNumber.Checked == false) { GetDirection( strOutputStartNo, strOutputEndNo, out nOutputStart, out nOutputEnd); } // 设置进度条范围 if (checkBox_verifyNumber.Checked == true) { Int64 nMax = nEnd - nStart; if (nMax < 0) nMax *= -1; nMax++; /* ProgressRatio = nMax / 10000; if (ProgressRatio < 1.0) ProgressRatio = 1.0; progressBar_main.Minimum = 0; progressBar_main.Maximum = (int)(nMax / ProgressRatio); progressBar_main.Value = 0; * */ stop.SetProgressRange(0, nMax); } else { Int64 nMax = nOutputEnd - nOutputStart; if (nMax < 0) nMax *= -1; nMax++; stop.SetProgressRange(0, nMax); } bool bFirst = true; // 是否为第一次取记录 string strID = this.textBox_startNo.Text; stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在导出数据"); stop.BeginLoop(); EnableControls(false); if (exportType == ExportFileType.XmlFile && writer != null) { writer.WriteStartDocument(); writer.WriteStartElement("dprms", "collection", DpNs.dprms); //writer.WriteStartElement("collection"); //writer.WriteAttributeString("xmlns:marc", // "http://www.loc.gov/MARC21/slim"); } WriteLog("开始输出数据库 '" + strDbName + "' 内的数据记录"); m_nRecordCount = 0; // 循环 for (; ; ) { Application.DoEvents(); // 出让界面控制权 if (stop.State != 0) { WriteLog("打开对话框 '确实要中断当前批处理操作?'"); DialogResult result = MessageBox.Show(this, "确实要中断当前批处理操作?", "dp2batch", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); WriteLog("关闭对话框 '确实要中断当前批处理操作?'"); if (result == DialogResult.Yes) { strError = "用户中断"; goto ERROR1; } else { stop.Continue(); } } string strDirectionComment = ""; string strStyle = ""; if (outputfile != null) strStyle = "data,content,timestamp,outputpath"; else strStyle = "timestamp,outputpath"; // 优化 if (bFirst == true) { strStyle += ""; } else { if (bAsc == true) { strStyle += ",next"; strDirectionComment = "的后一条记录"; } else { strStyle += ",prev"; strDirectionComment = "的前一条记录"; } } string strPath = strDbName + "/" + strID; string strXmlBody = ""; string strMetaData = ""; byte[] baOutputTimeStamp = null; string strOutputPath = ""; bool bFoundRecord = false; bool bNeedRetry = true; REDO_GETRES: // 获得资源 // return: // -1 出错。具体出错原因在this.ErrorCode中。this.ErrorInfo中有出错信息。 // 0 成功 long lRet = channel.GetRes(strPath, strStyle, out strXmlBody, out strMetaData, out baOutputTimeStamp, out strOutputPath, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) { if (bFirst == true) { if (checkBox_forceLoop.Checked == true) { string strText = "记录 " + strID + strDirectionComment + " 不存在。\r\n\r\n按 确认 继续。"; WriteLog("打开对话框 '" + strText.Replace("\r\n", "\\n") + "'"); AutoCloseMessageBox.Show(this, strText); WriteLog("关闭对话框 '" + strText.Replace("\r\n", "\\n") + "'"); bFirst = false; goto CONTINUE; } else { // 如果不要强制循环,此时也不能结束,否则会让用户以为数据库里面根本没有数据 string strText = "您为数据库 " + strDbName + " 指定的首记录 " + strID + strDirectionComment + " 不存在。\r\n\r\n(注:为避免出现此提示,可在操作前勾选“校准首尾ID”)\r\n\r\n按 确认 继续向后找..."; WriteLog("打开对话框 '" + strText.Replace("\r\n", "\\n") + "'"); AutoCloseMessageBox.Show(this, strText); WriteLog("关闭对话框 '" + strText.Replace("\r\n", "\\n") + "'"); bFirst = false; goto CONTINUE; } } else { Debug.Assert(bFirst == false, ""); if (bFirst == true) { strError = "记录 " + strID + strDirectionComment + " 不存在。处理结束。"; } else { if (bAsc == true) strError = "记录 " + strID + " 是最末一条记录。处理结束。"; else strError = "记录 " + strID + " 是最前一条记录。处理结束。"; } if (dbpaths.Length > 1) break; // 多库情况,继续其它库循环 else { bNeedRetry = false; // 单库情况,也没有必要出现重试对话框 WriteLog("打开对话框 '" + strError.Replace("\r\n", "\\n") + "'"); MessageBox.Show(this, strError); WriteLog("关闭对话框 '" + strError.Replace("\r\n", "\\n") + "'"); break; } } } else if (channel.ErrorCode == ChannelErrorCode.EmptyRecord) { bFirst = false; bFoundRecord = false; // 把id解析出来 strID = ResPath.GetRecordId(strOutputPath); goto CONTINUE; } // 允许重试 if (bNeedRetry == true) { string strText = "获取记录 '" + strPath + "' (style='" + strStyle + "')时出现错误: " + strError + "\r\n\r\n重试,还是中断当前批处理操作?\r\n(Retry 重试;Cancel 中断批处理)"; WriteLog("打开对话框 '" + strText.Replace("\r\n", "\\n") + "'"); DialogResult redo_result = MessageBox.Show(this, strText, "dp2batch", MessageBoxButtons.RetryCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); WriteLog("关闭对话框 '" + strText.Replace("\r\n", "\\n") + "'"); if (redo_result == DialogResult.Cancel) goto ERROR1; goto REDO_GETRES; } else { goto ERROR1; } } // 2008/11/9 if (String.IsNullOrEmpty(strXmlBody) == true) { bFirst = false; bFoundRecord = false; // 把id解析出来 strID = ResPath.GetRecordId(strOutputPath); goto CONTINUE; } bFirst = false; bFoundRecord = true; // 把id解析出来 strID = ResPath.GetRecordId(strOutputPath); stop.SetMessage("已导出记录 " + strOutputPath + " " + m_nRecordCount.ToString()); if (String.IsNullOrEmpty(strRealStartNo) == true) { strRealStartNo = strID; } strRealEndNo = strID; CONTINUE: // 是否超过循环范围 try { nCur = Convert.ToInt64(strID); } catch { // ??? nCur = 0; } if (checkBox_verifyNumber.Checked == false) { // 如果当前记录号码突破预计的头部和尾部 if (nCur > nOutputEnd || nCur < nOutputStart) { if (nCur > nOutputEnd) nOutputEnd = nCur; if (nCur < nOutputStart) nOutputStart = nCur; // 重新计算和设置进度条 long nMax = nOutputEnd - nOutputStart; if (nMax < 0) nMax *= -1; nMax++; stop.SetProgressRange(0, nMax); } } if (bAsc == true && nCur > nEnd) break; if (bAsc == false && nCur < nEnd) break; string strMarc = ""; // 将Xml转换为MARC if (exportType == ExportFileType.ISO2709File && bFoundRecord == true) // 2008/11/13 { nRet = GetMarc(strXmlBody, out strMarc, out strError); if (nRet == -1) { strError = "记录 " + strOutputPath + " 在将 XML 格式转换为MARC时出错: " + strError; goto ERROR1; } } if (this.MarcFilter != null) { // 触发filter中的Record相关动作 // TODO: 有可能strMarc为空哟,需要测试一下 nRet = MarcFilter.DoRecord( null, strMarc, m_nRecordCount, out strError); if (nRet == -1) goto ERROR1; } // 触发Script的Outputing()代码 if (bFoundRecord == true && this.AssemblyMain != null) { // 这些变量要先初始化,因为filter代码可能用到这些Batch成员. batchObj.XmlRecord = strXmlBody; batchObj.MarcSyntax = this.CurMarcSyntax; batchObj.MarcRecord = strMarc; // MARC记录体 batchObj.MarcRecordChanged = false; // 为本轮Script运行准备初始状态 batchObj.SearchPanel.ServerUrl = channel.Url; batchObj.ServerUrl = channel.Url; batchObj.RecPath = strOutputPath; // 记录路径 batchObj.RecIndex = m_nRecordCount; // 当前记录在一批中的序号 batchObj.TimeStamp = baOutputTimeStamp; BatchEventArgs args = new BatchEventArgs(); batchObj.Outputing(this, args); /* if (args.Continue == ContinueType.SkipMiddle) goto CONTINUEDBS; if (args.Continue == ContinueType.SkipBeginMiddle) goto CONTINUEDBS; */ if (args.Continue == ContinueType.SkipAll) goto CONTINUEDBS; // 观察用于输出的MARC记录是否被改变 if (batchObj.MarcRecordChanged == true) strMarc = batchObj.MarcRecord; // 观察XML记录是否被改变 if (batchObj.XmlRecordChanged == true) strXmlBody = batchObj.XmlRecord; } if (bFoundRecord == true && outputfile != null && string.IsNullOrEmpty(strXmlBody) == false) // == false 2017/5/18 { if (exportType == ExportFileType.BackupFile) { // 写磁盘 nRet = WriteRecordToBackupFile( outputfile, strDbName, strID, strMetaData, strXmlBody, baOutputTimeStamp, out strError); if (nRet == -1) { // 询问是否继续 goto ERROR1; } } else if (exportType == ExportFileType.ISO2709File) { // 写磁盘 nRet = WriteRecordToISO2709File( outputfile, strDbName, strID, strMarc, baOutputTimeStamp, targetEncoding, this.OutputCrLf, this.AddG01, this.Remove998, out strError); if (nRet == -1) { // 询问是否继续 goto ERROR1; } } else if (exportType == ExportFileType.XmlFile) { XmlDocument dom = new XmlDocument(); try { dom.LoadXml(strXmlBody); ResPath respathtemp = new ResPath(); respathtemp.Url = channel.Url; respathtemp.Path = strOutputPath; // DomUtil.SetAttr(dom.DocumentElement, "xmlns:dprms", DpNs.dprms); // 给根元素设置几个参数 DomUtil.SetAttr(dom.DocumentElement, "path", DpNs.dprms, respathtemp.FullPath); DomUtil.SetAttr(dom.DocumentElement, "timestamp", DpNs.dprms, ByteArray.GetHexTimeStampString(baOutputTimeStamp)); // DomUtil.SetAttr(dom.DocumentElement, "xmlns:marc", null); dom.DocumentElement.WriteTo(writer); } catch (Exception ex) { strError = ExceptionUtil.GetAutoText(ex); // 询问是否继续 goto ERROR1; } } } // 删除 if (checkBox_export_delete.Checked == true) { byte[] baOutputTimeStamp1 = null; strPath = strOutputPath; // 得到实际的路径 lRet = channel.DoDeleteRes( strPath, baOutputTimeStamp, strDeleteStyle, out baOutputTimeStamp1, out strError); if (lRet == -1) { // 询问是否继续 goto ERROR1; } stop.SetMessage("已删除记录" + strPath + " " + m_nRecordCount.ToString()); } if (bFoundRecord == true) m_nRecordCount++; if (bAsc == true) { //progressBar_main.Value = (int)((nCur - nStart + 1) / ProgressRatio); stop.SetProgressValue(nCur - nStart + 1); } else { // ? // progressBar_main.Value = (int)((nStart - nCur + 1) / ProgressRatio); stop.SetProgressValue(nStart - nCur + 1); } // 对已经作过的进行判断 if (bAsc == true && nCur >= nEnd) break; if (bAsc == false && nCur <= nEnd) break; } // end of for one database stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); EnableControls(true); //} CONTINUEDBS: strInfo += " : " + m_nRecordCount.ToString() + "条 (ID " + strRealStartNo + "-" + strRealEndNo + ")"; } // end of dbpaths loop } // end of try finally { if (writer != null) { writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); writer = null; } if (outputfile != null) { outputfile.Close(); outputfile = null; } } // END1: channel = null; if (checkBox_export_delete.Checked == true) strError = "数据导出和删除完成。\r\n---\r\n" + strInfo; else strError = "数据导出完成。\r\n---\r\n" + strInfo; WriteLog("结束输出"); return 0; ERROR1: stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); EnableControls(true); channel = null; return -1; } // 将Xml转换为MARC // 可供C#脚本调用 public int GetMarc(string strXmlBody, out string strMarc, out string strError) { string strOutMarcSyntax = ""; strMarc = ""; // 将MARCXML格式的xml记录转换为marc机内格式字符串 // parameters: // bWarning ==true, 警告后继续转换,不严格对待错误; = false, 非常严格对待错误,遇到错误后不继续转换 // strMarcSyntax 指示marc语法,如果=="",则自动识别 // strOutMarcSyntax out参数,返回marc,如果strMarcSyntax == "",返回找到marc语法,否则返回与输入参数strMarcSyntax相同的值 int nRet = MarcUtil.Xml2Marc(strXmlBody, true, // true 比 false 要宽松 // false, this.CurMarcSyntax, out strOutMarcSyntax, out strMarc, out strError); if (nRet == -1) return -1; return 0; } // 在MARC记录中加入一个-01字段 // 总是插入在第一个字段 static int AddG01ToMarc(ref string strMARC, string strFieldContent, out string strError) { strError = ""; if (strMARC.Length < 24) { strMARC = strMARC.PadRight(24, '*'); strMARC += "-01" + strFieldContent + new string(MarcUtil.FLDEND, 1); return 1; } strMARC = strMARC.Insert(24, "-01" + strFieldContent + new string(MarcUtil.FLDEND, 1)); /* // 如果原有记录中存在-01字段,则第一个-01字段将被覆盖 // return: // -1 出错 // 0 没有找到指定的字段,因此将strField内容插入到适当位置了。 // 1 找到了指定的字段,并且也成功用strField替换掉了。 int nRet = MarcUtil.ReplaceField( ref strMARC, "-01", 0, "-01" + strFieldContent); if (nRet == -1) { strError = "ReplaceField() error"; return -1; }*/ return 1; } // 去除MARC记录中的所有-01字段 // return: // -1 error // 0 not changed // 1 changed static int RemoveG01FromMarc(ref string strMARC, out string strError) { strError = ""; if (strMARC.Length <= 24) return 0; bool bChanged = false; for (; ; ) { string strField = ""; string strNextFieldName = ""; // return: // -1 出错 // 0 所指定的字段没有找到 // 1 找到。找到的字段返回在strField参数中 int nRet = MarcUtil.GetField(strMARC, "-01", 0, out strField, out strNextFieldName); if (nRet == -1) { strError = "GetField() error"; return -1; } if (nRet == 0) break; // return: // -1 出错 // 0 没有找到指定的字段,因此将strField内容插入到适当位置了。 // 1 找到了指定的字段,并且也成功用strField替换掉了。 nRet = MarcUtil.ReplaceField( ref strMARC, "-01", 0, null); if (nRet == -1) { strError = "ReplaceField() error"; return -1; } bChanged = true; } if (bChanged == true) return 1; return 0; } // 将记录写入ISO2709文件 int WriteRecordToISO2709File( Stream outputfile, string strDbName, string strID, string strMarc, byte[] body_timestamp, Encoding targetEncoding, bool bOutputCrLf, bool bAddG01, bool bRemove998, out string strError) { int nRet = 0; string strPath = strDbName + "/" + strID; long lStart = outputfile.Position; // 记忆起始位置 ResPath respath = new ResPath(); respath.Url = channel.Url; respath.Path = strPath; // 去除MARC记录中的所有-01字段 // return: // -1 error // 0 not changed // 1 changed nRet = RemoveG01FromMarc(ref strMarc, out strError); if (nRet == -1) return -1; if (bAddG01 == true) { string strDt1000Path = "/" + strDbName + "/ctlno/" + strID.PadLeft(10, '0'); string strTimestamp = ByteArray.GetHexTimeStampString(body_timestamp); nRet = AddG01ToMarc(ref strMarc, strDt1000Path + "|" + strTimestamp, out strError); if (nRet == -1) return -1; } if (bRemove998 == true) { MarcRecord record = new MarcRecord(strMarc); record.select("field[@name='998']").detach(); record.select("field[@name='997']").detach(); strMarc = record.Text; } byte[] baResult = null; // 将MARC机内格式转换为ISO2709格式 // parameters: // nMARCType [in]MARC格式类型。0为UNIMARC 1为USMARC // strSourceMARC [in]机内格式MARC记录。 // targetEncoding [in]输出ISO2709的编码方式为 UTF8 codepage-936等等 // baResult [out]输出的ISO2709记录。字符集受nCharset参数控制。 // 注意,缓冲区末尾不包含0字符。 nRet = MarcUtil.CvtJineiToISO2709( strMarc, this.CurMarcSyntax, targetEncoding, out baResult, out strError); if (nRet == -1) return -1; outputfile.Write(baResult, 0, baResult.Length); if (bOutputCrLf == true) { baResult = new byte[2]; baResult[0] = (byte)'\r'; baResult[1] = (byte)'\n'; outputfile.Write(baResult, 0, 2); } return 0; /* ERROR1: return -1; */ } // 将主记录和相关资源写入备份文件 // return: // -1 出错 // 0 因 strXmlBody 为空,忽略此记录,并没有导出任何内容 // 1 导出了内容 int WriteRecordToBackupFile( Stream outputfile, string strDbName, string strID, string strMetaData, string strXmlBody, byte[] body_timestamp, out string strError) { strError = ""; // 2017/9/19 if (string.IsNullOrEmpty(strXmlBody)) return 0; Debug.Assert(String.IsNullOrEmpty(strXmlBody) == false, "strXmlBody不能为空"); string strPath = strDbName + "/" + strID; long lStart = outputfile.Position; // 记忆起始位置 byte[] length = new byte[8]; outputfile.Write(length, 0, 8); // 临时写点数据,占据记录总长度位置 ResPath respath = new ResPath(); respath.Url = channel.Url; respath.Path = strPath; // 加工元数据 StringUtil.ChangeMetaData(ref strMetaData, null, null, null, null, respath.FullPath, ByteArray.GetHexTimeStampString(body_timestamp)); // 2005/6/11 // 向backup文件中保存第一个 res long lRet = Backup.WriteFirstResToBackupFile( outputfile, strMetaData, strXmlBody); // 其余 string[] ids = null; // 得到Xml记录中所有<file>元素的id属性值 int nRet = ExportUtil.GetFileIds(strXmlBody, out ids, out strError); if (nRet == -1) { outputfile.SetLength(lStart); // 把本次追加写入的全部去掉 strError = "GetFileIds()出错,无法获得 XML 记录中的 <dprms:file>元素的 id 属性, 因此保存记录失败,原因: " + strError; goto ERROR1; } nRet = WriteResToBackupFile( this, outputfile, respath.Path, ids, channel, stop, out strError); if (nRet == -1) { outputfile.SetLength(lStart); // 把本次追加写入的全部去掉 strError = "WriteResToBackupFile()出错,因此保存记录失败,原因: " + strError; goto ERROR1; } /// // 写入总长度 long lTotalLength = outputfile.Position - lStart - 8; byte[] data = BitConverter.GetBytes(lTotalLength); // 返回记录最开头位置 outputfile.Seek(lStart - outputfile.Position, SeekOrigin.Current); Debug.Assert(outputfile.Position == lStart, ""); // outputfile.Seek(lStart, SeekOrigin.Begin); // 文件大了以后这句话的性能会很差 outputfile.Write(data, 0, 8); outputfile.Seek(lTotalLength, SeekOrigin.Current); return 1; ERROR1: return -1; } // 下载资源,保存到备份文件 public static int WriteResToBackupFile( IWin32Window owner, Stream outputfile, string strXmlRecPath, string[] res_ids, RmsChannel channel, DigitalPlatform.Stop stop, out string strError) { strError = ""; long lRet; for (int i = 0; i < res_ids.Length; i++) { Application.DoEvents(); // 出让界面控制权 if (stop.State != 0) { DialogResult result = MessageBox.Show(owner, "确实要中断当前批处理操作?", "dp2batch", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResult.Yes) { strError = "用户中断"; return -1; } else { stop.Continue(); } } string strID = res_ids[i].Trim(); if (strID == "") continue; string strResPath = strXmlRecPath + "/object/" + strID; string strMetaData; if (stop != null) stop.SetMessage("正在下载 " + strResPath); long lResStart = 0; // 写res的头。 // 如果不能预先确知整个res的长度,可以用随便一个lTotalLength值调用本函数, // 但是需要记忆下函数所返回的lStart,最后调用EndWriteResToBackupFile()。 // 如果能预先确知整个res的长度,则最后不必调用EndWriteResToBackupFile() lRet = Backup.BeginWriteResToBackupFile( outputfile, 0, // 未知 out lResStart); byte[] baOutputTimeStamp = null; string strOutputPath; REDO_GETRES: lRet = channel.GetRes(strResPath, (Stream)null, // 故意不获取资源体 stop, "metadata,timestamp,outputpath", null, out strMetaData, // 但是要获得metadata out baOutputTimeStamp, out strOutputPath, out strError); if (lRet == -1) { // TODO: 允许重试 DialogResult redo_result = MessageBox.Show(owner, "获取记录 '" + strResPath + "' 时出现错误: " + strError + "\r\n\r\n重试,还是中断当前批处理操作?\r\n(Retry 重试;Cancel 中断批处理)", "dp2batch", MessageBoxButtons.RetryCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (redo_result == DialogResult.Cancel) return -1; goto REDO_GETRES; } byte[] timestamp = baOutputTimeStamp; ResPath respath = new ResPath(); respath.Url = channel.Url; respath.Path = strOutputPath; // strResPath; // strMetaData还要加入资源id? StringUtil.ChangeMetaData(ref strMetaData, strID, null, null, null, respath.FullPath, ByteArray.GetHexTimeStampString(baOutputTimeStamp)); lRet = Backup.WriteResMetadataToBackupFile(outputfile, strMetaData); if (lRet == -1) return -1; long lBodyStart = 0; // 写res body的头。 // 如果不能预先确知body的长度,可以用随便一个lBodyLength值调用本函数, // 但是需要记忆下函数所返回的lBodyStart,最后调用EndWriteResBodyToBackupFile()。 // 如果能预先确知body的长度,则最后不必调用EndWriteResBodyToBackupFile() lRet = Backup.BeginWriteResBodyToBackupFile( outputfile, 0, // 未知 out lBodyStart); if (lRet == -1) return -1; if (stop != null) stop.SetMessage("正在下载 " + strResPath + " 的数据体"); REDO_GETRES_1: lRet = channel.GetRes(strResPath, outputfile, stop, "content,data,timestamp", //"content,data,timestamp" timestamp, out strMetaData, out baOutputTimeStamp, out strOutputPath, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.EmptyRecord) { // 空记录 } else { // TODO: 允许重试 DialogResult redo_result = MessageBox.Show(owner, "获取记录 '" + strResPath + "' 时出现错误: " + strError + "\r\n\r\n重试,还是中断当前批处理操作?\r\n(Retry 重试;Cancel 中断批处理)", "dp2batch", MessageBoxButtons.RetryCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (redo_result == DialogResult.Cancel) return -1; goto REDO_GETRES_1; } } long lBodyLength = outputfile.Position - lBodyStart - 8; // res body收尾 lRet = Backup.EndWriteResBodyToBackupFile( outputfile, lBodyLength, lBodyStart); if (lRet == -1) return -1; long lTotalLength = outputfile.Position - lResStart - 8; lRet = Backup.EndWriteResToBackupFile( outputfile, lTotalLength, lResStart); if (lRet == -1) return -1; } /* if (stop != null) stop.SetMessage("保存资源到备份文件全部完成"); */ return 0; } // return: // true 起始号为小号 // false 起始号为大号 static bool GetDirection( string strStartNo, string strEndNo, out Int64 nStart, out Int64 nEnd) { bool bAsc = true; nStart = 0; nEnd = 9999999999; try { nStart = Convert.ToInt64(strStartNo); } catch { } try { nEnd = Convert.ToInt64(strEndNo); } catch { } if (nStart > nEnd) bAsc = false; else bAsc = true; return bAsc; } #if NOOOOOOOOOOOO // return: // true 起始号为小号 // false 起始号为大号 bool GetDirection(out Int64 nStart, out Int64 nEnd) { bool bAsc = true; nStart = 0; nEnd = 9999999999; try { nStart = Convert.ToInt64(textBox_startNo.Text); } catch { } try { nEnd = Convert.ToInt64(textBox_endNo.Text); } catch { } if (nStart > nEnd) bAsc = false; else bAsc = true; return bAsc; } #endif // 校验起止号 // return: // 0 不存在记录 // 1 存在记录 int VerifyRange(RmsChannel channel, string strDbName, string strInputStartNo, string strInputEndNo, out string strOutputStartNo, out string strOutputEndNo, out string strError) { strError = ""; strOutputStartNo = ""; strOutputEndNo = ""; bool bStartNotFound = false; bool bEndNotFound = false; // 如果输入参数中为空,则假定为“全部范围” if (strInputStartNo == "") strInputStartNo = "1"; if (strInputEndNo == "") strInputEndNo = "9999999999"; bool bAsc = true; Int64 nStart = 0; Int64 nEnd = 9999999999; try { nStart = Convert.ToInt64(strInputStartNo); } catch { } try { nEnd = Convert.ToInt64(strInputEndNo); } catch { } if (nStart > nEnd) bAsc = false; else bAsc = true; string strPath = strDbName + "/" + strInputStartNo; string strStyle = "outputpath"; if (bAsc == true) strStyle += ",next,myself"; else strStyle += ",prev,myself"; string strResult; string strMetaData; byte[] baOutputTimeStamp; string strOutputPath; string strError0 = ""; string strStartID = ""; string strEndID = ""; // 获得资源 // return: // -1 出错。具体出错原因在this.ErrorCode中。this.ErrorInfo中有出错信息。 // 0 成功 long lRet = channel.GetRes(strPath, strStyle, out strResult, out strMetaData, out baOutputTimeStamp, out strOutputPath, out strError0); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) { strStartID = strInputStartNo; bStartNotFound = true; } else strError += "校验startno时出错: " + strError0 + " "; } else { // 取得返回的id strStartID = ResPath.GetRecordId(strOutputPath); } if (strStartID == "") { strError = "strStartID为空..." + (string.IsNullOrEmpty(strError) == false ? " : " + strError : ""); return -1; } strPath = strDbName + "/" + strInputEndNo; strStyle = "outputpath"; if (bAsc == true) strStyle += ",prev,myself"; else strStyle += ",next,myself"; // 获得资源 // return: // -1 出错。具体出错原因在this.ErrorCode中。this.ErrorInfo中有出错信息。 // 0 成功 lRet = channel.GetRes(strPath, strStyle, out strResult, out strMetaData, out baOutputTimeStamp, out strOutputPath, out strError0); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) { strEndID = strInputEndNo; bEndNotFound = true; } else { strError += "校验endno时出错: " + strError0 + " "; } } else { // 取得返回的id strEndID = ResPath.GetRecordId(strOutputPath); } if (strEndID == "") { strError = "strEndID为空..." + (string.IsNullOrEmpty(strError) == false ? " : " + strError : ""); ; return -1; } /// bool bSkip = false; Int64 nTemp = 0; try { nTemp = Convert.ToInt64(strStartID); } catch { strError = "strStartID值 '" + strStartID + "' 不是数字..."; return -1; } if (bAsc == true) { if (nTemp > nEnd) { bSkip = true; } } else { if (nTemp < nEnd) { bSkip = true; } } if (bSkip == false) { strOutputStartNo = strStartID; } /// bSkip = false; try { nTemp = Convert.ToInt64(strEndID); } catch { strError = "strEndID值 '" + strEndID + "' 不是数字..."; return -1; } if (bAsc == true) { if (nTemp < nStart) { bSkip = true; } } else { if (nTemp > nStart) { bSkip = true; } } if (bSkip == false) { strOutputEndNo = strEndID; } if (bStartNotFound == true && bEndNotFound == true) return 0; return 1; } // 校验起止号 // return: // 0 不存在记录 // 1 存在记录 int VerifyRange(RmsChannel channel, string strDbName, out string strError) { strError = ""; string strOutputStartNo = ""; string strOutputEndNo = ""; int nRet = VerifyRange(channel, strDbName, this.textBox_startNo.Text, this.textBox_endNo.Text, out strOutputStartNo, out strOutputEndNo, out strError); if (nRet == -1) return -1; this.textBox_startNo.Text = strOutputStartNo; this.textBox_endNo.Text = strOutputEndNo; return nRet; } #if NOOOOOOOOOOOOOOOOOOOOOOOOOO // 校验起止号 // return: // 0 不存在记录 // 1 存在记录 int VerifyRange(RmsChannel channel, string strDbName, out string strError) { bool bStartNotFound = false; bool bEndNotFound = false; strError = ""; // 如果edit中为空,则假定为“全部范围” if (textBox_startNo.Text == "") textBox_startNo.Text = "1"; if (textBox_endNo.Text == "") textBox_endNo.Text = "9999999999"; bool bAsc = true; Int64 nStart = 0; Int64 nEnd = 9999999999; try { nStart = Convert.ToInt64(textBox_startNo.Text); } catch { } try { nEnd = Convert.ToInt64(textBox_endNo.Text); } catch { } if (nStart > nEnd) bAsc = false; else bAsc = true; string strPath = strDbName + "/" + textBox_startNo.Text; string strStyle = "outputpath"; if (bAsc == true) strStyle += ",next,myself"; else strStyle += ",prev,myself"; string strResult; string strMetaData; byte [] baOutputTimeStamp; string strOutputPath; string strError0 = ""; string strStartID = ""; string strEndID = ""; // 获得资源 // return: // -1 出错。具体出错原因在this.ErrorCode中。this.ErrorInfo中有出错信息。 // 0 成功 long lRet = channel.GetRes(strPath, strStyle, out strResult, out strMetaData, out baOutputTimeStamp, out strOutputPath, out strError0); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) { strStartID = textBox_startNo.Text; bStartNotFound = true; } else strError += "校验startno时出错: " + strError0 + " "; } else { // 取得返回的id strStartID = ResPath.GetRecordId(strOutputPath); } if (strStartID == "") { strError = "strStartID为空..."; return -1; } strPath = strDbName + "/" + textBox_endNo.Text; strStyle = "outputpath"; if (bAsc == true) strStyle += ",prev,myself"; else strStyle += ",next,myself"; // 获得资源 // return: // -1 出错。具体出错原因在this.ErrorCode中。this.ErrorInfo中有出错信息。 // 0 成功 lRet = channel.GetRes(strPath, strStyle, out strResult, out strMetaData, out baOutputTimeStamp, out strOutputPath, out strError0); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) { strEndID = textBox_endNo.Text; bEndNotFound = true; } else strError += "校验endno时出错: " + strError0 + " "; } else { // 取得返回的id strEndID = ResPath.GetRecordId(strOutputPath); } if (strEndID == "") { strError = "strEndID为空..."; return -1; } /// bool bSkip = false; Int64 nTemp = 0; try { nTemp = Convert.ToInt64(strStartID); } catch { strError = "strStartID值 '" + strStartID + "' 不是数字..."; return -1; } if (bAsc == true) { if (nTemp > nEnd) { bSkip = true; } } else { if (nTemp < nEnd) { bSkip = true; } } if (bSkip == false) { textBox_startNo.Text = strStartID; } /// bSkip = false; try { nTemp = Convert.ToInt64(strEndID); } catch { strError = "strEndID值 '" + strEndID + "' 不是数字..."; return -1; } if (bAsc == true) { if (nTemp < nStart) { bSkip = true; } } else { if (nTemp > nStart) { bSkip = true; } } if (bSkip == false) { textBox_endNo.Text = strEndID; } if (bStartNotFound == true && bEndNotFound == true) return 0; return 1; } #endif private void treeView_rangeRes_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e) { /* if (treeView_rangeRes.CheckBoxes == false && treeView_rangeRes.SelectedNode == null) return; */ List<string> paths = treeView_rangeRes.GetCheckedDatabaseList(); if (paths.Count == 0) { textBox_dbPath.Text = ""; return; } // 多个数据库路径之间用';'隔开 string strText = ""; for (int i = 0; i < paths.Count; i++) { if (strText != "") strText += ";"; strText += paths[i]; } textBox_dbPath.Text = strText; /* if (treeView_rangeRes.SelectedNode.ImageIndex != ResTree.RESTYPE_DB) { textBox_dbPath.Text = ""; return; } ResPath respath = new ResPath(treeView_rangeRes.SelectedNode); textBox_dbPath.Text = respath.FullPath; */ // 当选择发生改变后,如果当前在“全部”状态,则要重设起止范围,以免误用了先前缩小过的其他库的范围 if (this.radioButton_all.Checked == true) { this.textBox_startNo.Text = "1"; this.textBox_endNo.Text = "9999999999"; } } private void radioButton_all_CheckedChanged(object sender, System.EventArgs e) { if (radioButton_all.Checked == true && m_nPreventNest == 0) { m_nPreventNest++; this.textBox_startNo.Text = "1"; this.textBox_endNo.Text = "9999999999"; m_nPreventNest--; } } void EnableControls(bool bEnabled) { textBox_startNo.Enabled = bEnabled; textBox_endNo.Enabled = bEnabled; checkBox_verifyNumber.Enabled = bEnabled; checkBox_forceLoop.Enabled = bEnabled; treeView_rangeRes.Enabled = bEnabled; radioButton_startEnd.Enabled = bEnabled; radioButton_all.Enabled = bEnabled; checkBox_export_delete.Enabled = bEnabled; /// this.textBox_import_dbMap.Enabled = bEnabled; textBox_import_fileName.Enabled = bEnabled; textBox_import_range.Enabled = bEnabled; this.button_import_dbMap.Enabled = bEnabled; button_import_findFileName.Enabled = bEnabled; this.checkBox_import_fastMode.Enabled = bEnabled; this.checkBox_export_fastMode.Enabled = bEnabled; } private void menuItem_serversCfg_Click(object sender, System.EventArgs e) { ServersDlg dlg = new ServersDlg(); MainForm.SetControlFont(dlg, this.DefaultFont); string strWidths = this.AppInfo.GetString( "serversdlg", "list_column_width", ""); if (String.IsNullOrEmpty(strWidths) == false) { ListViewUtil.SetColumnHeaderWidth(dlg.ListView, strWidths, true); } ServerCollection newServers = Servers.Dup(); dlg.Servers = newServers; //dlg.StartPosition = FormStartPosition.CenterScreen; //dlg.ShowDialog(this); this.AppInfo.LinkFormState(dlg, "serversdlg_state"); dlg.ShowDialog(this); this.AppInfo.UnlinkFormState(dlg); strWidths = ListViewUtil.GetColumnWidthListString(dlg.ListView); this.AppInfo.SetString( "serversdlg", "list_column_width", strWidths); if (dlg.DialogResult != DialogResult.OK) return; // this.Servers = newServers; this.Servers.Import(newServers); // treeView_rangeRes.Servers = this.Servers; treeView_rangeRes.Fill(null); } private void menuItem_copyright_Click(object sender, System.EventArgs e) { CopyrightDlg dlg = new CopyrightDlg(); MainForm.SetControlFont(dlg, this.DefaultFont); dlg.StartPosition = FormStartPosition.CenterScreen; dlg.ShowDialog(this); } private void menuItem_projectManage_Click(object sender, System.EventArgs e) { ProjectManageDlg dlg = new ProjectManageDlg(); MainForm.SetControlFont(dlg, this.DefaultFont); dlg.DataDir = this.DataDir; dlg.ProjectsUrl = "http://dp2003.com/dp2batch/projects/projects.xml"; dlg.HostName = "dp2Batch"; dlg.scriptManager = this.scriptManager; dlg.AppInfo = AppInfo; dlg.StartPosition = FormStartPosition.CenterScreen; dlg.ShowDialog(this); } // 启动运行一个方案 private void menuItem_run_Click(object sender, System.EventArgs e) { } private void scriptManager_CreateDefaultContent(object sender, CreateDefaultContentEventArgs e) { string strPureFileName = Path.GetFileName(e.FileName); if (String.Compare(strPureFileName, "main.cs", true) == 0) { CreateDefaultMainCsFile(e.FileName); e.Created = true; } else if (String.Compare(strPureFileName, "marcfilter.fltx", true) == 0) { CreateDefaultMarcFilterFile(e.FileName); e.Created = true; } else { e.Created = false; } } // 创建缺省的main.cs文件 public static int CreateDefaultMainCsFile(string strFileName) { using (StreamWriter sw = new StreamWriter(strFileName, false, Encoding.UTF8)) { sw.WriteLine("using System;"); sw.WriteLine("using System.Windows.Forms;"); sw.WriteLine("using System.IO;"); sw.WriteLine("using System.Text;"); sw.WriteLine(""); sw.WriteLine("using DigitalPlatform.MarcDom;"); sw.WriteLine("using DigitalPlatform.Statis;"); sw.WriteLine("using dp2Batch;"); sw.WriteLine("public class MyBatch : Batch"); sw.WriteLine("{"); sw.WriteLine(" public override void OnBegin(object sender, BatchEventArgs e)"); sw.WriteLine(" {"); sw.WriteLine(" }"); sw.WriteLine("}"); } return 0; } // 创建缺省的marcfilter.fltx文件 public static int CreateDefaultMarcFilterFile(string strFileName) { using (StreamWriter sw = new StreamWriter(strFileName, false, Encoding.UTF8)) { sw.WriteLine("<?xml version='1.0' encoding='utf-8'?>"); sw.WriteLine("<filter>"); sw.WriteLine("<using>"); sw.WriteLine("<![CDATA["); sw.WriteLine("using System;"); sw.WriteLine("using System.IO;"); sw.WriteLine("using System.Text;"); sw.WriteLine("using System.Windows.Forms;"); sw.WriteLine("using DigitalPlatform.MarcDom;"); sw.WriteLine("using DigitalPlatform.Marc;"); sw.WriteLine("using dp2Batch;"); sw.WriteLine("]]>"); sw.WriteLine("</using>"); sw.WriteLine(" <record>"); sw.WriteLine(" <def>"); sw.WriteLine(" <![CDATA["); sw.WriteLine(" int i;"); sw.WriteLine(" int j;"); sw.WriteLine(" ]]>"); sw.WriteLine(" </def>"); sw.WriteLine(" <begin>"); sw.WriteLine(" <![CDATA["); sw.WriteLine(" MessageBox.Show(\"record data:\" + this.Data);"); sw.WriteLine(" ]]>"); sw.WriteLine(" </begin>"); sw.WriteLine(" <field name=\"200\">"); sw.WriteLine(""); sw.WriteLine(" </field>"); sw.WriteLine(" <end>"); sw.WriteLine(" <![CDATA["); sw.WriteLine(""); sw.WriteLine(" j ++;"); sw.WriteLine(" ]]>"); sw.WriteLine(" </end>"); sw.WriteLine(" </record>"); sw.WriteLine("</filter>"); } return 0; } private void treeView_rangeRes_AfterCheck(object sender, TreeViewEventArgs e) { treeView_rangeRes_AfterSelect(sender, e); } private void menuItem_openDataFolder_Click(object sender, EventArgs e) { try { System.Diagnostics.Process.Start(this.DataDir); } catch (Exception ex) { MessageBox.Show(this, ExceptionUtil.GetAutoText(ex)); } } // 重建检索点 private void menuItem_rebuildKeys_Click(object sender, EventArgs e) { DoRebuildKeys(); } // 重建检索点 // TODO: 需要改造为在不校准首位号的情况下进度条也要显示正确。可参考DoExportFile() // parameters: void DoRebuildKeys() { string strError = ""; int nRet = 0; long lRet = 0; string strInfo = ""; // 汇总信息,在完成后显示 // bClearKeysAtBegin 批处理开始的时候清除了所有的keys表 // bDeleteOldKeysPerRecord 做每条记录的时候是否要先删除属于这条记录的旧的检索点。 bool bClearKeysAtBegin = true; bool bDeleteOldKeysPerRecord = false; m_nRecordCount = -1; if (textBox_dbPath.Text == "") { MessageBox.Show(this, "尚未选择要重建检索点的数据库 ..."); return; } DialogResult result = MessageBox.Show(this, "确实要对下列数据库\r\n---\r\n" + this.textBox_dbPath.Text.Replace(";", "\r\n") + "\r\n---\r\n进行重建检索点的操作?", "dp2batch", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResult.No) return; RebuildKeysDialog option_dlg = new RebuildKeysDialog(); MainForm.SetControlFont(option_dlg, this.DefaultFont); option_dlg.StartPosition = FormStartPosition.CenterScreen; option_dlg.ShowDialog(this); if (option_dlg.DialogResult == DialogResult.Cancel) return; if (option_dlg.WholeMode == true) { bClearKeysAtBegin = true; bDeleteOldKeysPerRecord = false; } else { bClearKeysAtBegin = false; bDeleteOldKeysPerRecord = true; } string[] dbpaths = textBox_dbPath.Text.Split(new char[] { ';' }); // 如果为单库输出 if (dbpaths.Length == 1) { // 否则移到DoExportFile()函数里面去校验 ResPath respath = new ResPath(dbpaths[0]); channel = this.Channels.GetChannel(respath.Url); string strDbName = respath.Path; // 校验起止号 if (checkBox_verifyNumber.Checked == true) { nRet = VerifyRange(channel, strDbName, out strError); if (nRet == -1) MessageBox.Show(this, strError); } else { if (this.textBox_startNo.Text == "") { strError = "尚未指定起始号"; goto ERROR1; } if (this.textBox_endNo.Text == "") { strError = "尚未指定结束号"; goto ERROR1; } } } else { Debug.Assert(dbpaths.Length > 1, ""); // 多库输出。修改界面要素,表示针对每个库都是全库处理 this.radioButton_all.Checked = true; this.textBox_startNo.Text = "1"; this.textBox_endNo.Text = "9999999999"; } stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在重建检索点"); stop.BeginLoop(); EnableControls(false); try { // TODO: 如果是多库输出,是否要对非“全部”的起止号范围进行警告? 因为后面是强迫按照全部来进行的 for (int f = 0; f < dbpaths.Length; f++) { string strOneDbPath = dbpaths[f]; ResPath respath = new ResPath(strOneDbPath); channel = this.Channels.GetChannel(respath.Url); string strDbName = respath.Path; if (String.IsNullOrEmpty(strInfo) == false) strInfo += "\r\n"; strInfo += "" + strDbName; // 实际处理的首尾号 string strRealStartNo = ""; string strRealEndNo = ""; /* DialogResult result; if (checkBox_export_delete.Checked == true) { result = MessageBox.Show(this, "确实要删除" + respath.Path + "内指定范围的记录?\r\n\r\n---------\r\n(是)删除 (否)放弃批处理", "dp2batch", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result != DialogResult.Yes) continue; }*/ // // 如果为多库重建 if (dbpaths.Length > 1) { // 如果为全选 if (this.radioButton_all.Checked == true || f > 0) { // 恢复为最大范围 this.textBox_startNo.Text = "1"; this.textBox_endNo.Text = "9999999999"; } // 校验起止号 if (checkBox_verifyNumber.Checked == true) { nRet = VerifyRange(channel, strDbName, out strError); if (nRet == -1) MessageBox.Show(this, strError); if (nRet == 0) { // 库中无记录 AutoCloseMessageBox.Show(this, "数据库 " + strDbName + " 中无记录。"); strInfo += "(无记录)"; /* if (bClearKeysAtBegin == true) { // 结束Refresh数据库定义 lRet = channel.DoRefreshDB( "end", strDbName, false, // 此参数此时无用 out strError); if (lRet == -1) goto ERROR1; } * */ continue; } } else { if (this.textBox_startNo.Text == "") { strError = "尚未指定起始号"; goto ERROR1; } if (this.textBox_endNo.Text == "") { strError = "尚未指定结束号"; goto ERROR1; } } } Int64 nStart; Int64 nEnd; Int64 nCur; bool bAsc = GetDirection( this.textBox_startNo.Text, this.textBox_endNo.Text, out nStart, out nEnd); // 设置进度条范围 Int64 nMax = nEnd - nStart; if (nMax < 0) nMax *= -1; nMax++; /* ProgressRatio = nMax / 10000; if (ProgressRatio < 1.0) ProgressRatio = 1.0; progressBar_main.Minimum = 0; progressBar_main.Maximum = (int)(nMax / ProgressRatio); progressBar_main.Value = 0; * */ stop.SetProgressRange(0, nMax); // Refresh数据库定义 lRet = channel.DoRefreshDB( "begin", strDbName, bClearKeysAtBegin == true ? true : false, out strError); if (lRet == -1) goto ERROR1; bool bFirst = true; // 是否为第一次取记录 string strID = this.textBox_startNo.Text; m_nRecordCount = 0; // 循环 for (; ; ) { Application.DoEvents(); // 出让界面控制权 if (stop.State != 0) { result = MessageBox.Show(this, "确实要中断当前批处理操作?", "dp2batch", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResult.Yes) { strError = "用户中断"; goto ERROR1; } else { stop.Continue(); } } string strDirectionComment = ""; string strStyle = ""; strStyle = "timestamp,outputpath"; // 优化 if (bDeleteOldKeysPerRecord == true) strStyle += ",forcedeleteoldkeys"; if (bFirst == true) { // 注:如果不校验首号,只有强制循环的情况下,才能不需要next风格 strStyle += ""; } else { if (bAsc == true) { strStyle += ",next"; strDirectionComment = "的后一条记录"; } else { strStyle += ",prev"; strDirectionComment = "的前一条记录"; } } string strPath = strDbName + "/" + strID; string strOutputPath = ""; bool bFoundRecord = false; bool bNeedRetry = true; REDO_REBUILD: // 获得资源 // return: // -1 出错。具体出错原因在this.ErrorCode中。this.ErrorInfo中有出错信息。 // 0 成功 lRet = channel.DoRebuildResKeys(strPath, strStyle, out strOutputPath, out strError); if (lRet == -1) { if (channel.ErrorCode == ChannelErrorCode.NotFound) { if (bFirst == true) { // 如果要强制循环 if (checkBox_forceLoop.Checked == true) { AutoCloseMessageBox.Show(this, "您为数据库 " + strDbName + " 指定的首记录 " + strID + strDirectionComment + " 不存在。\r\n\r\n按 确认 继续向后找。"); bFirst = false; goto CONTINUE; } else { // 如果不要强制循环,此时也不能结束,否则会让用户以为数据库里面根本没有数据 AutoCloseMessageBox.Show(this, "您为数据库 " + strDbName + " 指定的首记录 " + strID + strDirectionComment + " 不存在。\r\n\r\n(注:为避免出现此提示,可在操作前勾选“校准首尾ID”)\r\n\r\n按 确认 继续向后找..."); bFirst = false; goto CONTINUE; } } else { Debug.Assert(bFirst == false, ""); if (bFirst == true) { strError = "记录 " + strID + strDirectionComment + " 不存在。处理结束。"; } else { if (bAsc == true) strError = "记录 " + strID + " 是最末一条记录。处理结束。"; else strError = "记录 " + strID + " 是最前一条记录。处理结束。"; } if (dbpaths.Length > 1) break; // 多库情况,继续其它库循环 else { bNeedRetry = false; // 单库情况,也没有必要出现重试对话框 MessageBox.Show(this, strError); break; } } } else if (channel.ErrorCode == ChannelErrorCode.EmptyRecord) { bFirst = false; // bFoundRecord = false; // 把id解析出来 strID = ResPath.GetRecordId(strOutputPath); goto CONTINUE; } // 允许重试 if (bNeedRetry == true) { DialogResult redo_result = MessageBox.Show(this, "重建检索点 记录 '" + strPath + "' (style='" + strStyle + "')时出现错误: " + strError + "\r\n\r\n重试,还是中断当前批处理操作?\r\n(Retry 重试;Cancel 中断批处理)", "dp2batch", MessageBoxButtons.RetryCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (redo_result == DialogResult.Cancel) goto ERROR1; goto REDO_REBUILD; } else { goto ERROR1; } } // end of nRet == -1 bFirst = false; bFoundRecord = true; // 把id解析出来 strID = ResPath.GetRecordId(strOutputPath); stop.SetMessage("已重建检索点 记录 " + strOutputPath + " " + m_nRecordCount.ToString()); if (String.IsNullOrEmpty(strRealStartNo) == true) { strRealStartNo = strID; } strRealEndNo = strID; CONTINUE: // 是否超过循环范围 try { nCur = Convert.ToInt64(strID); } catch { // ??? nCur = 0; } if (bAsc == true && nCur > nEnd) break; if (bAsc == false && nCur < nEnd) break; if (bFoundRecord == true) m_nRecordCount++; // // if (bAsc == true) { // progressBar_main.Value = (int)((nCur - nStart + 1) / ProgressRatio); stop.SetProgressValue(nCur - nStart + 1); } else { // ? // progressBar_main.Value = (int)((nStart - nCur + 1) / ProgressRatio); stop.SetProgressValue(nStart - nCur + 1); } // 对已经作过的进行判断 if (bAsc == true && nCur >= nEnd) break; if (bAsc == false && nCur <= nEnd) break; } if (bClearKeysAtBegin == true) { // 结束Refresh数据库定义 lRet = channel.DoRefreshDB( "end", strDbName, false, // 此参数此时无用 out strError); if (lRet == -1) goto ERROR1; } strInfo += " : " + m_nRecordCount.ToString() + "条 (ID " + strRealStartNo + "-" + strRealEndNo + ")"; } // end of dbpaths loop } // end of try finally { EnableControls(true); stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); } strError = "重建检索点完成。\r\n---\r\n" + strInfo; // END1: MessageBox.Show(this, strError); return; ERROR1: MessageBox.Show(this, strError); } private void tabControl_main_SelectedIndexChanged(object sender, EventArgs e) { if (this.tabControl_main.SelectedTab == this.tabPage_range) { this.menuItem_rebuildKeys.Enabled = true; } else { this.menuItem_rebuildKeys.Enabled = false; } } private void menuItem_rebuildKeysByDbnames_Click(object sender, EventArgs e) { string strError = ""; bool bHasClipboardObject = false; IDataObject iData = Clipboard.GetDataObject(); if (iData == null || iData.GetDataPresent(typeof(string)) == false) bHasClipboardObject = false; else bHasClipboardObject = true; if (bHasClipboardObject == false) { strError = "当前Windows剪贴板中并没有包含数据库名信息"; goto ERROR1; } string strDbnames = (string)iData.GetData(typeof(string)); if (String.IsNullOrEmpty(strDbnames) == true) { strError = "当前Windows剪贴板中的数据库名信息为空"; goto ERROR1; } int nRet = strDbnames.IndexOf("?"); // .asmx? if (nRet == -1) { string strText = strDbnames; if (strText.Length > 1000) strText = strText.Substring(0, 1000) + "..."; strError = "当前Windows剪贴板中所包含的字符串 '" + strText + "' 不是数据库名格式"; goto ERROR1; } List<string> paths = new List<string>(); string[] parts = strDbnames.Split(new char[] { ';' }); for (int i = 0; i < parts.Length; i++) { string strPart = parts[i].Trim(); if (String.IsNullOrEmpty(strPart) == true) continue; paths.Add(strPart); } Cursor oldCursor = this.Cursor; this.Cursor = Cursors.WaitCursor; Application.DoEvents(); // 让光标形状显示出来 bool bRet = this.treeView_rangeRes.SelectDatabases(paths, out strError); this.Cursor = oldCursor; if (bRet == false) { strError = "下列数据库路径在资源树中不存在: \r\n---\r\n" + strError + "\r\n---\r\n\r\n请(用主菜单“文件/缺省帐户管理”命令)向资源树中添加新的服务器节点,或刷新资源树后,再重新进行重建检索点的操作"; goto ERROR1; } DoRebuildKeys(); return; ERROR1: MessageBox.Show(this, strError); } int m_nPreventNest = 0; private void textBox_startNo_TextChanged(object sender, EventArgs e) { if (m_nPreventNest == 0) { m_nPreventNest++; // 防止radioButton_all_CheckedChanged()随动 this.radioButton_startEnd.Checked = true; m_nPreventNest--; } } private void textBox_endNo_TextChanged(object sender, EventArgs e) { if (m_nPreventNest == 0) { m_nPreventNest++; // 防止radioButton_all_CheckedChanged()随动 this.radioButton_startEnd.Checked = true; m_nPreventNest--; } } private void checkBox_export_delete_CheckedChanged(object sender, EventArgs e) { if (this.checkBox_export_delete.Checked == true) this.checkBox_export_fastMode.Visible = true; else this.checkBox_export_fastMode.Visible = false; } public bool IsFirstRun { get { try { if (ApplicationDeployment.CurrentDeployment.IsFirstRun == true) return true; return false; } catch { return false; } } } void SetFirstDefaultFont() { if (this.DefaultFont != null) return; try { FontFamily family = new FontFamily("微软雅黑"); } catch { return; } this.DefaultFontString = "微软雅黑, 9pt"; } public string DefaultFontString { get { return this.AppInfo.GetString( "Global", "default_font", ""); } set { this.AppInfo.SetString( "Global", "default_font", value); } } new public Font DefaultFont { get { string strDefaultFontString = this.DefaultFontString; if (String.IsNullOrEmpty(strDefaultFontString) == true) { return GuiUtil.GetDefaultFont(); // 2015/5/8 // return null; } // Create the FontConverter. System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Font)); return (Font)converter.ConvertFromString(strDefaultFontString); } } // parameters: // bForce 是否强制设置。强制设置是指DefaultFont == null 的时候,也要按照Control.DefaultFont来设置 public static void SetControlFont(Control control, Font font, bool bForce = false) { if (font == null) { if (bForce == false) return; font = Control.DefaultFont; } if (font.Name == control.Font.Name && font.Style == control.Font.Style && font.SizeInPoints == control.Font.SizeInPoints) { } else control.Font = font; ChangeDifferentFaceFont(control, font); } static void ChangeDifferentFaceFont(Control parent, Font font) { // 修改所有下级控件的字体,如果字体名不一样的话 foreach (Control sub in parent.Controls) { Font subfont = sub.Font; float ratio = subfont.SizeInPoints / font.SizeInPoints; if (subfont.Name != font.Name || subfont.SizeInPoints != font.SizeInPoints) { sub.Font = new Font(font.FontFamily, ratio * font.SizeInPoints, subfont.Style, GraphicsUnit.Point); // sub.Font = new Font(font, subfont.Style); } if (sub is ToolStrip) { ChangeDifferentFaceFont((ToolStrip)sub, font); } // 递归 ChangeDifferentFaceFont(sub, font); } } static void ChangeDifferentFaceFont(ToolStrip tool, Font font) { // 修改所有事项的字体,如果字体名不一样的话 for (int i = 0; i < tool.Items.Count; i++) { ToolStripItem item = tool.Items[i]; Font subfont = item.Font; float ratio = subfont.SizeInPoints / font.SizeInPoints; if (subfont.Name != font.Name || subfont.SizeInPoints != font.SizeInPoints) { // item.Font = new Font(font, subfont.Style); item.Font = new Font(font.FontFamily, ratio * font.SizeInPoints, subfont.Style, GraphicsUnit.Point); } } } } public enum ExportFileType { BackupFile = 0, XmlFile = 1, ISO2709File = 2, } public class MyFilterDocument : FilterDocument { public Batch Batch = null; } // 浏览记录到达 public delegate void CheckTargetDbEventHandler(object sender, CheckTargetDbEventArgs e); public class CheckTargetDbEventArgs : EventArgs { public string DbFullPath = ""; // 目标数据库全路径 public string CurrentMarcSyntax = ""; // 当前记录的 MARC 格式 2014/5/28 public bool Cancel = false; // 是否需要中断 public string ErrorInfo = ""; // 回调期间发生的错误信息 } }
33.783379
236
0.447834
[ "Apache-2.0" ]
jasonliaocn/dp2
dp2Batch/MainForm.cs
248,668
C#
using BookmarkManager.Domain.Dtos; using BookmarkManager.Domain.Models; using BookmarkManager.Tests.Support; using System; using System.Net; using System.Net.Http.Json; using System.Threading.Tasks; using Xunit; namespace BookmarkManager.Tests.Integration.Controllers.V1 { public class BookmarkControllerTests : WebHostFixture { [Fact(DisplayName = "Should return not found if bookmark does not exist")] public async Task GetBookmarkAsync_ShouldReturnNotFoundIfBookmarkDoesNotExist() { // arrange var id = Guid.NewGuid(); // act var result = await Client.GetAsync($"api/v1/bookmarks/{id}"); // assert Assert.Equal(HttpStatusCode.NotFound, result.StatusCode); } [Fact(DisplayName = "Should get bookmark")] public async Task GetBookmarkAsync_ShouldGetBookmark() { // arrange var id = Guid.Parse("0f899b5d-eb91-4b6a-8aa1-149fee29cc30"); DbContext.Bookmarks.AddRange( new Bookmark("https://excalidraw.com/") { Id = id }, new Bookmark("https://www.guidgenerator.com/")); DbContext.SaveChanges(); // act var result = await Client.GetAsync($"api/v1/bookmarks/{id}"); // assert Assert.Equal(HttpStatusCode.OK, result.StatusCode); var bookmark = await result.Content.ReadFromJsonAsync<Bookmark>(); Assert.Equal("https://excalidraw.com/", bookmark.Url); } [Fact(DisplayName = "Should add bookmark")] public async Task AddBookmarkAsync_ShouldAddBookmark() { // arrange var request = new AddBookmarkRequest("http://www.google.com"); // act var result = await Client.PostAsJsonAsync($"api/v1/bookmarks", request); // assert Assert.Equal(HttpStatusCode.Created, result.StatusCode); } } }
33.133333
87
0.613179
[ "MIT" ]
rafaelpadovezi/bookmark-manager
tests/Integration/Controllers/V1/BookmarkControllerTests.cs
1,990
C#
using System.Collections.Generic; namespace FakeServer.Authentication { public class AuthenticationSettings { public bool Enabled { get; set; } public IEnumerable<User> Users { get; set; } } public class User { public string Username { get; set; } public string Password { get; set; } } }
19.388889
52
0.621777
[ "MIT" ]
Lucarine/dotnet-fake-json-server
FakeServer/Authentication/AuthenticationSettings.cs
351
C#
using System; using System.Collections.Generic; namespace StealthyCommerce.Service.StealthyCommerceDBEntities { public partial class Customer { public Customer() { Order = new HashSet<Order>(); } public int CustomerId { get; set; } public string EmailAddress { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTime DateCreated { get; set; } public DateTime DateModified { get; set; } public virtual ICollection<Order> Order { get; set; } } }
26.043478
61
0.616027
[ "MIT" ]
ronakal/StealthyCommerce
StealthyCommerce/StealthyCommerce.Service/StealthyCommerceDBEntities/Customer.cs
601
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/wincodec.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { [Guid("F928B7B8-2221-40C1-B72E-7E82F1974D1A")] [NativeTypeName("struct IWICPlanarBitmapFrameEncode : IUnknown")] public unsafe partial struct IWICPlanarBitmapFrameEncode { public void** lpVtbl; [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) { return ((delegate* unmanaged<IWICPlanarBitmapFrameEncode*, Guid*, void**, int>)(lpVtbl[0]))((IWICPlanarBitmapFrameEncode*)Unsafe.AsPointer(ref this), riid, ppvObject); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* unmanaged<IWICPlanarBitmapFrameEncode*, uint>)(lpVtbl[1]))((IWICPlanarBitmapFrameEncode*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* unmanaged<IWICPlanarBitmapFrameEncode*, uint>)(lpVtbl[2]))((IWICPlanarBitmapFrameEncode*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int WritePixels([NativeTypeName("UINT")] uint lineCount, WICBitmapPlane* pPlanes, [NativeTypeName("UINT")] uint cPlanes) { return ((delegate* unmanaged<IWICPlanarBitmapFrameEncode*, uint, WICBitmapPlane*, uint, int>)(lpVtbl[3]))((IWICPlanarBitmapFrameEncode*)Unsafe.AsPointer(ref this), lineCount, pPlanes, cPlanes); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int WriteSource(IWICBitmapSource** ppPlanes, [NativeTypeName("UINT")] uint cPlanes, WICRect* prcSource) { return ((delegate* unmanaged<IWICPlanarBitmapFrameEncode*, IWICBitmapSource**, uint, WICRect*, int>)(lpVtbl[4]))((IWICPlanarBitmapFrameEncode*)Unsafe.AsPointer(ref this), ppPlanes, cPlanes, prcSource); } } }
47.351852
213
0.700039
[ "MIT" ]
manju-summoner/terrafx.interop.windows
sources/Interop/Windows/um/wincodec/IWICPlanarBitmapFrameEncode.cs
2,559
C#
namespace RabbitFarm.WebAPI.DataModels { using System.ComponentModel.DataAnnotations; using RabbitFarm.Models; public class PurchaseModel { public int Id { get; set; } [Required(ErrorMessage = "Purchase Name is required")] [MinLength(3, ErrorMessage = "Purchase Name must be at least 3 characters")] public string Name { get; set; } [Required(ErrorMessage = "Purchase Category is required")] public PurchaseCategory PurchaseCategory { get; set; } [Required(ErrorMessage = "Purchase Unit is required")] public Unit Unit { get; set; } [Required(ErrorMessage = "Purchase Unit Price is required")] [Range(0, double.MaxValue, ErrorMessage = "Unit Price must be positive number")] public decimal UnitPrice { get; set; } [Required(ErrorMessage = "Purchase Amount is required")] [Range(0, double.MaxValue, ErrorMessage = "Amount must be positive number")] public double Amount { get; set; } public decimal TotalPrice { get { return (decimal)this.Amount * this.UnitPrice; } } [MinLength(3, ErrorMessage = "Purchase Lot is required")] public string Lot { get; set; } [Required(ErrorMessage = "FarmId is required")] public int FarmId { get; set; } } }
33.325581
89
0.597348
[ "MIT" ]
Team-Antalya/Rabbit-Farm
RabbitFarm/RabbitFarm.WebAPI/DataModels/PurchaseModel.cs
1,435
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.Sql.Models; namespace Azure.ResourceManager.Sql { internal partial class LedgerDigestUploadsRestOperations { private readonly TelemetryDetails _userAgent; private readonly HttpPipeline _pipeline; private readonly Uri _endpoint; private readonly string _apiVersion; /// <summary> Initializes a new instance of LedgerDigestUploadsRestOperations. </summary> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="applicationId"> The application id to use for user agent. </param> /// <param name="endpoint"> server parameter. </param> /// <param name="apiVersion"> Api Version. </param> /// <exception cref="ArgumentNullException"> <paramref name="pipeline"/> or <paramref name="apiVersion"/> is null. </exception> public LedgerDigestUploadsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) { _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); _endpoint = endpoint ?? new Uri("https://management.azure.com"); _apiVersion = apiVersion ?? "2021-02-01-preview"; _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); } internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string serverName, string databaseName, LedgerDigestUploadsName ledgerDigestUploads) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Sql/servers/", false); uri.AppendPath(serverName, true); uri.AppendPath("/databases/", false); uri.AppendPath(databaseName, true); uri.AppendPath("/ledgerDigestUploads/", false); uri.AppendPath(ledgerDigestUploads.ToString(), true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); _userAgent.Apply(message); return message; } /// <summary> Gets the current ledger digest upload configuration for a database. </summary> /// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="ledgerDigestUploads"> The LedgerDigestUploadsName to use. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<LedgerDigestUploadsData>> GetAsync(string subscriptionId, string resourceGroupName, string serverName, string databaseName, LedgerDigestUploadsName ledgerDigestUploads, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(serverName, nameof(serverName)); Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName)); using var message = CreateGetRequest(subscriptionId, resourceGroupName, serverName, databaseName, ledgerDigestUploads); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { LedgerDigestUploadsData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = LedgerDigestUploadsData.DeserializeLedgerDigestUploadsData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((LedgerDigestUploadsData)null, message.Response); default: throw new RequestFailedException(message.Response); } } /// <summary> Gets the current ledger digest upload configuration for a database. </summary> /// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="ledgerDigestUploads"> The LedgerDigestUploadsName to use. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is an empty string, and was expected to be non-empty. </exception> public Response<LedgerDigestUploadsData> Get(string subscriptionId, string resourceGroupName, string serverName, string databaseName, LedgerDigestUploadsName ledgerDigestUploads, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(serverName, nameof(serverName)); Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName)); using var message = CreateGetRequest(subscriptionId, resourceGroupName, serverName, databaseName, ledgerDigestUploads); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { LedgerDigestUploadsData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = LedgerDigestUploadsData.DeserializeLedgerDigestUploadsData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((LedgerDigestUploadsData)null, message.Response); default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, string serverName, string databaseName, LedgerDigestUploadsName ledgerDigestUploads, LedgerDigestUploadsData parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Sql/servers/", false); uri.AppendPath(serverName, true); uri.AppendPath("/databases/", false); uri.AppendPath(databaseName, true); uri.AppendPath("/ledgerDigestUploads/", false); uri.AppendPath(ledgerDigestUploads.ToString(), true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; _userAgent.Apply(message); return message; } /// <summary> Enables upload ledger digests to an Azure Storage account or an Azure Confidential Ledger instance. </summary> /// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="ledgerDigestUploads"> The LedgerDigestUploadsName to use. </param> /// <param name="parameters"> The LedgerDigestUploads to use. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/> or <paramref name="parameters"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response> CreateOrUpdateAsync(string subscriptionId, string resourceGroupName, string serverName, string databaseName, LedgerDigestUploadsName ledgerDigestUploads, LedgerDigestUploadsData parameters, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(serverName, nameof(serverName)); Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName)); Argument.AssertNotNull(parameters, nameof(parameters)); using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, serverName, databaseName, ledgerDigestUploads, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw new RequestFailedException(message.Response); } } /// <summary> Enables upload ledger digests to an Azure Storage account or an Azure Confidential Ledger instance. </summary> /// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="ledgerDigestUploads"> The LedgerDigestUploadsName to use. </param> /// <param name="parameters"> The LedgerDigestUploads to use. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/> or <paramref name="parameters"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is an empty string, and was expected to be non-empty. </exception> public Response CreateOrUpdate(string subscriptionId, string resourceGroupName, string serverName, string databaseName, LedgerDigestUploadsName ledgerDigestUploads, LedgerDigestUploadsData parameters, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(serverName, nameof(serverName)); Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName)); Argument.AssertNotNull(parameters, nameof(parameters)); using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, serverName, databaseName, ledgerDigestUploads, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateListByDatabaseRequest(string subscriptionId, string resourceGroupName, string serverName, string databaseName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Sql/servers/", false); uri.AppendPath(serverName, true); uri.AppendPath("/databases/", false); uri.AppendPath(databaseName, true); uri.AppendPath("/ledgerDigestUploads", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); _userAgent.Apply(message); return message; } /// <summary> Gets all ledger digest upload settings on a database. </summary> /// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<LedgerDigestUploadsListResult>> ListByDatabaseAsync(string subscriptionId, string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(serverName, nameof(serverName)); Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName)); using var message = CreateListByDatabaseRequest(subscriptionId, resourceGroupName, serverName, databaseName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { LedgerDigestUploadsListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = LedgerDigestUploadsListResult.DeserializeLedgerDigestUploadsListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> Gets all ledger digest upload settings on a database. </summary> /// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is an empty string, and was expected to be non-empty. </exception> public Response<LedgerDigestUploadsListResult> ListByDatabase(string subscriptionId, string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(serverName, nameof(serverName)); Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName)); using var message = CreateListByDatabaseRequest(subscriptionId, resourceGroupName, serverName, databaseName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { LedgerDigestUploadsListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = LedgerDigestUploadsListResult.DeserializeLedgerDigestUploadsListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateDisableRequest(string subscriptionId, string resourceGroupName, string serverName, string databaseName, LedgerDigestUploadsName ledgerDigestUploads) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Sql/servers/", false); uri.AppendPath(serverName, true); uri.AppendPath("/databases/", false); uri.AppendPath(databaseName, true); uri.AppendPath("/ledgerDigestUploads/", false); uri.AppendPath(ledgerDigestUploads.ToString(), true); uri.AppendPath("/disable", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); _userAgent.Apply(message); return message; } /// <summary> Disables uploading ledger digests to an Azure Storage account or an Azure Confidential Ledger instance. </summary> /// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="ledgerDigestUploads"> The LedgerDigestUploadsName to use. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response> DisableAsync(string subscriptionId, string resourceGroupName, string serverName, string databaseName, LedgerDigestUploadsName ledgerDigestUploads, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(serverName, nameof(serverName)); Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName)); using var message = CreateDisableRequest(subscriptionId, resourceGroupName, serverName, databaseName, ledgerDigestUploads); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw new RequestFailedException(message.Response); } } /// <summary> Disables uploading ledger digests to an Azure Storage account or an Azure Confidential Ledger instance. </summary> /// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="ledgerDigestUploads"> The LedgerDigestUploadsName to use. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is an empty string, and was expected to be non-empty. </exception> public Response Disable(string subscriptionId, string resourceGroupName, string serverName, string databaseName, LedgerDigestUploadsName ledgerDigestUploads, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(serverName, nameof(serverName)); Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName)); using var message = CreateDisableRequest(subscriptionId, resourceGroupName, serverName, databaseName, ledgerDigestUploads); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: return message.Response; default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateListByDatabaseNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string serverName, string databaseName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); _userAgent.Apply(message); return message; } /// <summary> Gets all ledger digest upload settings on a database. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<LedgerDigestUploadsListResult>> ListByDatabaseNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken = default) { Argument.AssertNotNull(nextLink, nameof(nextLink)); Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(serverName, nameof(serverName)); Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName)); using var message = CreateListByDatabaseNextPageRequest(nextLink, subscriptionId, resourceGroupName, serverName, databaseName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { LedgerDigestUploadsListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = LedgerDigestUploadsListResult.DeserializeLedgerDigestUploadsListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> Gets all ledger digest upload settings on a database. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param> /// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param> /// <param name="serverName"> The name of the server. </param> /// <param name="databaseName"> The name of the database. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is an empty string, and was expected to be non-empty. </exception> public Response<LedgerDigestUploadsListResult> ListByDatabaseNextPage(string nextLink, string subscriptionId, string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken = default) { Argument.AssertNotNull(nextLink, nameof(nextLink)); Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(serverName, nameof(serverName)); Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName)); using var message = CreateListByDatabaseNextPageRequest(nextLink, subscriptionId, resourceGroupName, serverName, databaseName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { LedgerDigestUploadsListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = LedgerDigestUploadsListResult.DeserializeLedgerDigestUploadsListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } } }
70.109208
272
0.672032
[ "MIT" ]
Ramananaidu/dotnet-sonarqube
sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/RestOperations/LedgerDigestUploadsRestOperations.cs
32,741
C#
using TestStack.White.AutomationElementSearch; using TestStack.White.UIItems.Finders; using Xunit; namespace TestStack.White.UnitTests.AutomationElementSearch { public class SearchConditionTest { [Fact] public void TestToString() { const string name = "blah"; string @string = AutomationSearchCondition.ByName(name).ToString(); Assert.True(@string.Contains(name), @string); } [Fact] public void EqualsTests() { Assert.Equal(SearchConditionFactory.CreateForAutomationId("foo"), SearchConditionFactory.CreateForAutomationId("foo")); Assert.NotEqual(SearchConditionFactory.CreateForAutomationId("foo"), SearchConditionFactory.CreateForAutomationId("foo1")); Assert.NotEqual(SearchConditionFactory.CreateForAutomationId("foo"), SearchConditionFactory.CreateForName(("foo"))); } } }
38.04
136
0.669821
[ "Apache-2.0", "MIT" ]
DaveWeath/White
src/TestStack.White.UnitTests/AutomationElementSearch/SearchConditionTest.cs
927
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using HotChocolate.Language; using HotChocolate.Properties; using HotChocolate.Resolvers; using HotChocolate.Types; using HotChocolate.Utilities; using static HotChocolate.Execution.ArgumentNonNullValidator; namespace HotChocolate.Execution { internal sealed class FieldCollector { private const string _argumentProperty = "argument"; private readonly FragmentCollection _fragments; private readonly Func<ObjectField, FieldNode, FieldDelegate> _factory; private readonly ITypeConversion _converter; private readonly IReadOnlyList<IArgumentCoercionHandler> _coercionHandlers; private readonly Func<IInputField, object, object> _coerceArgumentValue; public FieldCollector( FragmentCollection fragments, Func<ObjectField, FieldNode, FieldDelegate> middlewareFactory, ITypeConversion converter, IEnumerable<IArgumentCoercionHandler> argumentCoercionHandlers) { _fragments = fragments ?? throw new ArgumentNullException(nameof(fragments)); _factory = middlewareFactory ?? throw new ArgumentNullException(nameof(middlewareFactory)); _converter = converter ?? throw new ArgumentNullException(nameof(converter)); _coercionHandlers = argumentCoercionHandlers is null ? Array.Empty<IArgumentCoercionHandler>() : argumentCoercionHandlers.ToArray(); _coerceArgumentValue = CoerceArgumentValue; } public IReadOnlyList<FieldSelection> CollectFields( ObjectType type, SelectionSetNode selectionSet, Path path) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (selectionSet == null) { throw new ArgumentNullException(nameof(selectionSet)); } var fields = new OrderedDictionary<string, FieldInfo>(); CollectFields(type, selectionSet, path, null, fields); int i = 0; var fieldSelections = new FieldSelection[fields.Count]; foreach (FieldInfo field in fields.Values) { field.Middleware = _factory(field.Field, field.Selection); fieldSelections[i++] = new FieldSelection(field); } return fieldSelections; } private void CollectFields( ObjectType type, SelectionSetNode selectionSet, Path path, FieldVisibility fieldVisibility, IDictionary<string, FieldInfo> fields) { foreach (ISelectionNode selection in selectionSet.Selections) { ResolveFields( type, selection, path, ExtractVisibility(selection, fieldVisibility), fields); } } private void ResolveFields( ObjectType type, ISelectionNode selection, Path path, FieldVisibility fieldVisibility, IDictionary<string, FieldInfo> fields) { if (selection is FieldNode fs) { ResolveFieldSelection( type, fs, path, fieldVisibility, fields); } else if (selection is FragmentSpreadNode fragSpread) { ResolveFragmentSpread( type, fragSpread, path, fieldVisibility, fields); } else if (selection is InlineFragmentNode inlineFrag) { ResolveInlineFragment( type, inlineFrag, path, fieldVisibility, fields); } } private void ResolveFieldSelection( ObjectType type, FieldNode fieldSelection, Path path, FieldVisibility fieldVisibility, IDictionary<string, FieldInfo> fields) { NameString fieldName = fieldSelection.Name.Value; NameString responseName = fieldSelection.Alias == null ? fieldSelection.Name.Value : fieldSelection.Alias.Value; if (type.Fields.TryGetField(fieldName, out ObjectField field)) { if (fields.TryGetValue(responseName, out FieldInfo fieldInfo)) { AddSelection(fieldInfo, fieldSelection); TryAddFieldVisibility(fieldInfo, fieldVisibility); } else { fieldInfo = new FieldInfo { Field = field, ResponseName = responseName, Selection = fieldSelection, Path = path }; TryAddFieldVisibility(fieldInfo, fieldVisibility); CoerceArgumentValues(fieldInfo); fields.Add(responseName, fieldInfo); } } else { throw new QueryException(ErrorBuilder.New() .SetMessage(CoreResources.FieldCollector_FieldNotFound) .SetPath(path) .AddLocation(fieldSelection) .Build()); } } private void ResolveFragmentSpread( ObjectType type, FragmentSpreadNode fragmentSpread, Path path, FieldVisibility fieldVisibility, IDictionary<string, FieldInfo> fields) { Fragment fragment = _fragments.GetFragment( fragmentSpread.Name.Value); if (fragment != null && DoesTypeApply(fragment.TypeCondition, type)) { CollectFields( type, fragment.SelectionSet, path, fieldVisibility, fields); } } private void ResolveInlineFragment( ObjectType type, InlineFragmentNode inlineFragment, Path path, FieldVisibility fieldVisibility, IDictionary<string, FieldInfo> fields) { Fragment fragment = _fragments.GetFragment(type, inlineFragment); if (DoesTypeApply(fragment.TypeCondition, type)) { CollectFields( type, fragment.SelectionSet, path, fieldVisibility, fields); } } private static FieldVisibility ExtractVisibility( Language.IHasDirectives selection, FieldVisibility fieldVisibility) { IValueNode skip = selection.Directives.SkipValue(); IValueNode include = selection.Directives.IncludeValue(); if (skip == null && include == null) { return fieldVisibility; } return new FieldVisibility(skip, include, fieldVisibility); } private static bool DoesTypeApply( IType typeCondition, ObjectType current) { if (typeCondition is ObjectType ot) { return ot == current; } else if (typeCondition is InterfaceType it) { return current.Interfaces.ContainsKey(it.Name); } else if (typeCondition is UnionType ut) { return ut.Types.ContainsKey(current.Name); } return false; } private void CoerceArgumentValues(FieldInfo fieldInfo) { var argumentValues = fieldInfo.Selection.Arguments .Where(t => t.Value != null) .ToDictionary(t => t.Name.Value, t => t.Value); foreach (Argument argument in fieldInfo.Field.Arguments) { try { CoerceArgumentValue( fieldInfo, argument, argumentValues); } catch (ScalarSerializationException ex) { fieldInfo.Arguments[argument.Name] = new ArgumentValue( argument, ErrorBuilder.New() .SetMessage(ex.Message) .AddLocation(fieldInfo.Selection) .SetExtension(_argumentProperty, argument.Name) .SetPath(fieldInfo.Path.AppendOrCreate( fieldInfo.ResponseName)) .Build()); } } } private void CoerceArgumentValue( FieldInfo fieldInfo, IInputField argument, IDictionary<string, IValueNode> argumentValues) { if (argumentValues.TryGetValue(argument.Name, out IValueNode literal)) { if (literal is VariableNode variable) { if (fieldInfo.VarArguments == null) { fieldInfo.VarArguments = new Dictionary<NameString, ArgumentVariableValue>(); } object defaultValue = argument.Type.IsLeafType() ? ParseLiteral(argument.Type, argument.DefaultValue) : argument.DefaultValue; defaultValue = CoerceArgumentValue(argument, defaultValue); fieldInfo.VarArguments[argument.Name] = new ArgumentVariableValue( argument, variable.Name.Value, defaultValue, _coerceArgumentValue); } else { CreateArgumentValue(fieldInfo, argument, literal); } } else { CreateArgumentValue(fieldInfo, argument, argument.DefaultValue); } } private void CreateArgumentValue( FieldInfo fieldInfo, IInputField argument, IValueNode literal) { if (fieldInfo.Arguments == null) { fieldInfo.Arguments = new Dictionary<NameString, ArgumentValue>(); } Report report = ArgumentNonNullValidator.Validate( argument.Type, literal, Path.New(argument.Name)); if (report.HasErrors) { IError error = ErrorBuilder.New() .SetMessage(string.Format( CultureInfo.InvariantCulture, TypeResources.ArgumentValueBuilder_NonNull, argument.Name, TypeVisualizer.Visualize(report.Type))) .AddLocation(fieldInfo.Selection) .SetExtension(_argumentProperty, report.Path.ToCollection()) .SetPath(fieldInfo.Path.AppendOrCreate( fieldInfo.ResponseName)) .Build(); fieldInfo.Arguments[argument.Name] = new ArgumentValue(argument, error); } else if (argument.Type.IsLeafType() && IsLeafLiteral(literal)) { object coerced = CoerceArgumentValue(argument, ParseLiteral(argument.Type, literal)); fieldInfo.Arguments[argument.Name] = new ArgumentValue( argument, literal.GetValueKind(), coerced); } else { object coerced = CoerceArgumentValue(argument, literal); fieldInfo.Arguments[argument.Name] = new ArgumentValue( argument, literal.GetValueKind(), coerced); } } private bool IsLeafLiteral(IValueNode value) { if (value is ObjectValueNode) { return false; } if (value is ListValueNode list) { for (int i = 0; i < list.Items.Count; i++) { if (!IsLeafLiteral(list.Items[i])) { return false; } } } return true; } private static void AddSelection( FieldInfo fieldInfo, FieldNode fieldSelection) { if (fieldInfo.Nodes == null) { fieldInfo.Nodes = new List<FieldNode>(); } fieldInfo.Nodes.Add(fieldSelection); } private static void TryAddFieldVisibility( FieldInfo fieldInfo, FieldVisibility fieldVisibility) { if (fieldVisibility != null) { if (fieldInfo.Visibilities == null) { fieldInfo.Visibilities = new List<FieldVisibility>(); } fieldInfo.Visibilities.Add(fieldVisibility); } } private static object ParseLiteral( IInputType argumentType, IValueNode value) { IInputType type = (argumentType is NonNullType) ? (IInputType)argumentType.InnerType() : argumentType; return type.ParseLiteral(value); } private object CoerceArgumentValue(IInputField argument, object value) { if (_coercionHandlers.Count == 0) { return value; } object current = value; for (int i = 0; i < _coercionHandlers.Count; i++) { current = _coercionHandlers[i].CoerceValue(argument, current); } return current; } } }
33.634312
83
0.493221
[ "MIT" ]
Elywejnak/hotchocolate
src/Core/Core/Execution/Utilities/FieldCollector.cs
14,900
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour, CollisionHandler { public static Enemy mob; public Transform body; public int health = 5; public float bodyDamage; public GameObject coin; public Transform GetBody() { return body; } public void TakeDamage(int damage) { health -= damage; if (health <= 0) { Die(); } } void Die() { Instantiate(coin, new Vector3(body.position.x, body.position.y + 0.5f, body.position.z), body.rotation); Destroy(gameObject); } private void OnTriggerEnter2D(Collider2D other) { //Debug.Log("TOUCHING!"); if (other.gameObject.CompareTag("Player")) { ScoreManager.instance.ChangeHealth(bodyDamage); } } }
18.914894
112
0.595051
[ "MIT" ]
brimatt16219/Knightshacks-Hackathon
Knightshacks Project/Assets/Scripts/Enemy.cs
889
C#
using System.Collections.Generic; namespace Sidekick.Business.Filters { public class Exchange { public List<string> Want { get; set; } = new List<string>(); public List<string> Have { get; set; } = new List<string>(); public Status Status { get; set; } = new Status(); } }
22.285714
68
0.612179
[ "MIT" ]
cmos12345/Sidekick
src/Sidekick.Business/Filters/Exchange.cs
312
C#
using Newtonsoft.Json; using System; namespace BinanceChain { [Serializable] public sealed class TransactionCoin { [JsonProperty] private string denom; [JsonProperty] private string amount; [JsonIgnore] private decimal? _amount; public string Denom { get => denom; } public decimal Amount { get { if (_amount == null) { _amount = decimal.Parse(amount); switch (denom) { case "AWC-986": _amount /= 100000000; break; } } return _amount.Value; } } } }
20.925
56
0.396655
[ "MIT" ]
Mathias-Hedelund-Larsen/Crypto_Transaction_Assistant
Assets/Scripts/Other/JsonModels/BinanceChain/TransactionCoin.cs
839
C#
using System; using System.Diagnostics; using NPoco; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Dtos; using Umbraco.Tests.TestHelpers; namespace Umbraco.Tests.Persistence.Querying { [TestFixture] public class MediaTypeRepositorySqlClausesTest : BaseUsingSqlCeSyntax { [Test] public void Can_Verify_Base_Clause() { var NodeObjectTypeId = Constants.ObjectTypes.MediaType; var expected = new Sql(); expected.Select("*") .From("[cmsContentType]") .InnerJoin("[umbracoNode]").On("[cmsContentType].[nodeId] = [umbracoNode].[id]") .Where("([umbracoNode].[nodeObjectType] = @0)", new Guid("4ea4382b-2f5a-4c2b-9587-ae9b3cf3602e")); var sql = Sql(); sql.SelectAll() .From<ContentTypeDto>() .InnerJoin<NodeDto>() .On<ContentTypeDto, NodeDto>(left => left.NodeId, right => right.NodeId) .Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId); Assert.That(sql.SQL, Is.EqualTo(expected.SQL)); Assert.AreEqual(expected.Arguments.Length, sql.Arguments.Length); for (int i = 0; i < expected.Arguments.Length; i++) { Assert.AreEqual(expected.Arguments[i], sql.Arguments[i]); } Debug.Print(sql.SQL); } } }
33.622222
115
0.57766
[ "MIT" ]
ismailmayat/Umbraco-CMS
src/Umbraco.Tests/Persistence/Querying/MediaTypeRepositorySqlClausesTest.cs
1,515
C#
// Copyright 2018 by JCoder58. See License.txt for license // Auto-generated --- Do not modify. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UE4.Core; using UE4.CoreUObject; using UE4.CoreUObject.Native; using UE4.InputCore; using UE4.Native; #pragma warning disable CS0108 using UE4.UMG.Native; using UE4.Engine; namespace UE4.UMG { ///<summary>The widget component provides a surface in the 3D environment on which to render widgets normally rendered to the screen.</summary> ///<remarks> ///Widgets are first rendered to a render target, then that render target is displayed in the world. /// ///Material Properties set by this component on whatever material overrides the default. ///SlateUI [Texture] ///BackColor [Vector] ///TintColorAndOpacity [Vector] ///OpacityFromTexture [Scalar] ///</remarks> public unsafe partial class WidgetComponent : MeshComponent { ///<summary>@return The draw size of the quad in the world</summary> public Vector2D GetDrawSize() => WidgetComponent_methods.GetDrawSize_method.Invoke(ObjPointer); ///<summary>@return The dynamic material instance used to render the user widget</summary> public MaterialInstanceDynamic GetMaterialInstance() => WidgetComponent_methods.GetMaterialInstance_method.Invoke(ObjPointer); ///<summary>Gets the local player that owns this widget component.</summary> public LocalPlayer GetOwnerPlayer() => WidgetComponent_methods.GetOwnerPlayer_method.Invoke(ObjPointer); ///<summary>@return The render target to which the user widget is rendered</summary> public TextureRenderTarget2D GetRenderTarget() => WidgetComponent_methods.GetRenderTarget_method.Invoke(ObjPointer); ///<summary>@return The user widget object displayed by this component</summary> public UserWidget GetUserWidgetObject() => WidgetComponent_methods.GetUserWidgetObject_method.Invoke(ObjPointer); ///<summary>Requests that the widget be redrawn.</summary> public void RequestRedraw() => WidgetComponent_methods.RequestRedraw_method.Invoke(ObjPointer); ///<summary>Sets the background color and opacityscale for this widget</summary> public void SetBackgroundColor(LinearColor NewBackgroundColor) => WidgetComponent_methods.SetBackgroundColor_method.Invoke(ObjPointer, NewBackgroundColor); ///<summary>Sets the draw size of the quad in the world</summary> public void SetDrawSize(Vector2D Size) => WidgetComponent_methods.SetDrawSize_method.Invoke(ObjPointer, Size); ///<summary>@see bManuallyRedraw</summary> public void SetManuallyRedraw(bool bUseManualRedraw) => WidgetComponent_methods.SetManuallyRedraw_method.Invoke(ObjPointer, bUseManualRedraw); ///<summary>Sets the local player that owns this widget component.</summary> ///<remarks> ///Setting the owning player controls ///which player's viewport the widget appears on in a split screen scenario. Additionally it ///forwards the owning player to the actual UserWidget that is spawned. ///</remarks> public void SetOwnerPlayer(LocalPlayer LocalPlayer) => WidgetComponent_methods.SetOwnerPlayer_method.Invoke(ObjPointer, LocalPlayer); ///<summary>Sets the tint color and opacity scale for this widget</summary> public void SetTintColorAndOpacity(LinearColor NewTintColorAndOpacity) => WidgetComponent_methods.SetTintColorAndOpacity_method.Invoke(ObjPointer, NewTintColorAndOpacity); ///<summary>Sets the widget to use directly.</summary> ///<remarks> ///This function will keep track of the widget till the next time it's called /// with either a newer widget or a nullptr ///</remarks> public void SetWidget(UserWidget Widget) => WidgetComponent_methods.SetWidget_method.Invoke(ObjPointer, Widget); //TODO: enum EWidgetSpace Space //TODO: enum EWidgetTimingPolicy TimingPolicy ///<summary>The class of User Widget to create and display an instance of</summary> public unsafe SubclassOf<UserWidget> WidgetClass { get {return WidgetComponent_ptr->WidgetClass;} set {WidgetComponent_ptr->WidgetClass = value;} } ///<summary>The size of the displayed quad.</summary> public unsafe IntPoint DrawSize { get {return WidgetComponent_ptr->DrawSize;} set {WidgetComponent_ptr->DrawSize = value;} } public bool bManuallyRedraw { get {return Main.GetGetBoolPropertyByName(this, "bManuallyRedraw"); } set {Main.SetGetBoolPropertyByName(this, "bManuallyRedraw", value); } } public bool bRedrawRequested { get {return Main.GetGetBoolPropertyByName(this, "bRedrawRequested"); } set {Main.SetGetBoolPropertyByName(this, "bRedrawRequested", value); } } ///<summary>The time in between draws, if 0 - we would redraw every frame.</summary> ///<remarks> ///If 1, we would redraw every second. ///This will work with bManuallyRedraw as well. So you can say, manually redraw, but only redraw at this ///maximum rate. ///</remarks> public unsafe float RedrawTime { get {return WidgetComponent_ptr->RedrawTime;} set {WidgetComponent_ptr->RedrawTime = value;} } ///<summary> ///The actual draw size, this changes based on DrawSize - or the desired size of the widget if ///bDrawAtDesiredSize is true. ///</summary> public unsafe IntPoint CurrentDrawSize { get {return WidgetComponent_ptr->CurrentDrawSize;} set {WidgetComponent_ptr->CurrentDrawSize = value;} } public bool bDrawAtDesiredSize { get {return Main.GetGetBoolPropertyByName(this, "bDrawAtDesiredSize"); } set {Main.SetGetBoolPropertyByName(this, "bDrawAtDesiredSize", value); } } ///<summary>The Alignment/Pivot point that the widget is placed at relative to the position.</summary> public unsafe Vector2D Pivot { get {return WidgetComponent_ptr->Pivot;} set {WidgetComponent_ptr->Pivot = value;} } public bool bReceiveHardwareInput { get {return Main.GetGetBoolPropertyByName(this, "bReceiveHardwareInput"); } set {Main.SetGetBoolPropertyByName(this, "bReceiveHardwareInput", value); } } public bool bWindowFocusable { get {return Main.GetGetBoolPropertyByName(this, "bWindowFocusable"); } set {Main.SetGetBoolPropertyByName(this, "bWindowFocusable", value); } } public bool bApplyGammaCorrection { get {return Main.GetGetBoolPropertyByName(this, "bApplyGammaCorrection"); } set {Main.SetGetBoolPropertyByName(this, "bApplyGammaCorrection", value); } } ///<summary> ///The owner player for a widget component, if this widget is drawn on the screen, this controls ///what player's screen it appears on for split screen, if not set, users player 0. ///</summary> public unsafe LocalPlayer OwnerPlayer { get {return WidgetComponent_ptr->OwnerPlayer;} set {WidgetComponent_ptr->OwnerPlayer = value;} } ///<summary>The background color of the component</summary> public unsafe LinearColor BackgroundColor { get {return WidgetComponent_ptr->BackgroundColor;} set {WidgetComponent_ptr->BackgroundColor = value;} } ///<summary>Tint color and opacity for this component</summary> public unsafe LinearColor TintColorAndOpacity { get {return WidgetComponent_ptr->TintColorAndOpacity;} set {WidgetComponent_ptr->TintColorAndOpacity = value;} } ///<summary>Sets the amount of opacity from the widget's UI texture to use when rendering the translucent or masked UI to the viewport (0.0-1.0)</summary> public unsafe float OpacityFromTexture { get {return WidgetComponent_ptr->OpacityFromTexture;} set {WidgetComponent_ptr->OpacityFromTexture = value;} } //TODO: enum EWidgetBlendMode BlendMode public bool bIsTwoSided { get {return Main.GetGetBoolPropertyByName(this, "bIsTwoSided"); } set {Main.SetGetBoolPropertyByName(this, "bIsTwoSided", value); } } public bool TickWhenOffscreen { get {return Main.GetGetBoolPropertyByName(this, "TickWhenOffscreen"); } set {Main.SetGetBoolPropertyByName(this, "TickWhenOffscreen", value); } } ///<summary>The User Widget object displayed and managed by this component</summary> public unsafe UserWidget Widget { get {return WidgetComponent_ptr->Widget;} set {WidgetComponent_ptr->Widget = value;} } ///<summary>The body setup of the displayed quad</summary> public unsafe BodySetup BodySetup { get {return WidgetComponent_ptr->BodySetup;} set {WidgetComponent_ptr->BodySetup = value;} } ///<summary>The material instance for translucent widget components</summary> public unsafe MaterialInterface TranslucentMaterial { get {return WidgetComponent_ptr->TranslucentMaterial;} set {WidgetComponent_ptr->TranslucentMaterial = value;} } ///<summary>The material instance for translucent, one-sided widget components</summary> public unsafe MaterialInterface TranslucentMaterial_OneSided { get {return WidgetComponent_ptr->TranslucentMaterial_OneSided;} set {WidgetComponent_ptr->TranslucentMaterial_OneSided = value;} } ///<summary>The material instance for opaque widget components</summary> public unsafe MaterialInterface OpaqueMaterial { get {return WidgetComponent_ptr->OpaqueMaterial;} set {WidgetComponent_ptr->OpaqueMaterial = value;} } ///<summary>The material instance for opaque, one-sided widget components</summary> public unsafe MaterialInterface OpaqueMaterial_OneSided { get {return WidgetComponent_ptr->OpaqueMaterial_OneSided;} set {WidgetComponent_ptr->OpaqueMaterial_OneSided = value;} } ///<summary>The material instance for masked widget components.</summary> public unsafe MaterialInterface MaskedMaterial { get {return WidgetComponent_ptr->MaskedMaterial;} set {WidgetComponent_ptr->MaskedMaterial = value;} } ///<summary>The material instance for masked, one-sided widget components.</summary> public unsafe MaterialInterface MaskedMaterial_OneSided { get {return WidgetComponent_ptr->MaskedMaterial_OneSided;} set {WidgetComponent_ptr->MaskedMaterial_OneSided = value;} } ///<summary>The target to which the user widget is rendered</summary> public unsafe TextureRenderTarget2D RenderTarget { get {return WidgetComponent_ptr->RenderTarget;} set {WidgetComponent_ptr->RenderTarget = value;} } ///<summary>The dynamic instance of the material that the render target is attached to</summary> public unsafe MaterialInstanceDynamic MaterialInstance { get {return WidgetComponent_ptr->MaterialInstance;} set {WidgetComponent_ptr->MaterialInstance = value;} } public bool bAddedToScreen { get {return Main.GetGetBoolPropertyByName(this, "bAddedToScreen"); } set {Main.SetGetBoolPropertyByName(this, "bAddedToScreen", value); } } public bool bEditTimeUsable { get {return Main.GetGetBoolPropertyByName(this, "bEditTimeUsable"); } set {Main.SetGetBoolPropertyByName(this, "bEditTimeUsable", value); } } ///<summary>Layer Name the widget will live on</summary> public unsafe Name SharedLayerName { get {return WidgetComponent_ptr->SharedLayerName;} set {WidgetComponent_ptr->SharedLayerName = value;} } ///<summary>ZOrder the layer will be created on, note this only matters on the first time a new layer is created, subsequent additions to the same layer will use the initially defined ZOrder</summary> public unsafe int LayerZOrder { get {return WidgetComponent_ptr->LayerZOrder;} set {WidgetComponent_ptr->LayerZOrder = value;} } //TODO: enum EWidgetGeometryMode GeometryMode ///<summary>Curvature of a cylindrical widget in degrees.</summary> public unsafe float CylinderArcAngle { get {return WidgetComponent_ptr->CylinderArcAngle;} set {WidgetComponent_ptr->CylinderArcAngle = value;} } static WidgetComponent() { StaticClass = Main.GetClass("WidgetComponent"); } internal unsafe WidgetComponent_fields* WidgetComponent_ptr => (WidgetComponent_fields*) ObjPointer.ToPointer(); ///<summary>Convert from IntPtr to UObject</summary> public static implicit operator WidgetComponent(IntPtr p) => UObject.Make<WidgetComponent>(p); ///<summary>Get UE4 Class</summary> public static Class StaticClass {get; private set;} ///<summary>Get UE4 Default Object for this Class</summary> public static WidgetComponent DefaultObject => Main.GetDefaultObject(StaticClass); ///<summary>Spawn an object of this class</summary> public static WidgetComponent New(UObject obj = null, Name name = new Name()) => Main.NewObject(StaticClass, obj, name); } }
52.94717
208
0.675861
[ "MIT" ]
UE4DotNet/Plugin
DotNet/DotNet/UE4/Generated/UMG/WidgetComponent.cs
14,031
C#
using System; using System.IO; using System.Windows.Forms; namespace apBiblioteca { public enum Situacao { navegando, incluindo, pesquisando, editando, excluindo } class VetorDados<Registro> : IVetorDados<Registro> where Registro : IComparable<Registro>, IRegistro, new() { Registro[] dados; int qtosDados; int posicaoAtual; Situacao situacaoAtual; // atributo protegido que armazena a situação atual /*****************************************************************************************************/ public VetorDados(int tamanhoMaximo) { dados = new Registro[tamanhoMaximo]; // a aplicação define o tamanho físico do vetor qtosDados = 0; // nenhuma posição usada ainda no vetor PosicaoAtual = -1; // não está posicionada em nenhum lugar do vetor situacaoAtual = Situacao.navegando; } public void GravacaoEmDisco(string nomeArquivo) { var arqDados = new StreamWriter(nomeArquivo); for (int i = 0; i < qtosDados; i++) { arqDados.WriteLine(dados[i].FormatoDeArquivo()); } arqDados.Close(); } public Registro ValorDe(int posicao) { if (posicao < 0 || posicao >= qtosDados) // fora do intervalo válido dos índices { throw new Exception("Acesso a posição inválida de armazenamento de dados"); } return dados[posicao]; } public void Incluir(Registro novo) // inclui um novo registro de funcionário no final do vetor { if (qtosDados < dados.Length) // não atingiu o tamanho físico do vetor { PosicaoAtual = qtosDados; dados[qtosDados] = novo; qtosDados++; } else { throw new Exception("Espaço de armazenamento insuficente!"); } } public void Incluir(Registro novoValor, int posicaoDeInclusao) { if (qtosDados >= dados.Length) { throw new Exception("Espaço de armazenamento insuficente!"); } for (int indice = qtosDados; indice > posicaoDeInclusao; indice--) { dados[indice] = dados[indice - 1]; } dados[posicaoDeInclusao] = novoValor; qtosDados++; } public void Ordenar() { for (int lento = 0; lento < qtosDados - 1; lento++) { for (int rapido = lento + 1; rapido < qtosDados; rapido++) { if (dados[lento].CompareTo(dados[rapido]) > 0) { Registro auxiliar = dados[lento]; dados[lento] = dados[rapido]; dados[rapido] = auxiliar; } } } } public void Excluir(int posicao) { if (posicao < 0 || posicao > qtosDados - 1) { throw new Exception("Índice fora dos limites!"); } for (int indice = posicao; indice < qtosDados; indice++) { dados[indice] = dados[indice + 1]; } qtosDados--; if (posicaoAtual >= qtosDados) { posicaoAtual = qtosDados - 1; // reposiocna o índice do registro atualmente visitado para // ficar na posição final em uso do vetor } } public bool ExisteNaoOrdenado(Registro registroProcurado, out int ondeEsta) { bool achou = false; ondeEsta = 0; while (!achou && ondeEsta < qtosDados) { if (dados[ondeEsta].CompareTo(registroProcurado) == 0) { achou = true; } else { ondeEsta++; } } return achou; } public bool ExisteSequencialOrdenado(Registro registroProcurado, out int onde) { bool fim, achou; onde = 0; // inicializa variáveis de controle da pesquisa achou = false; fim = false; while (!achou && !fim) // not (achou or fim) // De Morgan { if (onde >= qtosDados) // condição i { fim = true; } else { if (dados[onde].CompareTo(registroProcurado) == 0) { achou = true; // condição ii } else { if (dados[onde].CompareTo(registroProcurado) > 0) { fim = true; // condição iii } else { onde++; // como nenhuma das condições foi // satisfeita, acessa o elemento // seguinte no vetor. } } } } return achou; } public bool Existe(Registro registroProcurado, out int meio) { meio = 0; int inicio = 0; int fim = qtosDados - 1; bool achou = false; while (!achou && inicio <= fim) { meio = (inicio + fim) / 2; if (dados[meio].CompareTo(registroProcurado) == 0) { achou = true; } else { if (registroProcurado.CompareTo(dados[meio]) < 0) { fim = meio - 1; } else { inicio = meio + 1; } } } if (!achou) // quando o valor procurado náo existe, a posi;áo onde ele deveria estar { meio = inicio; // num vetor ordenado, é dada pelo último valor da varável inicio. Assim, // neste algoritmo, quando náo se acha o valor procurado, o parâmetro meio // retorna com o índica da posiçáo onde o valor procurado deveria estar. // Assim, se desejarmos incluir o valor náo encontrado, basta usar esse // parâmertro onde como índice de inclusáo, e o vetor continuará ordenado // com o novo valor recém-incluído nessa posição } return achou; } public void PosicionarNoPrimeiro() { if (!EstaVazio) { posicaoAtual = 0; // primeira posição do vetor em uso } else { posicaoAtual = -1; // indica antes do vetor vazio } } public void PosicionarNoUltimo() { if (!EstaVazio) { posicaoAtual = qtosDados - 1; // última posição usada do vetor } else { posicaoAtual = -1; // indica antes do vetor vazio } } public void AvancarPosicao() { if (posicaoAtual < qtosDados - 1) { posicaoAtual++; } } public void RetrocederPosicao() { if (posicaoAtual > 0) { posicaoAtual--; } } public void ExibirDados() { Console.Clear(); for (int i = 0; i < qtosDados; i++) { Console.WriteLine(dados[i].ToString()); } } public void ExibirDados(ListBox lista) { lista.Items.Clear(); for (int i = 0; i < qtosDados; i++) { lista.Items.Add(dados[i].ToString()); } } public void ExibirDados(ComboBox lista) { lista.Items.Clear(); for (int i = 0; i < qtosDados; i++) { lista.Items.Add(dados[i].ToString()); } } public void ExibirDados(TextBox lista) { lista.Clear(); lista.Multiline = true; for (int i = 0; i < qtosDados; i++) { lista.AppendText(dados[i].ToString() + Environment.NewLine); } } public void ExibirDados(DataGridView grade) { if (qtosDados > 0) { grade.RowCount = qtosDados; for (int indice = 0; indice < qtosDados; indice++) { grade[0, indice].Value = dados[indice].ToString(); } } } public void LerDados(string nomeArquivo) { if (!File.Exists(nomeArquivo)) { var f = File.CreateText(nomeArquivo); f.Close(); } qtosDados = 0; var arquivo = new StreamReader(nomeArquivo); while (!arquivo.EndOfStream) { Registro dadoLido = new Registro(); dadoLido.LerRegistro(arquivo); Incluir(dadoLido); } arquivo.Close(); } public void GravarDados(string nomeArquivo) { var arquivo = new StreamWriter(nomeArquivo); for (int indice = 0; indice < qtosDados; indice++) { arquivo.WriteLine(dados[indice].FormatoDeArquivo()); } arquivo.Close(); } public bool EstaNoInicio { get => posicaoAtual <= 0; // primeiro índice } public bool EstaNoFim { get => posicaoAtual >= qtosDados - 1; // último índice } // propriedade para acessar situacaoAtual para consulta e ajuste public Situacao SituacaoAtual { get => situacaoAtual; set => situacaoAtual = value; } public bool EstaVazio // permite à aplicação saber se o vetor dados está vazio { get => qtosDados <= 0; // se qtosDados <= 0, retorna true } public int PosicaoAtual { get => posicaoAtual; set { if (this.EstaVazio) { posicaoAtual = 0; } else if (value >= -1 && value < qtosDados) { posicaoAtual = value; } } } public int Tamanho { get => qtosDados; } public Registro this[int indice] { get { if (indice < 0 || indice >= qtosDados) { throw new IndexOutOfRangeException("Posição inválido!"); } return dados[indice]; } set { if (indice < 0 || indice >= qtosDados) { throw new IndexOutOfRangeException("Posição inválido!"); } dados[indice] = value; } } } }
29.84264
111
0.427879
[ "MIT" ]
FabricioOnofre/SistemaDeBiblioteca
20130_Projeto3TP1/VetorDados.cs
11,829
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the storagegateway-2013-06-30.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.StorageGateway.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.StorageGateway.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for UpdateGatewayInformation operation /// </summary> public class UpdateGatewayInformationResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { UpdateGatewayInformationResponse response = new UpdateGatewayInformationResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("GatewayARN", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.GatewayARN = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("GatewayName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.GatewayName = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerError")) { return InternalServerErrorExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidGatewayRequestException")) { return InvalidGatewayRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonStorageGatewayException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static UpdateGatewayInformationResponseUnmarshaller _instance = new UpdateGatewayInformationResponseUnmarshaller(); internal static UpdateGatewayInformationResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UpdateGatewayInformationResponseUnmarshaller Instance { get { return _instance; } } } }
39.9
198
0.631161
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/StorageGateway/Generated/Model/Internal/MarshallTransformations/UpdateGatewayInformationResponseUnmarshaller.cs
4,788
C#
using Newtonsoft.Json; using UnityEngine; public abstract class Config <T> where T : Config <T> { [JsonProperty("self")] public string Self { get; private set; } public static T LoadFromResources(string path) { var asset = Resources.Load<TextAsset>(path); if (asset == null) { Debug.LogError("No config named " + path + " in resources"); return null; } T config = JsonConvert.DeserializeObject<T>(asset.text); config.Self = path; return config; } }
28.421053
72
0.603704
[ "MIT" ]
mefist0fel/Astral-Empire
AstralEmpireProject/Assets/Sources/Utils/Config.cs
542
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Outputs { [OutputType] public sealed class WebAclRuleStatementOrStatementStatementAndStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchMethod { [OutputConstructor] private WebAclRuleStatementOrStatementStatementAndStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchMethod() { } } }
33.545455
155
0.785908
[ "ECL-2.0", "Apache-2.0" ]
Otanikotani/pulumi-aws
sdk/dotnet/WafV2/Outputs/WebAclRuleStatementOrStatementStatementAndStatementStatementOrStatementStatementRegexPatternSetReferenceStatementFieldToMatchMethod.cs
738
C#
using System; using System.Collections.Generic; using System.Text; namespace UpcomingMoviesMob.Models { public class TrendingRoot { public int page { get; set; } public List<TrendingItem> results { get; set; } public int total_Pages { get; set; } public int total_results { get; set; } } }
22.4
55
0.64881
[ "MIT" ]
catsbyy/movies-are-coming-android
UpcomingMoviesMob/Models/TrendingRoot.cs
338
C#
using System; using System.Collections.Generic; namespace HashSet { class StartUp { static void Main(string[] args) { } } }
12.461538
39
0.567901
[ "MIT" ]
NaskoVasilev/Data-Structures
Hash Tables - Sets and Dictionaries/HashSet/HashSet/StartUp.cs
164
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using AnaLight.Containers; namespace AnaLight.Commands { public class SpectraListCommand : ICommand { public delegate void HandlerDelegate(List<BasicSpectraContainer> spectra); private HandlerDelegate Handler { get; } public SpectraListCommand(HandlerDelegate handler) { Handler = handler; } public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { List<BasicSpectraContainer> items = (List<BasicSpectraContainer>)parameter; Handler?.Invoke(items); } } }
23.555556
87
0.659198
[ "MIT" ]
jmnich/AnaLight
Commands/SpectraListCommand.cs
850
C#
using System; using System.Collections.Generic; using System.Text; namespace Mossharbor.AzureWorkArounds.ServiceBus { using System.Xml.Serialization; [XmlRoot(ElementName = "Filter", DataType = "FalseFilter")] public class FalseFilter : SqlFilter { internal readonly static FalseFilter Default = new FalseFilter(); public FalseFilter() : base("1=0") { } } }
20.75
73
0.66988
[ "MIT" ]
Mossharbor/AzureWorkArounds.ServiceBus
Mossharbor.AzureWorkArounds.ServiceBus/FiltersActionsAndRules/FalseFilter.cs
417
C#
// Zeron - Scheduled Task Application for Windows OS // Copyright (c) 2019 Jiowcl. All rights reserved. using System.Security.Cryptography; using System.Text; namespace Zeron.ZCore.Utils { /// <summary> /// EncryptionProvider /// </summary> public static class EncryptionProvider { // Crypt Password hash. private const string m_CryptPasswordHash = "yyFDdat!@"; // Crypt Salt key. private const string m_CryptSaltKey = "YRjo1*9!"; // Crypt IV key. private const string m_CryptIVKey = "cdTeAV#$^YiuDamK"; /// <summary> /// Encrypt /// </summary> /// <param name="plainText"></param> /// <param name="iv"></param> /// <returns>Returns string.</returns> public static string Encrypt(string? plainText, string? iv = "") { if (plainText == null || plainText.Length == 0) { return ""; } if (iv == null || iv.Length == 0) { iv = m_CryptIVKey; } byte[] cipherTextBytes; byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); byte[] keyBytes = new Rfc2898DeriveBytes(m_CryptPasswordHash, Encoding.ASCII.GetBytes(m_CryptSaltKey)).GetBytes(256 / 8); using (Aes aesProvider = Aes.Create()) { ICryptoTransform encryptor = aesProvider.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(iv)); using (MemoryStream memoryStream = new()) { using (CryptoStream cryptoStream = new(memoryStream, encryptor, CryptoStreamMode.Write)) { cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); cipherTextBytes = memoryStream.ToArray(); } } } return Convert.ToBase64String(cipherTextBytes); } /// <summary> /// Decrypt /// </summary> /// <param name="cipherText"></param> /// <param name="iv"></param> /// <returns>Returns string.</returns> public static string Decrypt(string? cipherText, string? iv = "") { if (cipherText == null || cipherText.Length == 0) { return ""; } if (iv == null || iv.Length == 0) { iv = m_CryptIVKey; } string plainText; byte[] cipherTextBytes = Convert.FromBase64String(cipherText); byte[] keyBytes = new Rfc2898DeriveBytes(m_CryptPasswordHash, Encoding.ASCII.GetBytes(m_CryptSaltKey)).GetBytes(256 / 8); using (Aes aesProvider = Aes.Create()) { ICryptoTransform decryptor = aesProvider.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(iv)); using (MemoryStream memoryStream = new(cipherTextBytes)) { using (CryptoStream cryptoStream = new(memoryStream, decryptor, CryptoStreamMode.Read)) { using (StreamReader streamReader = new(cryptoStream)) { plainText = streamReader.ReadToEnd(); } } } } return plainText; } } }
33.4
133
0.516111
[ "MIT" ]
inwazy/Zeron
Zeron/ZCore/Utils/EncryptionProvider.cs
3,509
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenQA.Selenium; using Riganti.Selenium.Core.Factories; namespace Riganti.Selenium.Core.Drivers.Implementation { public class EdgeDevWebBrowser : DevWebBrowserBase { public new LocalWebBrowserFactory Factory => (LocalWebBrowserFactory)base.Factory; public EdgeDevWebBrowser(IWebBrowserFactory factory) : base(factory) { } protected override IWebDriver CreateDriver() { return EdgeHelpers.CreateEdgeDriver(Factory); } } }
25.08
90
0.717703
[ "Apache-2.0" ]
JTOne123/selenium-utils
src/Core/Riganti.Selenium.Core/Drivers/Implementation/EdgeDevWebBrowser.cs
629
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.CertificateManager")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Certificate Manager. AWS Certificate Manager (ACM) is an AWS service that makes it easier for you to deploy secure SSL based websites and applications on the AWS platform.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.3.5.38")]
48.03125
255
0.752765
[ "Apache-2.0" ]
damtur/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/CertificateManager/Properties/AssemblyInfo.cs
1,537
C#
using System; using System.Globalization; using System.Windows.Forms; namespace Opulos.Core.UI { public class TimePicker : MaskedTextBox<DateTime> { private String dateTimeFormat = null; public ClockControl ClockMenu = null; private ToolStripDropDownAttacher attacher = null; ///<summary> ///<para>Creates a time picker with the specified number of millisecond digits. The base format ///will be HH:mm:ss when the use24HourClock parameter is true, otherwise the base format ///will be hh:mm:ss. The milliseconds are appended at the end, e.g. HH:mm:ss.ffff ///</para> ///<para>Call the MimicDateTimePicker() to mimic the same style of input.</para> ///<para>Use the Value property to access the current DateTime value.</para> ///<para>Use the ValueChanged event to listen for DateTime changes.</para> ///<para>Use the TimeFormat and Mask in conjuction to change the format.</para> ///<para>The Arrays MinValues, MaxValues, PageUpDownDeltas and ByValues must ///contain at least the number of tokens as the TimeFormat contains.</para> ///</summary> ///<param name="addUpDownSpinner">An option to display up-down buttons.</param> ///<param name="immediateValueChange">An option if changing the clock menu value requires clicking the OK button, or if the change is instant.</param> ///<param name="numMilliDigits">The number of milliseconds to show.</param> ///<param name="showClockMenu">An option to show a clock menu when this control gets the focus or is clicked.</param> ///<param name="use24HourClock">An option to show hours 0 to 23 or 1 to 12.</param> public TimePicker(int numMilliDigits = 3, bool use24HourClock = true, bool addUpDownSpinner = true, bool showClockMenu = true, bool immediateValueChange = true) : base(addUpDownSpinner) { //Using 9s produces more natural usability than 0s. String mask = "99:99:99"; String timeFormat = (use24HourClock ? "HH:mm:ss" : "hh:mm:ss"); int maxValue = 1; if (numMilliDigits > 0) { mask += "." + new String('9', numMilliDigits); timeFormat += "." + new String('f', numMilliDigits); for (int i = 0; i < numMilliDigits; i++) maxValue *= 10; } dateTimeFormat = timeFormat; this.Mask = mask; if (use24HourClock) { Tokens[0].MaxValue = 24; } else { Tokens[0].MinValue = 1; Tokens[0].MaxValue = 13; } Tokens[2].MaxValue = 60; Tokens[4].MaxValue = 60; //-- Tokens[0].BigIncrement = 4; Tokens[2].BigIncrement = 10; Tokens[4].BigIncrement = 10; //-- MimicDateTimePicker(); Value = DateTime.Now; ClockMenu = new ClockControl(); //false, false, false); if (showClockMenu) attacher = new ToolStripDropDownAttacher(ClockMenu, this); ClockMenu.ButtonClicked += ClockMenu_ButtonClicked; this.ValueChanged += delegate { ClockMenu.Value = this.Value; }; DateTime origValue = DateTime.MinValue; ClockMenu.VisibleChanged += delegate { if (ClockMenu.Visible) { origValue = this.Value; ClockMenu.Value = this.Value; } }; ClockMenu.Closed += (o, e) => { // escape key is used if (e.CloseReason == ToolStripDropDownCloseReason.Keyboard) { this.Value = origValue; } else { this.Value = ClockMenu.Value; } }; ClockMenu.ValueChanged += delegate { if (immediateValueChange) this.Value = ClockMenu.Value; }; attacher.MenuShowing += delegate { Token t = this.TokenAt(this.SelectionStart); if (t.SeqNo == 0) ClockMenu.ClockFace = ClockFace.Hours; else if (t.SeqNo == 2) ClockMenu.ClockFace = ClockFace.Minutes; }; } void ClockMenu_ButtonClicked(object sender, EventArgs e) { // if Cancel button, then send Keyboard, which is used to indicate keyboard escape ToolStripDropDownCloseReason r = (sender == ClockMenu.ClockButtonOK ? ToolStripDropDownCloseReason.ItemClicked : ToolStripDropDownCloseReason.Keyboard); attacher.CloseMenu(r); } public String DateTimeFormat { get { return dateTimeFormat; } set { dateTimeFormat = value; } } public override DateTime TextToValue(String text) { DateTime d = DateTime.MinValue; DateTime.TryParseExact(text, dateTimeFormat, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out d); return d; } public override String ValueToText(DateTime value) { return value.ToString(dateTimeFormat); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { if (ClockMenu != null) ClockMenu.Dispose(); ClockMenu = null; } } } }
32.100719
189
0.707978
[ "MIT" ]
Arno1235Official/JugaAgenda
Libraries/MaskedTextBox/src/TimePicker.cs
4,462
C#
namespace Forum.Data.Models { using System.Collections.Generic; using Forum.Data.Common.Models; public class Category : BaseDeletableModel<int> { public Category() { this.Posts = new HashSet<Post>(); } public string Name { get; set; } public string Title { get; set; } public string Description { get; set; } public string ImgUrl { get; set; } public virtual ICollection<Post> Posts { get; set; } } }
20.2
60
0.580198
[ "MIT" ]
EvgeniTrifonov/Forum
Data/Forum.Data.Models/Category.cs
507
C#
using EasyLOB.Identity.Data.Resources; using EasyLOB.Data; using EasyLOB.Library; using EasyLOB.Resources; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace EasyLOB.Identity.Data { public partial class RoleViewModel : ZViewBase<RoleViewModel, Role> { #region Properties //[Display(Name = "PropertyId", ResourceType = typeof(RoleResources))] ////[Key] //[Required] //[StringLength(128)] //public virtual string Id { get; set; } [Display(Name = "PropertyName", ResourceType = typeof(RoleResources))] [Required] [StringLength(256)] public virtual string Name { get; set; } //[Display(Name = "PropertyDiscriminator", ResourceType = typeof(RoleResources))] //[Required] //[StringLength(128)] //public virtual string Discriminator { get; set; } #endregion Properties #region Methods public RoleViewModel() { OnConstructor(); } public RoleViewModel(IZDataBase dataModel) { FromData(dataModel); } #endregion Methods } }
26.541667
90
0.580848
[ "MIT" ]
EasyLOB/EasyLOB-MyLOB-3
MyLOB.Mvc/Models/Identity/Role/RoleViewModel.cs
1,276
C#
using System; using System.Collections.Generic; namespace LazyECS { public enum GroupType { Any, All } public enum EventType { Added, Set, Removed, All } public interface IGroup { GroupType GroupType { get; } HashSet<Entity.Entity> Entities { get; } HashSet<Type> Filters { get; } EventType EventType { get; } event Group.OnEntityUpdate OnEntityUpdateEvent; void EntitySet(Entity.Entity entity, Type component); void EntityDestroyed(Entity.Entity entity); void ComponentAddedToEntity(Entity.Entity entity, Type component); void ComponentRemovedFromEntity(Entity.Entity entity, Type component); } }
19.058824
72
0.731481
[ "MIT" ]
tatelax/LazyECS
Runtime/IGroup.cs
650
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Reflection; using Microsoft.CodeAnalysis; namespace Analyzer.Utilities.Lightup { internal static class NullableSyntaxAnnotationEx { public static SyntaxAnnotation? Oblivious { get; } public static SyntaxAnnotation? AnnotatedOrNotAnnotated { get; } static NullableSyntaxAnnotationEx() { var nullableSyntaxAnnotation = typeof(Workspace).Assembly.GetType("Microsoft.CodeAnalysis.CodeGeneration.NullableSyntaxAnnotation", throwOnError: false); if (nullableSyntaxAnnotation is not null) { Oblivious = (SyntaxAnnotation?)nullableSyntaxAnnotation.GetField(nameof(Oblivious), BindingFlags.Static | BindingFlags.Public)?.GetValue(null); AnnotatedOrNotAnnotated = (SyntaxAnnotation?)nullableSyntaxAnnotation.GetField(nameof(AnnotatedOrNotAnnotated), BindingFlags.Static | BindingFlags.Public)?.GetValue(null); } } } }
45.916667
187
0.725045
[ "MIT" ]
AndreasVolkmann/roslyn-analyzers
src/NetAnalyzers/Core/NullableSyntaxAnnotationEx.cs
1,104
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Web; using System.Xml; using Umbraco.Core; using Umbraco.Core.IO; using umbraco.BasePages; using umbraco.BusinessLogic; using umbraco.interfaces; using System.Linq; namespace Umbraco.Web.UI { /// <summary> /// This is used to replace the old umbraco.presentation.create.dialogHandler_temp class which is used /// to handle sections create/delete actions. /// </summary> /// <remarks> /// We need to overhaul how all of this is handled which is why this is a legacy class /// http://issues.umbraco.org/issue/U4-1373 /// </remarks> public static class LegacyDialogHandler { private enum Operation { Create, Delete } private const string ContextKeyCreate = "LegacyDialogHandler-Create-"; private const string ContextKeyDelete = "LegacyDialogHandler-Delete-"; /// <summary> /// Gets the ITask for the operation for the node Type /// </summary> /// <param name="umbracoUser"></param> /// <param name="op"></param> /// <param name="nodeType"></param> /// <param name="httpContext"></param> /// <returns> /// Returns the ITask if one is found and can be made, otherwise null /// </returns> /// <remarks> /// This will first check if we've already created the ITask in the current Http request /// </remarks> private static ITask GetTaskForOperation(HttpContextBase httpContext, User umbracoUser, Operation op, string nodeType) { if (httpContext == null) throw new ArgumentNullException("httpContext"); if (umbracoUser == null) throw new ArgumentNullException("umbracoUser"); if (nodeType == null) throw new ArgumentNullException("nodeType"); var ctxKey = op == Operation.Create ? ContextKeyCreate : ContextKeyDelete; //check contextual cache if (httpContext.Items[ctxKey] != null) { return (ITask) httpContext.Items[ctxKey]; } var operationNode = op == Operation.Create ? "create" : "delete"; var createDef = GetXmlDoc(); var def = createDef.SelectSingleNode("//nodeType [@alias = '" + nodeType + "']"); if (def == null) { return null; } var del = def.SelectSingleNode("./tasks/" + operationNode); if (del == null) { return null; } if (!del.Attributes.HasAttribute("assembly")) { return null; } var taskAssembly = del.AttributeValue<string>("assembly"); if (!del.Attributes.HasAttribute("type")) { return null; } var taskType = del.AttributeValue<string>("type"); var assembly = Assembly.LoadFrom(IOHelper.MapPath(SystemDirectories.Bin + "/" + taskAssembly + ".dll")); var type = assembly.GetType(taskAssembly + "." + taskType); var typeInstance = Activator.CreateInstance(type) as ITask; if (typeInstance == null) { return null; } //set the user/user id for the instance var dialogTask = typeInstance as LegacyDialogTask; if (dialogTask != null) { dialogTask.User = umbracoUser; } else { typeInstance.UserId = umbracoUser.Id; } //put in contextual cache httpContext.Items[ctxKey] = typeInstance; return typeInstance; } /// <summary> /// Checks if the user has access to launch the ITask that matches the node type based on the app assigned /// </summary> /// <param name="httpContext"></param> /// <param name="umbracoUser"></param> /// <param name="nodeType"></param> /// <returns></returns> /// <remarks> /// If the ITask doesn't implement LegacyDialogTask then we will return 'true' since we cannot validate /// the application assigned. /// /// TODO: Create an API to assign a nodeType to an app so developers can manually secure it /// </remarks> internal static bool UserHasCreateAccess(HttpContextBase httpContext, User umbracoUser, string nodeType) { var task = GetTaskForOperation(httpContext, umbracoUser, Operation.Create, nodeType); if (task == null) { //if no task was found it will use the default task and we cannot validate the application assigned so return true return true; } var dialogTask = task as LegacyDialogTask; if (dialogTask != null) { return dialogTask.ValidateUserForApplication(); } return true; } /// <summary> /// Checks if the user has access to launch the ITask that matches the node type based on the app assigned /// </summary> /// <param name="httpContext"></param> /// <param name="umbracoUser"></param> /// <param name="nodeType"></param> /// <returns></returns> /// <remarks> /// If the ITask doesn't implement LegacyDialogTask then we will return 'true' since we cannot validate /// the application assigned. /// /// TODO: Create an API to assign a nodeType to an app so developers can manually secure it /// </remarks> internal static bool UserHasDeleteAccess(HttpContextBase httpContext, User umbracoUser, string nodeType) { var task = GetTaskForOperation(httpContext, umbracoUser, Operation.Delete, nodeType); if (task == null) { //if no task was found it will use the default task and we cannot validate the application assigned so return true return true; } var dialogTask = task as LegacyDialogTask; if (dialogTask != null) { return dialogTask.ValidateUserForApplication(); } return true; } public static void Delete(HttpContextBase httpContext, User umbracoUser, string nodeType, int nodeId, string text) { var typeInstance = GetTaskForOperation(httpContext, umbracoUser, Operation.Delete, nodeType); if (typeInstance == null) throw new InvalidOperationException( string.Format("Could not task for operation {0} for node type {1}", Operation.Delete, nodeType)); typeInstance.ParentID = nodeId; typeInstance.Alias = text; typeInstance.Delete(); } public static string Create(HttpContextBase httpContext, User umbracoUser, string nodeType, int nodeId, string text, int typeId = 0) { var typeInstance = GetTaskForOperation(httpContext, umbracoUser, Operation.Create, nodeType); if (typeInstance == null) throw new InvalidOperationException( string.Format("Could not task for operation {0} for node type {1}", Operation.Create, nodeType)); typeInstance.TypeID = typeId; typeInstance.ParentID = nodeId; typeInstance.Alias = text; typeInstance.Save(); // check for returning url var returnUrlTask = typeInstance as ITaskReturnUrl; return returnUrlTask != null ? returnUrlTask.ReturnUrl : ""; } internal static string Create(HttpContextBase httpContext, User umbracoUser, string nodeType, int nodeId, string text, IDictionary<string, object> additionalValues, int typeId = 0) { var typeInstance = GetTaskForOperation(httpContext, umbracoUser, Operation.Create, nodeType); if (typeInstance == null) throw new InvalidOperationException( string.Format("Could not task for operation {0} for node type {1}", Operation.Create, nodeType)); typeInstance.TypeID = typeId; typeInstance.ParentID = nodeId; typeInstance.Alias = text; // check for returning url ITaskReturnUrl returnUrlTask = typeInstance as LegacyDialogTask; if (returnUrlTask != null) { // if castable to LegacyDialogTask: add in additionalValues ((LegacyDialogTask) returnUrlTask).AdditionalValues = additionalValues; } else { // otherwise cast to returnUrl interface returnUrlTask = typeInstance as ITaskReturnUrl; } typeInstance.Save(); return returnUrlTask != null ? returnUrlTask.ReturnUrl : ""; } private static XmlDocument GetXmlDoc() { // Load task settings var createDef = new XmlDocument(); using (var defReader = new XmlTextReader(IOHelper.MapPath(SystemFiles.CreateUiXml))) { createDef.Load(defReader); defReader.Close(); return createDef; } } } }
38.522088
188
0.573499
[ "MIT" ]
mariusz-sycz/UmbracoSEO
src/Umbraco.Web/UI/LegacyDialogHandler.cs
9,594
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Runtime.ExceptionServices; using Azure.Core; namespace Microsoft.Extensions.Azure { internal class ClientRegistration<TClient> { public string Name { get; set; } public object Version { get; set; } public bool RequiresTokenCredential { get; set; } private readonly Func<object, TokenCredential, TClient> _factory; private readonly object _cacheLock = new object(); private TClient _cachedClient; private ExceptionDispatchInfo _cachedException; public ClientRegistration(string name, Func<object, TokenCredential, TClient> factory) { Name = name; _factory = factory; } public TClient GetClient(object options, TokenCredential tokenCredential) { _cachedException?.Throw(); if (_cachedClient != null) { return _cachedClient; } lock (_cacheLock) { _cachedException?.Throw(); if (_cachedClient != null) { return _cachedClient; } if (RequiresTokenCredential && tokenCredential == null) { throw new InvalidOperationException("Client registration requires a TokenCredential. Configure it using UseCredential method."); } try { _cachedClient = _factory(options, tokenCredential); } catch (Exception e) { _cachedException = ExceptionDispatchInfo.Capture(e); throw; } return _cachedClient; } } } }
28.179104
148
0.54714
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/extensions/Microsoft.Extensions.Azure/src/Internal/ClientRegistration.cs
1,890
C#
using System.Text.Json.Serialization; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// AlipaySocialBaseIdpsourceSyncModel Data Structure. /// </summary> public class AlipaySocialBaseIdpsourceSyncModel : AlipayObject { /// <summary> /// 数据内容为json格式的字符串,要求数据内容所有字段平铺,不支持复杂数据结构,时间类型请统一使用unix毫秒时间戳。 /// </summary> [JsonPropertyName("data")] public string Data { get; set; } /// <summary> /// 能唯一标识一份外部数据的名称,确定后不可变更,不可重复 /// </summary> [JsonPropertyName("name")] public string Name { get; set; } } }
27.217391
70
0.619808
[ "MIT" ]
LuohuaRain/payment
src/Essensoft.AspNetCore.Payment.Alipay/Domain/AlipaySocialBaseIdpsourceSyncModel.cs
782
C#
namespace Application.UseCases.Transactions.Deposit; using System.ComponentModel.DataAnnotations; public sealed class DepositInput { [Required] public Guid AccountId { get; set; } [Required] public decimal Amount { get; set; } [Required] public string Currency { get; set; } = string.Empty; }
21.4
56
0.707165
[ "MIT" ]
MartsTech/D-Wallet
packages/api/src/Application/UseCases/Transactions/Deposit/DepositInput.cs
323
C#
/* Copyright (c) 2018 ExT (V.Sigalkin) */ using System; namespace extOSC { [Serializable] public struct OSCMidi { #region Public Vars public byte Channel; public byte Status; public byte Data1; public byte Data2; #endregion #region Public Methods public OSCMidi(byte channel, byte status, byte data1, byte data2) { Channel = channel; Status = status; Data1 = data1; Data2 = data2; } public override string ToString() { return string.Format("({0}, {1}, {2}, {3})", Channel, Status, Data1, Data2); } #endregion } }
18.25641
88
0.519663
[ "MIT" ]
TheBricktop/extOSC
Assets/extOSC/Scripts/OSCMidi.cs
714
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using WritingExample.Data; namespace WritingExample.Migrations { [DbContext(typeof(WritingInstrumentDbContext))] [Migration("20201129215256_Init")] partial class Init { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.10"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("TEXT"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("TEXT"); b.Property<string>("Name") .HasColumnType("TEXT") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasColumnType("TEXT") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("ClaimType") .HasColumnType("TEXT"); b.Property<string>("ClaimValue") .HasColumnType("TEXT"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => { b.Property<string>("Id") .HasColumnType("TEXT"); b.Property<int>("AccessFailedCount") .HasColumnType("INTEGER"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("TEXT"); b.Property<string>("Email") .HasColumnType("TEXT") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .HasColumnType("INTEGER"); b.Property<bool>("LockoutEnabled") .HasColumnType("INTEGER"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("TEXT"); b.Property<string>("NormalizedEmail") .HasColumnType("TEXT") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasColumnType("TEXT") .HasMaxLength(256); b.Property<string>("PasswordHash") .HasColumnType("TEXT"); b.Property<string>("PhoneNumber") .HasColumnType("TEXT"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("INTEGER"); b.Property<string>("SecurityStamp") .HasColumnType("TEXT"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("INTEGER"); b.Property<string>("UserName") .HasColumnType("TEXT") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("ClaimType") .HasColumnType("TEXT"); b.Property<string>("ClaimValue") .HasColumnType("TEXT"); b.Property<string>("UserId") .IsRequired() .HasColumnType("TEXT"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("TEXT") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasColumnType("TEXT") .HasMaxLength(128); b.Property<string>("ProviderDisplayName") .HasColumnType("TEXT"); b.Property<string>("UserId") .IsRequired() .HasColumnType("TEXT"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("TEXT"); b.Property<string>("RoleId") .HasColumnType("TEXT"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("TEXT"); b.Property<string>("LoginProvider") .HasColumnType("TEXT") .HasMaxLength(128); b.Property<string>("Name") .HasColumnType("TEXT") .HasMaxLength(128); b.Property<string>("Value") .HasColumnType("TEXT"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("WritingExample.Data.Crayon", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("HTMLColor") .HasColumnType("TEXT"); b.HasKey("Id"); b.ToTable("Crayons"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
35.136842
95
0.445376
[ "MIT" ]
PacktPublishing/Visual-Studio-2019-Tricks-and-Techniques
Chapter15/WritingInstruments/Migrations/20201129215256_Init.Designer.cs
10,016
C#
using Ryujinx.Graphics.Gpu.Memory; using System; namespace Ryujinx.Graphics.Vic { class StructUnpacker { private MemoryAccessor _vmm; private ulong _position; private ulong _buffer; private int _buffPos; public StructUnpacker(MemoryAccessor vmm, ulong position) { _vmm = vmm; _position = position; _buffPos = 64; } public int Read(int bits) { if ((uint)bits > 32) { throw new ArgumentOutOfRangeException(nameof(bits)); } int value = 0; while (bits > 0) { RefillBufferIfNeeded(); int readBits = bits; int maxReadBits = 64 - _buffPos; if (readBits > maxReadBits) { readBits = maxReadBits; } value <<= readBits; value |= (int)(_buffer >> _buffPos) & (int)(0xffffffff >> (32 - readBits)); _buffPos += readBits; bits -= readBits; } return value; } private void RefillBufferIfNeeded() { if (_buffPos >= 64) { _buffer = _vmm.ReadUInt64(_position); _position += 8; _buffPos = 0; } } } }
20.753623
91
0.445531
[ "MIT" ]
AidanXu/Ryujinx
Ryujinx.Graphics.Nvdec/Vic/StructUnpacker.cs
1,432
C#
using System; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; #pragma warning disable 1591 #pragma warning disable CA1401 // P/Invokes should not be visible #pragma warning disable CA2101 // Specify marshaling for P/Invoke string arguments #pragma warning disable IDE1006 // Naming style namespace OpenCvSharp.Internal { static partial class NativeMethods { [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern ExceptionStatus ml_Boost_getBoostType(IntPtr obj, out int returnValue); [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern ExceptionStatus ml_Boost_setBoostType(IntPtr obj, int val); [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern ExceptionStatus ml_Boost_getWeakCount(IntPtr obj, out int returnValue); [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern ExceptionStatus ml_Boost_setWeakCount(IntPtr obj, int val); [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern ExceptionStatus ml_Boost_getWeightTrimRate(IntPtr obj, out double returnValue); [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern ExceptionStatus ml_Boost_setWeightTrimRate(IntPtr obj, double val); [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern ExceptionStatus ml_Boost_create(out IntPtr returnValue); [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern ExceptionStatus ml_Ptr_Boost_delete(IntPtr obj); [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern ExceptionStatus ml_Ptr_Boost_get(IntPtr obj, out IntPtr returnValue); [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern ExceptionStatus ml_Boost_load([MarshalAs(UnmanagedType.LPStr)] string filePath, out IntPtr returnValue); [Pure, DllImport(DllExtern, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern ExceptionStatus ml_Boost_loadFromString([MarshalAs(UnmanagedType.LPStr)] string strModel, out IntPtr returnValue); } }
61.090909
143
0.769345
[ "Apache-2.0" ]
AvenSun/opencvsharp
src/OpenCvSharp/Internal/PInvoke/NativeMethods/ml/NativeMethods_ml_Boost.cs
2,690
C#
using System; using NUnit.Framework; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Agreement; using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Crypto.Encodings; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.Macs; using Org.BouncyCastle.Crypto.Modes; using Org.BouncyCastle.Crypto.Paddings; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Signers; using Org.BouncyCastle.Math; using Org.BouncyCastle.Math.EC; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Crypto.Tests { /// <remarks>Test for ECIES - Elliptic Curve Integrated Encryption Scheme</remarks> [TestFixture] public class EcIesTest : SimpleTest { public EcIesTest() { } public override string Name { get { return "ECIES"; } } private void StaticTest() { BigInteger n = new BigInteger("6277101735386680763835789423176059013767194773182842284081"); FpCurve curve = new FpCurve( new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16), // b n, BigInteger.One); ECDomainParameters parameters = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G n, BigInteger.One); ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( "ECDH", new BigInteger("651056770906015076056810763456358567190100156695615665659"), // d parameters); ECPublicKeyParameters pubKey = new ECPublicKeyParameters( "ECDH", curve.DecodePoint(Hex.Decode("0262b12d60690cdcf330babab6e69763b471f994dd702d16a5")), // Q parameters); AsymmetricCipherKeyPair p1 = new AsymmetricCipherKeyPair(pubKey, priKey); AsymmetricCipherKeyPair p2 = new AsymmetricCipherKeyPair(pubKey, priKey); // // stream test // IesEngine i1 = new IesEngine( new ECDHBasicAgreement(), new Kdf2BytesGenerator(new Sha1Digest()), new HMac(new Sha1Digest())); IesEngine i2 = new IesEngine( new ECDHBasicAgreement(), new Kdf2BytesGenerator(new Sha1Digest()), new HMac(new Sha1Digest())); byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 }; IesParameters p = new IesParameters(d, e, 64); i1.Init(true, p1.Private, p2.Public, p); i2.Init(false, p2.Private, p1.Public, p); byte[] message = Hex.Decode("1234567890abcdef"); byte[] out1 = i1.ProcessBlock(message, 0, message.Length); if (!AreEqual(out1, Hex.Decode("468d89877e8238802403ec4cb6b329faeccfa6f3a730f2cdb3c0a8e8"))) { Fail("stream cipher test failed on enc"); } byte[] out2 = i2.ProcessBlock(out1, 0, out1.Length); if (!AreEqual(out2, message)) { Fail("stream cipher test failed"); } // // twofish with CBC // BufferedBlockCipher c1 = new PaddedBufferedBlockCipher( new CbcBlockCipher(new TwofishEngine())); BufferedBlockCipher c2 = new PaddedBufferedBlockCipher( new CbcBlockCipher(new TwofishEngine())); i1 = new IesEngine( new ECDHBasicAgreement(), new Kdf2BytesGenerator(new Sha1Digest()), new HMac(new Sha1Digest()), c1); i2 = new IesEngine( new ECDHBasicAgreement(), new Kdf2BytesGenerator(new Sha1Digest()), new HMac(new Sha1Digest()), c2); d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 }; p = new IesWithCipherParameters(d, e, 64, 128); i1.Init(true, p1.Private, p2.Public, p); i2.Init(false, p2.Private, p1.Public, p); message = Hex.Decode("1234567890abcdef"); out1 = i1.ProcessBlock(message, 0, message.Length); if (!AreEqual(out1, Hex.Decode("b8a06ea5c2b9df28b58a0a90a734cde8c9c02903e5c220021fe4417410d1e53a32a71696"))) { Fail("twofish cipher test failed on enc"); } out2 = i2.ProcessBlock(out1, 0, out1.Length); if (!AreEqual(out2, message)) { Fail("twofish cipher test failed"); } } private void DoTest( AsymmetricCipherKeyPair p1, AsymmetricCipherKeyPair p2) { // // stream test // IesEngine i1 = new IesEngine( new ECDHBasicAgreement(), new Kdf2BytesGenerator(new Sha1Digest()), new HMac(new Sha1Digest())); IesEngine i2 = new IesEngine( new ECDHBasicAgreement(), new Kdf2BytesGenerator(new Sha1Digest()), new HMac(new Sha1Digest())); byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 }; IesParameters p = new IesParameters(d, e, 64); i1.Init(true, p1.Private, p2.Public, p); i2.Init(false, p2.Private, p1.Public, p); byte[] message = Hex.Decode("1234567890abcdef"); byte[] out1 = i1.ProcessBlock(message, 0, message.Length); byte[] out2 = i2.ProcessBlock(out1, 0, out1.Length); if (!AreEqual(out2, message)) { Fail("stream cipher test failed"); } // // twofish with CBC // BufferedBlockCipher c1 = new PaddedBufferedBlockCipher( new CbcBlockCipher(new TwofishEngine())); BufferedBlockCipher c2 = new PaddedBufferedBlockCipher( new CbcBlockCipher(new TwofishEngine())); i1 = new IesEngine( new ECDHBasicAgreement(), new Kdf2BytesGenerator(new Sha1Digest()), new HMac(new Sha1Digest()), c1); i2 = new IesEngine( new ECDHBasicAgreement(), new Kdf2BytesGenerator(new Sha1Digest()), new HMac(new Sha1Digest()), c2); d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 }; p = new IesWithCipherParameters(d, e, 64, 128); i1.Init(true, p1.Private, p2.Public, p); i2.Init(false, p2.Private, p1.Public, p); message = Hex.Decode("1234567890abcdef"); out1 = i1.ProcessBlock(message, 0, message.Length); out2 = i2.ProcessBlock(out1, 0, out1.Length); if (!AreEqual(out2, message)) { Fail("twofish cipher test failed"); } } public override void PerformTest() { StaticTest(); BigInteger n = new BigInteger("6277101735386680763835789423176059013767194773182842284081"); FpCurve curve = new FpCurve( new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16), // b n, BigInteger.One); ECDomainParameters parameters = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G n, BigInteger.One); ECKeyPairGenerator eGen = new ECKeyPairGenerator(); KeyGenerationParameters gParam = new ECKeyGenerationParameters(parameters, new SecureRandom()); eGen.Init(gParam); AsymmetricCipherKeyPair p1 = eGen.GenerateKeyPair(); AsymmetricCipherKeyPair p2 = eGen.GenerateKeyPair(); DoTest(p1, p2); } public static void MainOld( string[] args) { RunTest(new EcIesTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
35.731225
120
0.561394
[ "MIT" ]
TangoCS/BouncyCastle
crypto/test/src/crypto/test/ECIESTest.cs
9,040
C#
#nullable enable using System; using JetBrains.Annotations; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Prototypes; namespace Content.Shared.Utility { [UsedImplicitly] public static class EntityPrototypeHelpers { public static bool HasComponent<T>(this EntityPrototype prototype, IComponentFactory? componentFactory = null) where T : IComponent { return prototype.HasComponent(typeof(T), componentFactory); } public static bool HasComponent(this EntityPrototype prototype, Type component, IComponentFactory? componentFactory = null) { componentFactory ??= IoCManager.Resolve<IComponentFactory>(); var registration = componentFactory.GetRegistration(component); return prototype.Components.ContainsKey(registration.Name); } public static bool HasComponent<T>(string prototype, IPrototypeManager? prototypeManager = null, IComponentFactory? componentFactory = null) where T : IComponent { return HasComponent(prototype, typeof(T), prototypeManager, componentFactory); } public static bool HasComponent(string prototype, Type component, IPrototypeManager? prototypeManager = null, IComponentFactory? componentFactory = null) { prototypeManager ??= IoCManager.Resolve<IPrototypeManager>(); return prototypeManager.TryIndex(prototype, out EntityPrototype? proto) && proto!.HasComponent(component, componentFactory); } } }
38.875
169
0.716399
[ "MIT" ]
BingoJohnson/space-station-14
Content.Shared/Utility/EntityPrototypeHelpers.cs
1,557
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using CsSystem = System; using Fox; namespace Fox.Geo { public partial class GeoCheckModuleConditionBody : Fox.Geo.GeoTrapConditionBody { // PropertyInfo private static Fox.EntityInfo classInfo; public static new Fox.EntityInfo ClassInfo { get { return classInfo; } } public override Fox.EntityInfo GetClassEntityInfo() { return classInfo; } static GeoCheckModuleConditionBody() { classInfo = new Fox.EntityInfo("GeoCheckModuleConditionBody", new Fox.Geo.GeoTrapConditionBody(0, 0, 0).GetClassEntityInfo(), 0, "Trap", 0); } // Constructor public GeoCheckModuleConditionBody(ulong address, ushort idA, ushort idB) : base(address, idA, idB) { } public override void SetProperty(string propertyName, Fox.Value value) { switch(propertyName) { default: base.SetProperty(propertyName, value); return; } } public override void SetPropertyElement(string propertyName, ushort index, Fox.Value value) { switch(propertyName) { default: base.SetPropertyElement(propertyName, index, value); return; } } public override void SetPropertyElement(string propertyName, string key, Fox.Value value) { switch(propertyName) { default: base.SetPropertyElement(propertyName, key, value); return; } } } }
29.794521
152
0.50023
[ "MIT" ]
Joey35233/FoxKit-3
FoxKit/Assets/FoxKit/Fox/Generated/Fox/Geo/GeoCheckModuleConditionBody.generated.cs
2,175
C#
using System; using System.Linq; using System.Reflection; namespace Repo2.Core.ns11.ReflectionTools { public static class AssemblyReflector { //public static List<string> GetNamespaces(this Assembly assembly) // => assembly.ExportedTypes.Select(x // => x.Namespace).Distinct().ToList(); public static string PrependNamespace(this Assembly assembly, string typeName) { var typ = assembly.ExportedTypes.FirstOrDefault(x => x.Name == typeName); if (typ == null) return null; return $"{typ.Namespace}.{typ.Name}"; } public static Type FindTypeByName(this Assembly assembly, string typeName, bool errorIfMissing) { var fullNme = assembly.PrependNamespace(typeName); if (fullNme == null) { if (!errorIfMissing) return null; throw new TypeAccessException($"Failed to find type: “{typeName}”."); } try { return assembly.GetType(fullNme); } catch (Exception ex) { if (errorIfMissing) throw ex; return null; } } } }
28.930233
103
0.551447
[ "MIT" ]
peterson1/Repo2
Repo2.Core.ns11/ReflectionTools/AssemblyReflector.cs
1,250
C#
// -------------------------------------------------------------------------------------------------- // <copyright file="PropertyTypeCommandHandler.cs" company="InmoIT"> // Copyright (c) InmoIT. All rights reserved. // Developer: Vladimir P. CHibás (vladperchi). // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // -------------------------------------------------------------------------------------------------- using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using AutoMapper; using InmoIT.Modules.Inmo.Core.Abstractions; using InmoIT.Modules.Inmo.Core.Entities; using InmoIT.Modules.Inmo.Core.Exceptions; using InmoIT.Modules.Inmo.Core.Features.Owners.Events; using InmoIT.Modules.Inmo.Core.Features.PropertyTypes.Events; using InmoIT.Shared.Core.Common.Enums; using InmoIT.Shared.Core.Constants; using InmoIT.Shared.Core.Integration.Inmo; using InmoIT.Shared.Core.Interfaces.Services; using InmoIT.Shared.Core.Wrapper; using InmoIT.Shared.Dtos.Upload; using MediatR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Localization; namespace InmoIT.Modules.Inmo.Core.Features.PropertyTypes.Commands { internal class PropertyTypeCommandHandler : IRequestHandler<CreatePropertyTypeCommand, Result<Guid>>, IRequestHandler<UpdatePropertyTypeCommand, Result<Guid>>, IRequestHandler<RemovePropertyTypeCommand, Result<Guid>> { private readonly IDistributedCache _cache; private readonly IInmoDbContext _context; private readonly IMapper _mapper; private readonly IUploadService _uploadService; private readonly IStringLocalizer<PropertyTypeCommandHandler> _localizer; private readonly IPropertyService _propertyService; private readonly IPropertyTypeService _propertyTypeService; public PropertyTypeCommandHandler( IInmoDbContext context, IMapper mapper, IUploadService uploadService, IStringLocalizer<PropertyTypeCommandHandler> localizer, IPropertyService propertyService, IPropertyTypeService propertyTypeService, IDistributedCache cache) { _context = context; _mapper = mapper; _uploadService = uploadService; _localizer = localizer; _propertyService = propertyService; _propertyTypeService = propertyTypeService; _cache = cache; } public async Task<Result<Guid>> Handle(CreatePropertyTypeCommand command, CancellationToken cancellationToken) { if (await _context.PropertyTypes.Where(x => x.IsActive).AnyAsync(x => x.CodeInternal == command.CodeInternal, cancellationToken)) { throw new PropertyTypeAlreadyExistsException(_localizer); } var propertyType = _mapper.Map<PropertyType>(command); if (command.FileUploadRequest != null) { var fileUploadRequest = new FileUploadRequest { Data = command.FileUploadRequest?.Data, Extension = Path.GetExtension(command.FileUploadRequest.FileName), UploadStorageType = UploadStorageType.PropertyType }; string fileName = await _propertyTypeService.GenerateFileName(20); fileUploadRequest.FileName = $"{fileName}.{fileUploadRequest.Extension}"; propertyType.ImageUrl = await _uploadService.UploadAsync(fileUploadRequest, FileType.Image); } propertyType.CodeInternal.ToUpper(); propertyType.IsActive = true; try { propertyType.AddDomainEvent(new PropertyTypeRegisteredEvent(propertyType)); await _context.PropertyTypes.AddAsync(propertyType, cancellationToken); await _context.SaveChangesAsync(cancellationToken); return await Result<Guid>.SuccessAsync(propertyType.Id, _localizer["Property Type Saved"]); } catch (Exception) { throw new PropertyTypeCustomException(_localizer, null); } } public async Task<Result<Guid>> Handle(UpdatePropertyTypeCommand command, CancellationToken cancellationToken) { if (!await _context.PropertyTypes .Where(x => x.Id == command.Id) .AnyAsync(x => x.Name == command.Name, cancellationToken)) { throw new PropertyTypeNotFoundException(_localizer, command.Id); } var propertyType = _mapper.Map<PropertyType>(command); string currentImageUrl = command.ImageUrl ?? string.Empty; if (command.DeleteCurrentImageUrl && !string.IsNullOrEmpty(currentImageUrl)) { await _uploadService.RemoveFileImage(UploadStorageType.PropertyType, currentImageUrl); propertyType = propertyType.ClearPathImageUrl(); var fileUploadRequest = new FileUploadRequest { Data = command.FileUploadRequest?.Data, Extension = Path.GetExtension(command.FileUploadRequest.FileName), UploadStorageType = UploadStorageType.PropertyType }; string fileName = await _propertyTypeService.GenerateFileName(20); fileUploadRequest.FileName = $"{fileName}.{fileUploadRequest.Extension}"; propertyType.ImageUrl = await _uploadService.UploadAsync(fileUploadRequest, FileType.Image); } propertyType.CodeInternal = command.CodeInternal.ToUpper() ?? propertyType.CodeInternal; propertyType.IsActive = command.IsActive || propertyType.IsActive; try { propertyType.AddDomainEvent(new PropertyTypeUpdatedEvent(propertyType)); _context.PropertyTypes.Update(propertyType); await _context.SaveChangesAsync(cancellationToken); await _cache.RemoveAsync(CacheKeys.Common.GetEntityByIdCacheKey<Guid, PropertyType>(command.Id), cancellationToken); return await Result<Guid>.SuccessAsync(propertyType.Id, _localizer["Property Type Updated"]); } catch (Exception) { throw new PropertyTypeCustomException(_localizer, null); } } public async Task<Result<Guid>> Handle(RemovePropertyTypeCommand command, CancellationToken cancellationToken) { var propertyType = await _context.PropertyTypes.Where(x => x.Id == command.Id).FirstOrDefaultAsync(cancellationToken); _ = propertyType ?? throw new PropertyTypeNotFoundException(_localizer, command.Id); if (!await _propertyService.IsPropertyTypeUsed(propertyType.Id)) { try { propertyType.AddDomainEvent(new PropertyTypeRemovedEvent(propertyType.Id)); _context.PropertyTypes.Remove(propertyType); await _context.SaveChangesAsync(cancellationToken); await _cache.RemoveAsync(CacheKeys.Common.GetEntityByIdCacheKey<Guid, PropertyType>(command.Id), cancellationToken); return await Result<Guid>.SuccessAsync(propertyType.Id, _localizer["Property Type Deleted"]); } catch (Exception) { throw new PropertyTypeCustomException(_localizer, null); } } else { return await Result<Guid>.FailAsync(propertyType.Id, _localizer["Deletion Not Allowed Property Type"]); } } } }
47.592814
141
0.636512
[ "MIT" ]
DevCrafts/InmoIT
src/server/Modules/Inmo/Modules.Inmo.Core/Features/PropertyTypes/Commands/PropertyTypeCommandHandler.cs
7,951
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Flower : MonoBehaviour { public enum FlowerType { not_set, grow, colonize, protect, attack, }; public FlowerType type; public int owner; // 1 lub 2 public Vector2Int position; public int creationTime; /// Creation time in game ticks. public float creationTimeInSeconds; /// Creation time in seconds - used for animations and such. Not for logic. public Vector2Int sourcePosition2d; /// On creation flower will smoothly travel from this position to it's destination. public Vector3 sourcePosition3d; /// On creation flower will smoothly travel from this position to it's destination. public float travelSpeed; /// How fast does a sprout travel. In tiles per second. public float createFadeInSeconds; /// Duration of fade in during creation. public float destroyFadeOutSeconds; /// Duration of fade out during destruction. public float previousFadeOutSeconds; /// Duration of fade out of previous flower. public AudioClip[] createSounds = { }; /// Sounds played when flower is created. private Transform stolenModel; /// Model of the previous flower - will be faded out. internal bool isInFinalPosition; protected Map map { get { return Map.instance; } } // Start is called before the first frame update public virtual void Start() { isInFinalPosition = true; } void Update() { travelToPosition(); fadeIn(); fadeOutPrevious(); } void OnDisable() { if (stolenModel != null) Destroy(stolenModel.gameObject); } public void setSourcePosition(Vector2Int position2d, Vector3 position3d) { sourcePosition2d = position2d; sourcePosition3d = position3d; transform.position = position3d; } /// Logic for smooth movement from sourcePosition to final position. void travelToPosition() { var travelFraction = 1.0f; var destPos = map.mapPositionToWorldPosition(position, map.flowerZ); if (destPos != sourcePosition3d) { travelFraction = (Time.time - creationTimeInSeconds) * travelSpeed / (destPos - sourcePosition3d).magnitude; } if (travelFraction < 1.0f) { isInFinalPosition = false; travelFraction = Mathf.Sqrt(travelFraction); transform.position = sourcePosition3d * (1 - travelFraction) + destPos * travelFraction; } else { isInFinalPosition = true; transform.position = destPos; } } /// Logic for fade in on create. void fadeIn() { if (createFadeInSeconds == 0) return; var fadeFraction = (Time.time - creationTimeInSeconds) / createFadeInSeconds; if (fadeFraction > 1.0f) { fadeFraction = 1.0f; } else { fadeFraction = Mathf.Sqrt(fadeFraction); } var model = this.transform.Find("Model"); foreach (var child in model.GetComponentsInChildren<SpriteRenderer>()) { var color = child.color; color.a = fadeFraction; child.color = color; } } /// Logic for fade out of previous flower. void fadeOutPrevious() { if (stolenModel == null) return; if (previousFadeOutSeconds <= 0) { Destroy(stolenModel.gameObject); stolenModel = null; return; } var fadeFraction = (Time.time - creationTimeInSeconds) / previousFadeOutSeconds; if (fadeFraction > 1.0f) { fadeFraction = 1.0f; } else { fadeFraction = Mathf.Sqrt(fadeFraction); } foreach (var child in stolenModel.GetComponentsInChildren<SpriteRenderer>()) { var color = child.color; color.a = Mathf.Min(color.a, 1.0f - fadeFraction); child.color = color; } if (fadeFraction >= 1.0f) { Destroy(stolenModel.gameObject); stolenModel = null; } } public virtual void init(Flower previousFlower) { if (previousFlower != null) { var stolenModelsParent = GameObject.Find("StolenModelsParent").transform; // We need stolenmodels to be static, so we parent to a static object. stolenModel = previousFlower.transform.Find("Model"); stolenModel.SetParent(stolenModelsParent); } } public virtual void logicUpdate(int currentTime) { } }
29.580247
156
0.599332
[ "Unlicense" ]
Zbyl/GardenForce
GardenForce/Assets/Scripts/Flower.cs
4,794
C#
#region License /* MIT License Copyright © 2006 The Mono.Xna Team All rights reserved. Authors: Olivier Dufour (Duff) 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. */ #endregion License using System; using System.Collections.Generic; using System.Globalization; using UnityEngine; namespace Microsoft.Xna.Framework { public struct BoundingSphere : IEquatable<BoundingSphere> { #region Public Fields public Vector3 Center; public float Radius; #endregion Public Fields #region Constructors public BoundingSphere(Vector3 center, float radius) { this.Center = center; this.Radius = radius; } #endregion Constructors #region Public Methods public BoundingSphere Transform(Matrix matrix) { BoundingSphere sphere = new BoundingSphere(); sphere.Center = Vector3Helper.Transform(ref this.Center, matrix); sphere.Radius = this.Radius * ((float)Math.Sqrt((double)Math.Max(((matrix.M11 * matrix.M11) + (matrix.M12 * matrix.M12)) + (matrix.M13 * matrix.M13), Math.Max(((matrix.M21 * matrix.M21) + (matrix.M22 * matrix.M22)) + (matrix.M23 * matrix.M23), ((matrix.M31 * matrix.M31) + (matrix.M32 * matrix.M32)) + (matrix.M33 * matrix.M33))))); return sphere; } public void Transform(ref Matrix matrix, out BoundingSphere result) { result.Center = Vector3Helper.Transform(ref this.Center, matrix); result.Radius = this.Radius * ((float)Math.Sqrt((double)Math.Max(((matrix.M11 * matrix.M11) + (matrix.M12 * matrix.M12)) + (matrix.M13 * matrix.M13), Math.Max(((matrix.M21 * matrix.M21) + (matrix.M22 * matrix.M22)) + (matrix.M23 * matrix.M23), ((matrix.M31 * matrix.M31) + (matrix.M32 * matrix.M32)) + (matrix.M33 * matrix.M33))))); } public ContainmentType Contains(BoundingBox box) { //check if all corner is in sphere bool inside = true; foreach (Vector3 corner in box.GetCorners()) { if (this.Contains(corner) == ContainmentType.Disjoint) { inside = false; break; } } if (inside) return ContainmentType.Contains; //check if the distance from sphere center to cube face < radius double dmin = 0; if (Center.x < box.Min.x) dmin += (Center.x - box.Min.x) * (Center.x - box.Min.x); else if (Center.x > box.Max.x) dmin += (Center.x - box.Max.x) * (Center.x - box.Max.x); if (Center.y < box.Min.y) dmin += (Center.y - box.Min.y) * (Center.y - box.Min.y); else if (Center.y > box.Max.y) dmin += (Center.y - box.Max.y) * (Center.y - box.Max.y); if (Center.z < box.Min.z) dmin += (Center.z - box.Min.z) * (Center.z - box.Min.z); else if (Center.z > box.Max.z) dmin += (Center.z - box.Max.z) * (Center.z - box.Max.z); if (dmin <= Radius * Radius) return ContainmentType.Intersects; //else disjoint return ContainmentType.Disjoint; } public void Contains(ref BoundingBox box, out ContainmentType result) { result = this.Contains(box); } public ContainmentType Contains(BoundingFrustum frustum) { //check if all corner is in sphere bool inside = true; Vector3[] corners = frustum.GetCorners(); foreach (Vector3 corner in corners) { if (this.Contains(corner) == ContainmentType.Disjoint) { inside = false; break; } } if (inside) return ContainmentType.Contains; //check if the distance from sphere center to frustrum face < radius double dmin = 0; //TODO : calcul dmin if (dmin <= Radius * Radius) return ContainmentType.Intersects; //else disjoint return ContainmentType.Disjoint; } public ContainmentType Contains(BoundingSphere sphere) { float val = Vector3.Distance(sphere.Center, Center); if (val > sphere.Radius + Radius) return ContainmentType.Disjoint; else if (val <= Radius - sphere.Radius) return ContainmentType.Contains; else return ContainmentType.Intersects; } public void Contains(ref BoundingSphere sphere, out ContainmentType result) { result = Contains(sphere); } public ContainmentType Contains(Vector3 point) { float distance = Vector3.Distance(point, Center); if (distance > this.Radius) return ContainmentType.Disjoint; else if (distance < this.Radius) return ContainmentType.Contains; return ContainmentType.Intersects; } public void Contains(ref Vector3 point, out ContainmentType result) { result = Contains(point); } public static BoundingSphere CreateFromBoundingBox(BoundingBox box) { // Find the center of the box. Vector3 center = new Vector3((box.Min.x + box.Max.x) / 2.0f, (box.Min.y + box.Max.y) / 2.0f, (box.Min.z + box.Max.z) / 2.0f); // Find the distance between the center and one of the corners of the box. float radius = Vector3.Distance(center, box.Max); return new BoundingSphere(center, radius); } public static void CreateFromBoundingBox(ref BoundingBox box, out BoundingSphere result) { result = CreateFromBoundingBox(box); } public static BoundingSphere CreateFromFrustum(BoundingFrustum frustum) { return BoundingSphere.CreateFromPoints(frustum.GetCorners()); } public static BoundingSphere CreateFromPoints(IEnumerable<Vector3> points) { if (points == null) throw new ArgumentNullException("points"); float radius = 0; Vector3 center = new Vector3(); // First, we'll find the center of gravity for the point 'cloud'. int num_points = 0; // The number of points (there MUST be a better way to get this instead of counting the number of points one by one?) foreach (Vector3 v in points) { center += v; // If we actually knew the number of points, we'd get better accuracy by adding v / num_points. ++num_points; } center /= (float)num_points; // Calculate the radius of the needed sphere (it equals the distance between the center and the point further away). foreach (Vector3 v in points) { float distance = ((Vector3)(v - center)).magnitude; if (distance > radius) radius = distance; } return new BoundingSphere(center, radius); } public static BoundingSphere CreateMerged(BoundingSphere original, BoundingSphere additional) { Vector3 ocenterToaCenter = additional.Center - original.Center; float distance = ocenterToaCenter.magnitude; if (distance <= original.Radius + additional.Radius)//intersect { if (distance <= original.Radius - additional.Radius)//original contain additional return original; if (distance <= additional.Radius - original.Radius)//additional contain original return additional; } //else find center of new sphere and radius float leftRadius = Math.Max(original.Radius - distance, additional.Radius); float Rightradius = Math.Max(original.Radius + distance, additional.Radius); ocenterToaCenter = ocenterToaCenter + (((leftRadius - Rightradius) / (2 * ocenterToaCenter.magnitude)) * ocenterToaCenter);//oCenterToResultCenter BoundingSphere result = new BoundingSphere(); result.Center = original.Center + ocenterToaCenter; result.Radius = (leftRadius + Rightradius) / 2; return result; } public static void CreateMerged(ref BoundingSphere original, ref BoundingSphere additional, out BoundingSphere result) { result = BoundingSphere.CreateMerged(original, additional); } public bool Equals(BoundingSphere other) { return this.Center == other.Center && this.Radius == other.Radius; } public override bool Equals(object obj) { if (obj is BoundingSphere) return this.Equals((BoundingSphere)obj); return false; } public override int GetHashCode() { return this.Center.GetHashCode() + this.Radius.GetHashCode(); } public bool Intersects(BoundingBox box) { return box.Intersects(this); } public void Intersects(ref BoundingBox box, out bool result) { result = Intersects(box); } public bool Intersects(BoundingFrustum frustum) { if (frustum == null) throw new NullReferenceException(); throw new NotImplementedException(); } public bool Intersects(BoundingSphere sphere) { float val = Vector3.Distance(sphere.Center, Center); if (val > sphere.Radius + Radius) return false; return true; } public void Intersects(ref BoundingSphere sphere, out bool result) { result = Intersects(sphere); } public PlaneIntersectionType Intersects(Plane plane) { float distance = Vector3.Dot(plane.normal, this.Center) + plane.distance; if (distance > this.Radius) return PlaneIntersectionType.Front; if (distance < -this.Radius) return PlaneIntersectionType.Back; //else it intersect return PlaneIntersectionType.Intersecting; } public void Intersects(ref Plane plane, out PlaneIntersectionType result) { result = Intersects(plane); } public Nullable<float> Intersects(Ray ray) { return ray.Intersects(this); } public void Intersects(ref Ray ray, out Nullable<float> result) { result = Intersects(ray); } public static bool operator ==(BoundingSphere a, BoundingSphere b) { return a.Equals(b); } public static bool operator !=(BoundingSphere a, BoundingSphere b) { return !a.Equals(b); } public override string ToString() { return string.Format(CultureInfo.CurrentCulture, "{{Center:{0} Radius:{1}}}", this.Center.ToString(), this.Radius.ToString()); } #endregion Public Methods } }
34.476584
344
0.58346
[ "MIT" ]
harzival/PyriteDemoClient
Assets/Pyrite/Scripts/Microsoft.Xna/BoundingSphere.cs
12,518
C#
// <copyright file="ItemPriceCalculatorTest.cs" company="MUnique"> // Licensed under the MIT License. See LICENSE file in the project root for full license information. // </copyright> namespace MUnique.OpenMU.Tests { using System.Collections.Generic; using MUnique.OpenMU.DataModel.Configuration.Items; using MUnique.OpenMU.DataModel.Entities; using MUnique.OpenMU.GameLogic; using MUnique.OpenMU.GameLogic.Attributes; using NUnit.Framework; using Rhino.Mocks; /// <summary> /// Tests the <see cref="ItemPriceCalculator"/> with some exemplary data. /// </summary> /// <remarks> /// The most price values here are directly taken from stores on GMO. /// However, I guess they are calculated and shown by the client, if you just show such an item in the merchant store. /// </remarks> [TestFixture] public class ItemPriceCalculatorTest { /// <summary> /// The calculator which is tested. /// </summary> private readonly ItemPriceCalculator calculator = new ItemPriceCalculator(); /// <summary> /// Tests if the apple price is calculated correctly. /// </summary> /// <param name="level">The level.</param> /// <param name="price">The price.</param> [TestCase(0, 60)] [TestCase(1, 120)] public void Apple(byte level, int price) { this.CheckPrice(0, 1, 3, 1, 1, 14, 5, level, price); } /// <summary> /// Tests if the bolt price is calculated correctly. /// </summary> /// <param name="level">The level.</param> /// <param name="price">The price.</param> [TestCase(0, 100)] [TestCase(1, 1400)] [TestCase(2, 2200)] public void Bolts(byte level, int price) { this.CheckPrice(7, 0, 255, 1, 1, 4, 0, level, price); } /// <summary> /// Tests if the arrow price is calculated correctly. /// </summary> /// <param name="level">The level.</param> /// <param name="price">The price.</param> [TestCase(0, 70)] [TestCase(1, 1200)] [TestCase(2, 2000)] public void Arrows(byte level, int price) { this.CheckPrice(15, 0, 255, 1, 1, 4, 0, level, price); } /// <summary> /// Tests if the price of the fireball scroll is calculated as 300. /// </summary> [Test] public void FireballScroll() { this.CheckPrice(3, 0, 1, 1, 1, 15, 300, 0, 300); } /// <summary> /// Tests if the price of the powerwave scroll is calculated as 1100. /// </summary> [Test] public void PowerwaveScroll() { this.CheckPrice(10, 0, 1, 1, 1, 15, 1100, 0, 1100); } /// <summary> /// Tests if the price of the lightning scroll is calculated as 3000. /// </summary> [Test] public void LightningScroll() { this.CheckPrice(2, 0, 1, 1, 1, 15, 3000, 0, 3000); } /// <summary> /// Tests if the price of the meteorite scroll is calculated as 11000. /// </summary> [Test] public void MeteoriteScroll() { this.CheckPrice(1, 0, 1, 1, 1, 15, 11000, 0, 11000); } /// <summary> /// Tests if the price of the teleport scroll is calculated as 5000. /// </summary> [Test] public void TeleportScroll() { this.CheckPrice(5, 0, 1, 1, 1, 15, 5000, 0, 5000); } /// <summary> /// Tests if the price of the ice scroll is calculated as 14000. /// </summary> [Test] public void IceScroll() { this.CheckPrice(6, 0, 1, 1, 1, 15, 14000, 0, 14000); } /// <summary> /// Tests if the price of the poison scroll is calculated as 17000. /// </summary> [Test] public void PoisonScroll() { this.CheckPrice(0, 0, 1, 1, 1, 15, 17000, 0, 17000); } /// <summary> /// Tests if the items of a pad set +0+4+Luck is calculated correctly. /// </summary> /// <param name="group">The group.</param> /// <param name="dropLevel">The drop level.</param> /// <param name="maxDurability">The maximum durability.</param> /// <param name="price">The price.</param> /// <remarks> /// pad helm+0+4+l 480 /// armor 1400 /// pants 960 /// gloves 290 /// boots 370. /// </remarks> [TestCase(7, 5, 28, 480, Description="Pad Helm")] [TestCase(8, 10, 28, 1400, Description = "Pad Armor")] [TestCase(9, 8, 28, 960, Description = "Pad Pants")] [TestCase(10, 3, 28, 290, Description = "Pad Gloves")] [TestCase(11, 4, 28, 370, Description = "Pad Boots")] public void PadSetItem_0_4_Luck(byte group, byte dropLevel, byte maxDurability, long price) { this.CheckPrice(2, dropLevel, maxDurability, 2, 2, group, 0, 0, price, true, true); } /// <summary> /// Tests if the items of a bone set +2+4+Luck is calculated correctly. /// </summary> /// <param name="group">The group.</param> /// <param name="dropLevel">The drop level.</param> /// <param name="maxDurability">The maximum durability.</param> /// <param name="price">The price.</param> /// <remarks> /// bone helm+2+4+l 9400 /// armor 13500 /// pants 11300 /// gloves 6200 /// boots 7700. /// </remarks> [TestCase(7, 18, 30, 9400, Description = "Bone Helm")] [TestCase(8, 22, 30, 13500, Description = "Bone Armor")] [TestCase(9, 20, 30, 11300, Description = "Bone Pants")] [TestCase(10, 14, 30, 6200, Description = "Bone Gloves")] [TestCase(11, 16, 30, 7700, Description = "Bone Boots")] public void BoneSetItem_2_4_Luck(byte group, byte dropLevel, byte maxDurability, long price) { this.CheckPrice(4, dropLevel, maxDurability, 2, 2, group, 0, 2, price, true, true); } /// <summary> /// Tests if the items of a sphinx set +3+4+Luck is calculated correctly. /// </summary> /// <param name="group">The group.</param> /// <param name="dropLevel">The drop level.</param> /// <param name="maxDurability">The maximum durability.</param> /// <param name="price">The price.</param> /// <remarks> /// sphinx helm+3+4+l 34200 /// armor 48200 /// pants 38500 /// gloves 26500 /// boots 30200. /// </remarks> [TestCase(7, 32, 36, 34200, Description = "Sphinx Mask")] [TestCase(8, 38, 36, 48200, Description = "Sphinx Armor")] [TestCase(9, 34, 36, 38500, Description = "Sphinx Pants")] [TestCase(10, 28, 36, 26500, Description = "Sphinx Gloves")] [TestCase(11, 30, 36, 30200, Description = "Sphinx Boots")] public void SphinxSetItem_3_4_Luck(byte group, byte dropLevel, byte maxDurability, long price) { this.CheckPrice(7, dropLevel, maxDurability, 2, 2, group, 0, 3, price, true, true); } /// <summary> /// Tests the price calculations of some staffs. /// </summary> /// <param name="id">The identifier.</param> /// <param name="level">The level.</param> /// <param name="dropLevel">The drop level.</param> /// <param name="maxDurability">The maximum durability.</param> /// <param name="width">The width.</param> /// <param name="heigth">The heigth.</param> /// <param name="price">The price.</param> /// <remarks> /// skull+0+4+l 480 /// angelic+2+4+l 9400 /// serpent+3+4+l 30200 /// thunder+3+4+l 59300. /// </remarks> [TestCase(0, 0, 6, 20, 1, 3, 480, Description = "skull+0+4+l")] [TestCase(1, 2, 18, 38, 2, 3, 9400, Description = "angelic+2+4+l")] [TestCase(2, 3, 30, 50, 2, 3, 30200, Description = "serpent+3+4+l")] [TestCase(3, 3, 42, 60, 2, 4, 59300, Description = "thunder+3+4+l")] public void Staffs(byte id, byte level, byte dropLevel, byte maxDurability, byte width, byte heigth, long price) { this.CheckPrice(id, dropLevel, maxDurability, heigth, width, 5, 0, level, price, true, true); } /// <summary> /// Tests the price calculations of some shields. /// </summary> /// <param name="id">The identifier.</param> /// <param name="level">The level.</param> /// <param name="dropLevel">The drop level.</param> /// <param name="maxDurability">The maximum durability.</param> /// <param name="width">The width.</param> /// <param name="heigth">The heigth.</param> /// <param name="skill">if set to <c>true</c> [skill].</param> /// <param name="price">The price.</param> /// <remarks> /// small shield+0+5+l 230 /// buckler+1+5+s+l 2300 /// horn+2+5+l 2600 /// kite+3+5+l 5500 /// skull+3+5+s+l 18800 /// </remarks> [TestCase(0, 0, 3, 22, 2, 2, false, 230, Description = "small shield+0+5+l")] [TestCase(4, 1, 6, 24, 2, 2, true, 2300, Description = "buckler+1+5+s+l")] [TestCase(1, 2, 9, 28, 2, 2, false, 2600, Description = "horn+2+5+l")] [TestCase(2, 3, 12, 32, 2, 2, false, 5500, Description = "kite+3+5+l")] [TestCase(6, 3, 15, 34, 2, 2, true, 18800, Description = "skull+3+5+s+l")] public void Shields(byte id, byte level, byte dropLevel, byte maxDurability, byte width, byte heigth, bool skill, long price) { this.CheckPrice(id, dropLevel, maxDurability, heigth, width, 6, 0, level, price, true, true, skill); } /// <summary> /// Tests the price calculation of a small shield. /// </summary> /// <param name="level">The level.</param> /// <param name="price">The price.</param> [TestCase(0, 110)] [TestCase(1, 240)] [TestCase(2, 470)] [TestCase(3, 820)] [TestCase(4, 1300)] [TestCase(5, 3000)] [TestCase(6, 6900)] [TestCase(7, 21400)] [TestCase(8, 58100)] [TestCase(9, 121900)] [TestCase(10, 275300)] [TestCase(11, 617000)] [TestCase(12, 1324700)] [TestCase(13, 2693500)] [TestCase(14, 4777500)] [TestCase(15, 7726800)] public void SmallShield(byte level, long price) { this.CheckPrice(0, 3, 22, 2, 2, 6, 0, level, price); } /// <summary> /// Tests the price calculations of some swords. /// </summary> /// <param name="id">The identifier.</param> /// <param name="level">The level.</param> /// <param name="dropLevel">The drop level.</param> /// <param name="maxDurability">The maximum durability.</param> /// <param name="width">The width.</param> /// <param name="heigth">The heigth.</param> /// <param name="skill">if set to <c>true</c> [skill].</param> /// <param name="price">The price.</param> /// <remarks> /// short sword+0+4+l 230 /// hand axe+1+4+l 610 /// kris+2+4+l 1600 /// mace+2+4+l 1900 /// rapier+2+4+l 2600 /// double+2+4+s+l 12400 /// blade+3+4+s+l 86400. /// </remarks> [TestCase(1, 0, 3, 22, 1, 2, false, 230, Description = "short sword+0+4+l")] [TestCase(0, 2, 6, 20, 1, 2, false, 1600, Description = "kris+2+4+l")] [TestCase(2, 2, 9, 23, 1, 3, false, 2600, Description = "rapier+2+4+l")] [TestCase(5, 3, 36, 39, 1, 3, true, 86400, Description = "blade+3+4+s+l")] public void Swords(byte id, byte level, byte dropLevel, byte maxDurability, byte width, byte heigth, bool skill, long price) { this.CheckPrice(id, dropLevel, maxDurability, heigth, width, 0, 0, level, price, true, true, skill); } private void CheckPrice(byte id, byte dropLevel, byte maxDurability, byte height, byte width, byte group, int value, byte level, long price, bool luck = false, bool option = false, bool skill = false) { var itemDefinition = MockRepository.GenerateStub<ItemDefinition>(); itemDefinition.DropLevel = dropLevel; itemDefinition.Durability = maxDurability; itemDefinition.Height = height; itemDefinition.Width = width; itemDefinition.Group = group; itemDefinition.Value = value; itemDefinition.Number = id; itemDefinition.Stub(d => d.BasePowerUpAttributes).Return(new List<ItemBasePowerUpDefinition>()); if (group < 6) { // weapons should have a min dmg attribute itemDefinition.BasePowerUpAttributes.Add(new ItemBasePowerUpDefinition { TargetAttribute = Stats.MinimumPhysBaseDmg }); } var item = MockRepository.GenerateStub<Item>(); item.Definition = itemDefinition; item.Durability = itemDefinition.Durability; item.Level = level; item.Stub(i => i.ItemOptions).Return(new List<ItemOptionLink>()); if (luck) { var optionLink = new ItemOptionLink { ItemOption = new ItemOption { OptionType = ItemOptionTypes.Luck } }; item.ItemOptions.Add(optionLink); } if (option) { var optionLink = new ItemOptionLink { ItemOption = new ItemOption { OptionType = ItemOptionTypes.Option } }; item.ItemOptions.Add(optionLink); } if (skill) { item.HasSkill = true; } var buyingPrice = this.calculator.CalculateBuyingPrice(item); Assert.That(buyingPrice, Is.EqualTo(price)); } } }
39.836957
208
0.530832
[ "MIT" ]
sven-n/OpenMU
tests/MUnique.OpenMU.Tests/ItemPriceCalculatorTest.cs
14,662
C#
using System.Collections.Generic; using Latem.Runtime.Instructions; using Latem.Runtime.Memory.Storage; namespace Latem.Runtime { public class MachineState { public IMemory Memory { get; private set; } public InstructionSet Instructions { get; private set; } public MachineState(IMemory memory, IReadOnlyCollection<IInstruction> instructions) { Memory = memory; Instructions = new InstructionSet(instructions); } } }
26.052632
91
0.678788
[ "MIT" ]
FetzenRndy/Creative
projects/Latem/Latem.Runtime/MachineState.cs
495
C#
using System.Web; using System.Web.Optimization; namespace FIT5032_Week06B { public class BundleConfig { // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at https://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } } }
38.9375
113
0.575441
[ "MIT" ]
JianLoong/FIT5032-S2-2018
Solutions/FIT5032_Week06B/FIT5032_Week06B/App_Start/BundleConfig.cs
1,248
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using Aliyun.Acs.Core; using System.Collections.Generic; namespace Aliyun.Acs.Rds.Model.V20140815 { public class DescribeSlowLogRecordsResponse : AcsResponse { private string requestId; private string dBInstanceId; private string engine; private int? totalRecordCount; private int? pageNumber; private int? pageRecordCount; private List<DescribeSlowLogRecords_SQLSlowRecord> items; public string RequestId { get { return requestId; } set { requestId = value; } } public string DBInstanceId { get { return dBInstanceId; } set { dBInstanceId = value; } } public string Engine { get { return engine; } set { engine = value; } } public int? TotalRecordCount { get { return totalRecordCount; } set { totalRecordCount = value; } } public int? PageNumber { get { return pageNumber; } set { pageNumber = value; } } public int? PageRecordCount { get { return pageRecordCount; } set { pageRecordCount = value; } } public List<DescribeSlowLogRecords_SQLSlowRecord> Items { get { return items; } set { items = value; } } public class DescribeSlowLogRecords_SQLSlowRecord { private string hostAddress; private string dBName; private string sQLText; private long? queryTimes; private long? lockTimes; private long? parseRowCounts; private long? returnRowCounts; private string executionStartTime; public string HostAddress { get { return hostAddress; } set { hostAddress = value; } } public string DBName { get { return dBName; } set { dBName = value; } } public string SQLText { get { return sQLText; } set { sQLText = value; } } public long? QueryTimes { get { return queryTimes; } set { queryTimes = value; } } public long? LockTimes { get { return lockTimes; } set { lockTimes = value; } } public long? ParseRowCounts { get { return parseRowCounts; } set { parseRowCounts = value; } } public long? ReturnRowCounts { get { return returnRowCounts; } set { returnRowCounts = value; } } public string ExecutionStartTime { get { return executionStartTime; } set { executionStartTime = value; } } } } }
15.244813
63
0.572673
[ "Apache-2.0" ]
brightness007/unofficial-aliyun-openapi-net-sdk
aliyun-net-sdk-rds/Rds/Model/V20140815/DescribeSlowLogRecordsResponse.cs
3,674
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace AdventOfCode2019.Puzzles.Day16 { public class Puzzle1 : IPuzzle { public object Solve() { var inputSignal = GetInputSignal(); var signalCleaner = new SignalCleaner(); var outputSignal = signalCleaner.Clean(inputSignal, 100); var answer = string.Join(string.Empty, outputSignal.Take(8)); return answer; } private IReadOnlyList<int> GetInputSignal() { var line = File.ReadAllText("Puzzles/Day16/input.txt").Trim(); return line.Select(c => int.Parse(c.ToString())).ToList(); } private class SignalCleaner { public IEnumerable<int> Clean(IReadOnlyCollection<int> inputSignal, int phases) { var offsetPatterns = GenerateOffsetPatterns(inputSignal.Count); var outputSignal = new List<int>(inputSignal); for (var phaseIndex = 0; phaseIndex < phases; phaseIndex++) { var phaseResult = new List<int>(inputSignal); for (var offsetPatternIndex = 0; offsetPatternIndex < offsetPatterns.Count; offsetPatternIndex++) { var offsetPattern = offsetPatterns[offsetPatternIndex]; var runningTotal = 0; for (var elementIndex = 0; elementIndex < outputSignal.Count; elementIndex++) { var element = outputSignal[elementIndex]; var elementOffset = offsetPattern[elementIndex]; var elementResult = element * elementOffset; runningTotal += elementResult; } var keptDigit = Math.Abs(runningTotal % 10); phaseResult[offsetPatternIndex] = keptDigit; } outputSignal = phaseResult; } return outputSignal; } private IReadOnlyDictionary<int, IReadOnlyList<int>> GenerateOffsetPatterns(int inputSignalLength) { var basePattern = new[] { 0, 1, 0, -1 }; var offsetPattern = new Dictionary<int, IReadOnlyList<int>>(); for (var i = 0; i < inputSignalLength; i++) { var pattern = new List<int>(); while (pattern.Count <= inputSignalLength) { foreach (var basePatternValue in basePattern) { pattern.AddRange(Enumerable.Repeat(basePatternValue, i + 1)); } } offsetPattern[i] = pattern.Skip(1).Take(inputSignalLength).ToList(); } return offsetPattern; } } } }
34.202247
117
0.507884
[ "MIT" ]
lewishenson/AdventOfCode2019
src/Puzzles/Day16/Puzzle1.cs
3,044
C#
/* Copyright (c) 2013, 2014 Paolo Patierno All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Paolo Patierno - initial API and implementation and/or initial documentation Simonas Greicius - 2021 rework */ using System; namespace Tevux.Protocols.Mqtt { public delegate void UnsubscribedEventHandler(object sender, UnsubscribedEventArgs e); public class UnsubscribedEventArgs : EventArgs { public string Topic { get; private set; } internal UnsubscribedEventArgs(string topic) { Topic = topic; } } }
30.903226
91
0.723382
[ "EPL-1.0" ]
tevux-tech/forks.paho.mqtt.m2mqtt
M2Mqtt/Events/UnsubscribedEventArgs.cs
930
C#
using System; using System.Text.RegularExpressions; using System.Linq; namespace bindu { public class WgetOutput { public double PercentageComplete {get;set;} public double DownloadRate {get;set;} } public class WgetOutputParser { public WgetOutput _output; public WgetOutputParser() { } public WgetOutput Parse(string outputLine) { //" 0K .......... .......... .......... .......... .......... 1% 79.4K 34s" Regex regex = new Regex(@"^(\s)*[0-9]*K(.)*[0-9]*%(.)*$"); _output = new WgetOutput(); if (String.IsNullOrEmpty(outputLine)) return null; if (!regex.Matches(outputLine).Any()) return null; string[] progParts = outputLine.Split(' '); string strPerc = progParts.Where(p => p.Contains("%")).FirstOrDefault(); if (!string.IsNullOrEmpty(strPerc)) _output.PercentageComplete = Double.Parse(strPerc.Replace("%","")); return _output; } } }
26.023256
92
0.512064
[ "MIT" ]
AdhirRamjiawan/bindu
WgetOutputParser.cs
1,119
C#
/* * Copyright (c) 2018 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.Runtime.InteropServices; using Tizen.Internals.Errors; using Tizen.Applications; using System.Reflection; internal static partial class Interop { internal static partial class LibRPCPort { internal enum ErrorCode { None = Tizen.Internals.Errors.ErrorCode.None, InvalidParameter = Tizen.Internals.Errors.ErrorCode.InvalidParameter, OutOfMemory = Tizen.Internals.Errors.ErrorCode.OutOfMemory, PermissionDenied = Tizen.Internals.Errors.ErrorCode.PermissionDenied, IoError = Tizen.Internals.Errors.ErrorCode.IoError, } internal enum PortType { Main, Callback } internal static partial class Parcel { //int rpc_port_parcel_create(rpc_port_parcel_h *h); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_create")] internal static extern ErrorCode Create(out IntPtr handle); //int rpc_port_parcel_create_from_port(rpc_port_parcel_h *h, rpc_port_h port); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_create_from_port")] internal static extern ErrorCode CreateFromPort(out IntPtr parcelHandle, IntPtr portHandle); //int rpc_port_parcel_send(rpc_port_parcel_h h, rpc_port_h port); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_send")] internal static extern ErrorCode Send(IntPtr parcelHandle, IntPtr portHandle); //int rpc_port_parcel_destroy(rpc_port_parcel_h h); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_destroy")] internal static extern ErrorCode Destroy(IntPtr handle); //int rpc_port_parcel_write_byte(rpc_port_parcel_h h, char b); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_write_byte")] internal static extern ErrorCode WriteByte(IntPtr parcelHandle, byte b); //int rpc_port_parcel_write_int16(rpc_port_parcel_h h, short i); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_write_int16")] internal static extern ErrorCode WriteInt16(IntPtr parcelHandle, short i); //int rpc_port_parcel_write_int32(rpc_port_parcel_h h, int i); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_write_int32")] internal static extern ErrorCode WriteInt32(IntPtr parcelHandle, int i); //int rpc_port_parcel_write_int64(rpc_port_parcel_h h, int i); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_write_int64")] internal static extern ErrorCode WriteInt64(IntPtr parcelHandle, long i); //int rpc_port_parcel_write_float(rpc_port_parcel_h h, float f); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_write_float")] internal static extern ErrorCode WriteFloat(IntPtr parcelHandle, float f); //int rpc_port_parcel_write_double(rpc_port_parcel_h h, double d); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_write_double")] internal static extern ErrorCode WriteDouble(IntPtr parcelHandle, double d); //int rpc_port_parcel_write_string(rpc_port_parcel_h h, const char* str); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_write_string")] internal static extern ErrorCode WriteString(IntPtr parcelHandle, string str); //int rpc_port_parcel_write_bool(rpc_port_parcel_h h, bool b); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_write_bool")] internal static extern ErrorCode WriteBool(IntPtr parcelHandle, bool b); //int rpc_port_parcel_write_bundle(rpc_port_parcel_h h, bundle* b); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_write_bundle")] internal static extern ErrorCode WriteBundle(IntPtr parcelHandle, IntPtr b); //int rpc_port_parcel_write_array_count(rpc_port_parcel_h h, int count); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_write_array_count")] internal static extern ErrorCode WriteArrayCount(IntPtr parcelHandle, int count); //int rpc_port_parcel_read_byte(rpc_port_parcel_h h, char* b); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_read_byte")] internal static extern ErrorCode ReadByte(IntPtr parcelHandle, out byte b); //int rpc_port_parcel_read_int16(rpc_port_parcel_h h, short *i); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_read_int16")] internal static extern ErrorCode ReadInt16(IntPtr parcelHandle, out short i); //int rpc_port_parcel_read_int32(rpc_port_parcel_h h, int* i); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_read_int32")] internal static extern ErrorCode ReadInt32(IntPtr parcelHandle, out int i); //int rpc_port_parcel_read_int64(rpc_port_parcel_h h, long long* i); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_read_int64")] internal static extern ErrorCode ReadInt64(IntPtr parcelHandle, out long i); //int rpc_port_parcel_read_float(rpc_port_parcel_h h, float *f); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_read_float")] internal static extern ErrorCode ReadFloat(IntPtr parcelHandle, out float f); //int rpc_port_parcel_read_double(rpc_port_parcel_h h, double *d); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_read_double")] internal static extern ErrorCode ReadDouble(IntPtr parcelHandle, out double f); //int rpc_port_parcel_read_string(rpc_port_parcel_h h, char** str); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_read_string")] internal static extern ErrorCode ReadString(IntPtr parcelHandle, out string str); //int rpc_port_parcel_read_bool(rpc_port_parcel_h h, bool *b); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_read_bool")] internal static extern ErrorCode ReadBool(IntPtr parcelHandle, out bool b); //int rpc_port_parcel_read_bundle(rpc_port_parcel_h h, bundle** b); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_read_bundle")] internal static extern ErrorCode ReadBundle(IntPtr parcelHandle, out IntPtr b); //int rpc_port_parcel_read_array_count(rpc_port_parcel_h h, int *count); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_read_array_count")] internal static extern ErrorCode ReadArrayCount(IntPtr parcelHandle, out int count); //int rpc_port_parcel_burst_read(rpc_port_parcel_h h, unsigned char *buf, unsigned int size); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_burst_read")] internal static extern ErrorCode Read(IntPtr parcelHandle, [In, Out] byte[] buf, int size); //int rpc_port_parcel_burst_write(rpc_port_parcel_h h, const unsigned char *buf, unsigned int size); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_burst_write")] internal static extern ErrorCode Write(IntPtr parcelHandle, byte[] buf, int size); //int rpc_port_parcel_get_header(rpc_port_parcel_h h, rpc_port_parcel_header_h *header); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_get_header")] internal static extern ErrorCode GetHeader(IntPtr parcelHandle, out IntPtr ParcelHeaderHandle); //int rpc_port_parcel_header_set_tag(rpc_port_parcel_header_h header, const char *tag); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_header_set_tag")] internal static extern ErrorCode SetTag(IntPtr parcelHeaderHandle, string tag); //int rpc_port_parcel_header_get_tag(rpc_port_parcel_header_h header, char **tag); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_header_get_tag")] internal static extern ErrorCode GetTag(IntPtr parcelHeaderHandle, out string tag); //int rpc_port_parcel_header_set_seq_num(rpc_port_parcel_header_h header, int seq_num); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_header_set_seq_num")] internal static extern ErrorCode SetSeqNum(IntPtr parcelHeaderHandle, int seq_num); //int rpc_port_parcel_header_get_seq_num(rpc_port_parcel_header_h header, int *seq_num); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_header_get_seq_num")] internal static extern ErrorCode GetSeqNum(IntPtr parcelHeaderHandle, out int seq_num); //int rpc_port_parcel_header_get_timestamp(rpc_port_parcel_header_h header, struct timespec *timestamp); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_header_get_timestamp")] internal static extern ErrorCode GetTimeStamp(IntPtr parcelHeaderHandle, ref Libc.TimeStamp time); //int rpc_port_parcel_get_raw(rpc_port_parcel_h h, void **raw, unsigned int *size); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_get_raw")] internal static extern ErrorCode GetRaw(IntPtr parcelHandle, out IntPtr raw, out uint size); //int rpc_port_parcel_create_from_raw(rpc_port_parcel_h *h, const void *raw, unsigned int size); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_parcel_create_from_raw")] internal static extern ErrorCode CreateFromRaw(out IntPtr parcelHandle, byte[] raw, uint size); } internal static partial class Proxy { //typedef void (*rpc_port_proxy_connected_event_cb)(const char *ep, const char* port_name, rpc_port_h port, void* data); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void ConnectedEventCallback(string endPoint, string port_name, IntPtr port, IntPtr data); //typedef void (*rpc_port_proxy_disconnected_event_cb)(const char *ep, const char* port_name, void* data); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void DisconnectedEventCallback(string endPoint, string port_name, IntPtr data); //typedef void (*rpc_port_proxy_rejected_event_cb) (const char* ep, const char* port_name, void* data); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void RejectedEventCallback(string endPoint, string port_name, IntPtr data); //typedef void (*rpc_port_proxy_received_event_cb) (const char* ep, const char* port_name, void* data); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void ReceivedEventCallback(string endPoint, string port_name, IntPtr data); //int rpc_port_proxy_create(rpc_port_proxy_h *h); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_proxy_create")] internal static extern ErrorCode Create(out IntPtr handle); //int rpc_port_proxy_destroy(rpc_port_proxy_h h); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_proxy_destroy")] internal static extern ErrorCode Destroy(IntPtr handle); //int rpc_port_proxy_connect(rpc_port_proxy_h h, const char *appid, const char* port); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_proxy_connect")] internal static extern ErrorCode Connect(IntPtr handle, string appId, string port); //int rpc_port_proxy_add_connected_event_cb(rpc_port_proxy_h h, rpc_port_proxy_connected_event_cb cb, void* data); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_proxy_add_connected_event_cb")] internal static extern ErrorCode AddConnectedEventCb(IntPtr handle, ConnectedEventCallback cb, IntPtr data); //int rpc_port_proxy_add_disconnected_event_cb(rpc_port_proxy_h h, rpc_port_proxy_disconnected_event_cb cb, void* data); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_proxy_add_disconnected_event_cb")] internal static extern ErrorCode AddDisconnectedEventCb(IntPtr handle, DisconnectedEventCallback cb, IntPtr data); //int rpc_port_proxy_add_rejected_event_cb(rpc_port_proxy_h h, rpc_port_proxy_rejected_event_cb cb, void* data); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_proxy_add_rejected_event_cb")] internal static extern ErrorCode AddRejectedEventCb(IntPtr handle, RejectedEventCallback cb, IntPtr data); //int rpc_port_proxy_add_received_event_cb(rpc_port_proxy_h h, rpc_port_proxy_received_event_cb cb, void* data); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_proxy_add_received_event_cb")] internal static extern ErrorCode AddReceivedEventCb(IntPtr handle, ReceivedEventCallback cb, IntPtr data); //int rpc_port_proxy_get_port(rpc_port_proxy_h h, rpc_port_port_type_e type, rpc_port_h* port); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_proxy_get_port")] internal static extern ErrorCode GetPort(IntPtr handle, PortType t, out IntPtr port); //int rpc_port_proxy_connect_sync(rpc_port_proxy_h h, const char* appid, const char* port); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_proxy_connect_sync")] internal static extern ErrorCode ConnectSync(IntPtr handle, string appId, string port); } internal static partial class Stub { //typedef void (*rpc_port_stub_connected_event_cb)(const char *sender, const char *instance, void* data); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void ConnectedEventCallback(string sender, string instance, IntPtr data); //typedef void (* rpc_port_stub_disconnected_event_cb) (const char* sender, const char *instance, void* data); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void DisconnectedEventCallback(string sender, string instance, IntPtr data); //typedef void (* rpc_port_stub_received_event_cb) (const char* sender, const char *instance, rpc_port_h port, void* data); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int ReceivedEventCallback(string sender, string instance, IntPtr port, IntPtr data); //int rpc_port_stub_create(rpc_port_stub_h* h, const char* port_name); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_stub_create")] internal static extern ErrorCode Create(out IntPtr handle, string portName); //int rpc_port_stub_destroy(rpc_port_stub_h h); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_stub_destroy")] internal static extern ErrorCode Destroy(IntPtr handle); //int rpc_port_stub_listen(rpc_port_stub_h h); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_stub_listen")] internal static extern ErrorCode Listen(IntPtr handle); //int rpc_port_stub_add_connected_event_cb(rpc_port_stub_h h, rpc_port_stub_connected_event_cb cb, void* data); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_stub_add_connected_event_cb")] internal static extern ErrorCode AddConnectedEventCb(IntPtr handle, ConnectedEventCallback cb, IntPtr data); //int rpc_port_stub_add_disconnected_event_cb(rpc_port_stub_h h, rpc_port_stub_disconnected_event_cb cb, void* data); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_stub_add_disconnected_event_cb")] internal static extern ErrorCode AddDisconnectedEventCb(IntPtr handle, DisconnectedEventCallback cb, IntPtr data); //int rpc_port_stub_add_received_event_cb(rpc_port_stub_h h, rpc_port_stub_received_event_cb cb, void* data); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_stub_add_received_event_cb")] internal static extern ErrorCode AddReceivedEventCb(IntPtr handle, ReceivedEventCallback cb, IntPtr data); //int rpc_port_stub_add_privilege(rpc_port_stub_h h, const char *privilege); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_stub_add_privilege")] internal static extern ErrorCode AddPrivilege(IntPtr handle, string privilege); //int rpc_port_stub_set_trusted(rpc_port_stub_h h, const bool trusted); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_stub_set_trusted")] internal static extern ErrorCode SetTrusted(IntPtr handle, bool trusted); //int rpc_port_stub_get_port(rpc_port_stub_h h, rpc_port_port_type_e type, const char* instance, rpc_port_h *port); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_stub_get_port")] internal static extern ErrorCode GetPort(IntPtr handle, PortType t, string instance, out IntPtr port); } internal static partial class Port { //int rpc_port_set_private_sharing_array(rpc_port_h port, const char* paths[], unsigned int size); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_set_private_sharing_array")] internal static extern ErrorCode SetPrivateSharingArray(IntPtr handle, string[] paths, uint size); //int rpc_port_set_private_sharing(rpc_port_h port, const char* path); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_set_private_sharing")] internal static extern ErrorCode SetPrivateSharing(IntPtr handle, string path); //int rpc_port_unset_private_sharing(rpc_port_h port); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_unset_private_sharing")] internal static extern ErrorCode UnsetPrivateSharing(IntPtr handle); //int rpc_port_disconnect(rpc_port_h h); [DllImport(Libraries.RpcPort, EntryPoint = "rpc_port_disconnect")] internal static extern ErrorCode Disconnect(IntPtr handle); } } }
61.75
135
0.717651
[ "Apache-2.0", "MIT" ]
Inhong/TizenFX
src/Tizen.Applications.Common/Interop/Interop.RPCPort.cs
19,019
C#
using System; using System.Collections.Generic; using System.Text; using System.Windows.Media.Imaging; namespace PuzzleTimer.Models { class LangComboBoxItem { public string Name { get; set; } public BitmapImage ImgPath { get; set; } public LangComboBoxItem() { Name = String.Empty; ImgPath = new BitmapImage(); } public LangComboBoxItem(string Name, string ImgPath) { this.Name = Name; this.ImgPath = new BitmapImage(new Uri(ImgPath, UriKind.Relative)); } } }
28.3
79
0.621908
[ "MIT" ]
overflowed-stack/PuzzleTimer
PuzzleTimer/Models/LangComboBoxItem.cs
568
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace GestureSample.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { Rg.Plugins.Popup.Popup.Init(); global::Xamarin.Forms.Forms.Init(); LoadApplication(new App()); return base.FinishedLaunching(app, options); } } }
33.764706
98
0.672474
[ "MIT" ]
JavierVaca/Catan
GestureSample/GestureSample/GestureSample.iOS/AppDelegate.cs
1,150
C#
using System.Collections.Generic; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; using Zenject; namespace Zenject.Tests.Installers { public class TestCompositeInstallerExtensions { TestInstaller _installer1; TestCompositeInstaller _compositeInstaller1; TestCompositeInstaller _compositeInstaller2; TestCompositeInstaller _circularRefCompositeInstaller1; List<TestCompositeInstaller> _parentInstallers1; TestInstaller _dummyInstaller1; TestInstaller _dummyInstaller2; TestInstaller _dummyInstaller3; TestCompositeInstaller _dummyCompositeInstaller1; [SetUp] public void SetUp() { _installer1 = new TestInstaller(); _compositeInstaller1 = new TestCompositeInstaller { _leafInstallers = new List<TestInstaller>() }; _compositeInstaller2 = new TestCompositeInstaller { _leafInstallers = new List<TestInstaller> { _compositeInstaller1, }, }; _circularRefCompositeInstaller1 = new TestCompositeInstaller { _leafInstallers = new List<TestInstaller>() }; _circularRefCompositeInstaller1._leafInstallers.Add(_circularRefCompositeInstaller1); _parentInstallers1 = new List<TestCompositeInstaller> { _compositeInstaller1, }; _dummyInstaller1 = new TestInstaller(); _dummyInstaller2 = new TestInstaller(); _dummyInstaller3 = new TestInstaller(); _dummyCompositeInstaller1 = new TestCompositeInstaller { _leafInstallers = new List<TestInstaller>() }; } [Test] public void TestValidateAsCompositeZeroParent() { var circular = _circularRefCompositeInstaller1; Assert.True(_installer1.ValidateAsComposite()); Assert.True(_compositeInstaller1.ValidateAsComposite()); Assert.False(circular.ValidateAsComposite<IInstaller>()); Assert.False(circular.ValidateAsComposite<TestInstaller>()); // T will be infered as TestCompositeInstaller, so parent will be "ICompositeInstaller<TestCompositeInstaller>>" Assert.True(circular.ValidateAsComposite()); } [Test] public void TestValidateAsCompositeOneParent() { var dummy = _dummyCompositeInstaller1; var circular = _circularRefCompositeInstaller1; Assert.True(_installer1.ValidateAsComposite(dummy)); Assert.True(_installer1.ValidateAsComposite(circular)); Assert.True(_compositeInstaller1.ValidateAsComposite(dummy)); Assert.False(_compositeInstaller1.ValidateAsComposite(_compositeInstaller1)); Assert.False(circular.ValidateAsComposite(dummy)); Assert.False(_compositeInstaller2.ValidateAsComposite(_compositeInstaller1)); } [Test] public void TestValidateAsCompositeTwoParents() { var dummy = _dummyCompositeInstaller1; var circular = _circularRefCompositeInstaller1; Assert.True(_installer1.ValidateAsComposite(dummy, dummy)); Assert.True(_installer1.ValidateAsComposite(circular, circular)); Assert.True(_compositeInstaller1.ValidateAsComposite(dummy, dummy)); Assert.False(_compositeInstaller1.ValidateAsComposite(_compositeInstaller1, dummy)); Assert.False(_compositeInstaller1.ValidateAsComposite(dummy, _compositeInstaller1)); Assert.False(circular.ValidateAsComposite(dummy, dummy)); Assert.False(_compositeInstaller2.ValidateAsComposite(_compositeInstaller1, dummy)); Assert.False(_compositeInstaller2.ValidateAsComposite(dummy, _compositeInstaller1)); } [Test] public void TestValidateAsCompositeThreeParents() { var dummy = _dummyCompositeInstaller1; var circular = _circularRefCompositeInstaller1; Assert.True(_installer1.ValidateAsComposite(dummy, dummy, dummy)); Assert.True(_installer1.ValidateAsComposite(circular, circular, circular)); Assert.True(_compositeInstaller1.ValidateAsComposite(dummy, dummy, dummy)); Assert.False(_compositeInstaller1.ValidateAsComposite(_compositeInstaller1, dummy, dummy)); Assert.False(_compositeInstaller1.ValidateAsComposite(dummy, _compositeInstaller1, dummy)); Assert.False(_compositeInstaller1.ValidateAsComposite(dummy, dummy, _compositeInstaller1)); Assert.False(circular.ValidateAsComposite(dummy, dummy, dummy)); Assert.False(_compositeInstaller2.ValidateAsComposite(_compositeInstaller1, dummy, dummy)); Assert.False(_compositeInstaller2.ValidateAsComposite(dummy, _compositeInstaller1, dummy)); Assert.False(_compositeInstaller2.ValidateAsComposite(dummy, dummy, _compositeInstaller1)); } [Test] public void TestValidateAsCompositeFourParents() { var dummy = _dummyCompositeInstaller1; var circular = _circularRefCompositeInstaller1; Assert.True(_installer1.ValidateAsComposite(dummy, dummy, dummy, dummy)); Assert.True(_installer1.ValidateAsComposite(circular, circular, circular, circular)); Assert.True(_compositeInstaller1.ValidateAsComposite(dummy, dummy, dummy, dummy)); Assert.False(_compositeInstaller1.ValidateAsComposite(_compositeInstaller1, dummy, dummy, dummy)); Assert.False(_compositeInstaller1.ValidateAsComposite(dummy, _compositeInstaller1, dummy, dummy)); Assert.False(_compositeInstaller1.ValidateAsComposite(dummy, dummy, _compositeInstaller1, dummy)); Assert.False(_compositeInstaller1.ValidateAsComposite(dummy, dummy, dummy, _compositeInstaller1)); Assert.False(circular.ValidateAsComposite(dummy, dummy, dummy, dummy)); Assert.False(_compositeInstaller2.ValidateAsComposite(_compositeInstaller1, dummy, dummy, dummy)); Assert.False(_compositeInstaller2.ValidateAsComposite(dummy, _compositeInstaller1, dummy, dummy)); Assert.False(_compositeInstaller2.ValidateAsComposite(dummy, dummy, _compositeInstaller1, dummy)); Assert.False(_compositeInstaller2.ValidateAsComposite(dummy, dummy, dummy, _compositeInstaller1)); } [Test] public void TestValidateLeafInstallers() { Assert.True(_compositeInstaller1.ValidateLeafInstallers()); } [Test] public void TestValidateLeafInstallersWithCircularRef() { Assert.False(_circularRefCompositeInstaller1.ValidateLeafInstallers()); } [Test] public void TestValidateLeafInstallersWithCircularRefLeaf() { _compositeInstaller1._leafInstallers = new List<TestInstaller> { _circularRefCompositeInstaller1, }; Assert.False(_compositeInstaller1.ValidateLeafInstallers()); } [Test] public void TestValidateAsCompositeWithInstaller() { Assert.True(_installer1.ValidateAsComposite(_parentInstallers1)); } [Test] public void TestValidateAsCompositeWithCompositeInstallerWithoutCircularRef() { _parentInstallers1 = new List<TestCompositeInstaller> { new TestCompositeInstaller(), new TestCompositeInstaller(), new TestCompositeInstaller(), }; bool actual = _compositeInstaller1.ValidateAsComposite(_parentInstallers1); Assert.True(actual); } [Test] public void TestValidateAsCompositeWithCompositeInstallerWithoutCircularRefDeep() { var compositeInstaller1 = new TestCompositeInstaller(); var compositeInstaller2 = new TestCompositeInstaller(); var compositeInstaller3 = new TestCompositeInstaller(); compositeInstaller1._leafInstallers = new List<TestInstaller> { _dummyInstaller1, compositeInstaller2, _dummyInstaller2, }; compositeInstaller2._leafInstallers = new List<TestInstaller> { compositeInstaller3, }; compositeInstaller3._leafInstallers = new List<TestInstaller> { _dummyInstaller3, }; bool actual = compositeInstaller1.ValidateAsComposite(_parentInstallers1); Assert.True(actual); } [Test] public void TestValidateAsCompositeWithCompositeInstallerAndParentAsSelf() { _parentInstallers1 = new List<TestCompositeInstaller> { _compositeInstaller1, }; bool actual = _compositeInstaller1.ValidateAsComposite(_parentInstallers1); Assert.False(actual); } [Test] public void TestValidateAsCompositeWithCompositeInstallerAndSelfCircularRef() { _parentInstallers1.Clear(); bool actual = _circularRefCompositeInstaller1.ValidateAsComposite(_parentInstallers1); Assert.False(actual); } [Test] public void TestValidateAsCompositeWithCompositeInstallerAndSelfCircularRefDeep() { var installer1 = new TestCompositeInstaller(); var installer2 = new TestCompositeInstaller(); var installer3 = new TestCompositeInstaller(); installer1._leafInstallers = new List<TestInstaller> { _dummyInstaller1, installer2, _dummyInstaller2, }; installer2._leafInstallers = new List<TestInstaller> { installer3, }; installer3._leafInstallers = new List<TestInstaller> { installer1, // a circular reference _dummyInstaller3, }; bool actual = installer1.ValidateAsComposite(_parentInstallers1); Assert.False(actual); } [Test] public void TestValidateAsCompositeWithCompositeInstallerAndParentCircularRef() { var installer = new TestCompositeInstaller { _leafInstallers = new List<TestInstaller> { _compositeInstaller1, }, }; _parentInstallers1 = new List<TestCompositeInstaller> { _compositeInstaller1, }; bool actual = installer.ValidateAsComposite(_parentInstallers1); Assert.False(actual); } [Test] public void TestValidateAsCompositeWithCompositeInstallerAndParentCircularRefDeep() { var installer1 = new TestCompositeInstaller(); var installer2 = new TestCompositeInstaller(); var installer3 = new TestCompositeInstaller(); installer1._leafInstallers = new List<TestInstaller> { _dummyInstaller1, installer2, _dummyInstaller2, }; installer2._leafInstallers = new List<TestInstaller> { installer3, }; installer3._leafInstallers = new List<TestInstaller> { _compositeInstaller1, // a circular reference _dummyInstaller3, }; bool actual = installer1.ValidateAsComposite(_parentInstallers1); Assert.False(actual); } [Test] public void TestValidateAsCompositeWithCompositeInstallerAndAnotherCircularRef() { var installer1 = new TestCompositeInstaller(); var installer2 = new TestCompositeInstaller(); var installer3 = new TestCompositeInstaller(); installer1._leafInstallers = new List<TestInstaller> { _dummyInstaller1, installer2, _dummyInstaller2, }; installer2._leafInstallers = new List<TestInstaller> { installer3, }; installer3._leafInstallers = new List<TestInstaller> { installer2, // a circular reference _dummyInstaller3, }; bool actual = installer1.ValidateAsComposite(_parentInstallers1); Assert.False(actual); } [Test] public void TestValidateAsCompositeWithCompositeInstallerAndAnotherCircularRefDeep() { var installer1 = new TestCompositeInstaller(); var installer2 = new TestCompositeInstaller(); var installer3 = new TestCompositeInstaller(); var installer4 = new TestCompositeInstaller(); var installer5 = new TestCompositeInstaller(); installer1._leafInstallers = new List<TestInstaller> { _dummyInstaller1, installer2, _dummyInstaller2, }; installer2._leafInstallers = new List<TestInstaller> { installer3, }; installer3._leafInstallers = new List<TestInstaller> { installer4, _dummyInstaller3, }; installer4._leafInstallers = new List<TestInstaller> { installer5, }; installer5._leafInstallers = new List<TestInstaller> { installer3, // a circular reference }; bool actual = installer1.ValidateAsComposite(_parentInstallers1); Assert.False(actual); } [Test] public void TestValidateAsCompositeSavedAllocWithInstaller() { var reusableParentInstallers = new List<ICompositeInstaller<TestInstaller>> { new TestCompositeInstaller(), new TestCompositeInstaller(), new TestCompositeInstaller(), }; Assert.True(_installer1.ValidateAsCompositeSavedAlloc(reusableParentInstallers)); Assert.AreEqual(3, reusableParentInstallers.Count); } [Test] public void TestValidateAsCompositeSavedAllocWithCompositeInstaller() { var reusableParentInstallers = new List<ICompositeInstaller<TestInstaller>> { new TestCompositeInstaller(), new TestCompositeInstaller(), new TestCompositeInstaller(), }; Assert.True(_compositeInstaller2.ValidateAsCompositeSavedAlloc(reusableParentInstallers)); Assert.AreEqual(3, reusableParentInstallers.Count); } [Test] public void TestValidateAsCompositeSavedAllocWithCompositeInstallerSelfInParent() { var reusableParentInstallers = new List<ICompositeInstaller<TestInstaller>> { new TestCompositeInstaller(), _compositeInstaller1, new TestCompositeInstaller(), }; Assert.False(_compositeInstaller1.ValidateAsCompositeSavedAlloc(reusableParentInstallers)); Assert.AreEqual(3, reusableParentInstallers.Count); } [Test] public void TestValidateAsCompositeSavedAllocWithCompositeInstallerParentCircularRef() { var reusableParentInstallers = new List<ICompositeInstaller<TestInstaller>> { new TestCompositeInstaller(), _compositeInstaller1, new TestCompositeInstaller(), }; Assert.False(_compositeInstaller2.ValidateAsCompositeSavedAlloc(reusableParentInstallers)); Assert.AreEqual(3, reusableParentInstallers.Count); } public class TestInstaller : IInstaller { public bool IsEnabled => false; public void InstallBindings() { } } public class TestCompositeInstaller : TestInstaller, ICompositeInstaller<TestInstaller> { public List<TestInstaller> _leafInstallers; public IReadOnlyList<TestInstaller> LeafInstallers => _leafInstallers; } } }
37.887665
125
0.607407
[ "MIT" ]
AgeOfLearning/Extenject
UnityProject/Assets/Plugins/Zenject/Tests/IntegrationTests/Tests/TestCompositeInstallerExtensions/TestCompositeInstallerExtensions.cs
17,201
C#
namespace IRunesWebApp.Controllers { using SIS.Framework.ActionResults.Contracts; using SIS.HTTP.Requests.Contracts; using SIS.HTTP.Response.Contracts; public class HomeController : BaseController { public IActionResult Index() { //if (this.IsAuthenticated(request)) //{ // var username = this.GetUser(request); // this.ViewBag[Username] = username; // this.Authenticated = true; // return this.View("IndexLoggedIn"); //} return this.View(); } } }
26.391304
55
0.556837
[ "MIT" ]
MihailDobrev/SoftUni
C# Web/C# Web Development Basics/09. Introduction To MVC - Lab/IRunesWebApp/Controllers/HomeController.cs
609
C#
using Binance; using CryptoShark.Data; using CryptoShark.Utility; using CryptoShark.Utility.Enum; using Quantum.Framework.GenericProperties.Data; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CryptoShark.Hunting.Data { public class Hunting { public virtual string TypeName { get; } public GenericPropertyCollection Properties { get; set; } public BinanceApi Api { get; private set; } public BinanceApiUser User { get; private set; } public bool TradeEnabled => genericProperties.Get(SettingName.TRADING_ENABLED, false); private GenericPropertyCollection genericProperties; public Hunting() { genericProperties = SettingsHelper.GetGeneralProperties(); } public virtual void Initialize() { Api = new BinanceApi(); var apiKey = genericProperties.Get(SettingName.API_KEY, string.Empty); var secretKey = genericProperties.Get(SettingName.SECRET_KEY, string.Empty); if (!string.IsNullOrEmpty(apiKey) && !string.IsNullOrEmpty(secretKey)) User = new BinanceApiUser(apiKey, secretKey); var jArrayProperties = SettingsHelper.GetJArrayHuntingProperties(TypeName); if (jArrayProperties != null) GenericPropertySerializer.DeserializePropertiesFromArray(Properties, jArrayProperties); } public virtual void StartHunting() { } public virtual void StopHunting() { } public virtual Hunting Clone() { return null; } public async Task<decimal> GetBTCBalance() { var account = await Api.GetAccountInfoAsync(User); foreach (var balance in account.Balances) { if (balance.Free > 0 || balance.Locked > 0) { if (balance.Asset == Asset.BTC.Symbol) return balance.Free; } } return 0; } public async Task<decimal> GetUSDTBalance() { var account = await Api.GetAccountInfoAsync(User); foreach (var balance in account.Balances) { if (balance.Free > 0 || balance.Locked > 0) { if (balance.Asset == Asset.USDT.Symbol) return balance.Free; } } return 0; } public async Task<decimal> GetSymbolBalance(string symbol) { var account = await Api.GetAccountInfoAsync(User); foreach (var balance in account.Balances) { if (balance.Free > 0 || balance.Locked > 0) { if (balance.Asset == symbol) return balance.Free; } } return 0; } public async Task<MarketOrderResult> BuyFromMarket(decimal mainFundQuantity, string symbol) { var success = false; var boughtAll = true; var symbolObj = await BinanceApiHelper.Instance.GetSymbol(symbol); var orders = new List<Order>(); var quantityDecimalPlaces = symbolObj.Quantity.Increment.DecimalPlaces(); var priceDecimalPlaces = symbolObj.Price.Increment.DecimalPlaces(); while (!success || !boughtAll) { var orderBookTop = await Api.GetOrderBookTopAsync(symbol); var amountToBuy = mainFundQuantity / orderBookTop.Bid.Price; amountToBuy = amountToBuy.RoundTo(quantityDecimalPlaces); if (amountToBuy > orderBookTop.Bid.Quantity) { amountToBuy = orderBookTop.Bid.Quantity; boughtAll = false; } if (amountToBuy == 0) break; try { var order = await Api.PlaceAsync(new MarketOrder(User) { Quantity = amountToBuy, Side = OrderSide.Buy, Symbol = symbol }); orders.Add(order); var averagePriceOrder = BinanceApiHelper.Instance.GetAveragePrice(order, symbolObj); mainFundQuantity -= amountToBuy * averagePriceOrder; success = true; } catch (Exception ex) { success = false; } /* if (!success || !boughtAll) await Task.Delay(50); */ } var totalOrderPrice = 0m; var totalOrderQuantity = 0m; foreach (var order in orders) { var totalPrice = 0m; var fills = order.Fills.ToList(); foreach (var fill in fills) totalPrice += fill.Price * fill.Quantity; var averageOrderPrice = totalPrice / order.ExecutedQuantity; totalOrderPrice += averageOrderPrice * order.ExecutedQuantity; totalOrderQuantity += order.ExecutedQuantity; } if (totalOrderQuantity == 0) throw new Exception($"Total order quantitiy is 0"); var averagePrice = (totalOrderPrice / totalOrderQuantity).RoundTo(priceDecimalPlaces); return new MarketOrderResult() { Symbol = symbolObj, AveragePrice = averagePrice, Quantity = totalOrderQuantity.RoundTo(quantityDecimalPlaces) }; } } }
31.532258
104
0.530776
[ "MIT" ]
arcadeindy/Binance-CryptoShark
CryptoShark/Hunting/Data/Hunting.cs
5,867
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 16.05.2021. using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.NotEqual.Complete2__objs.Int64.NullableInt32{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Int64; using T_DATA2 =System.Nullable<System.Int32>; using T_DATA1_U=System.Int64; using T_DATA2_U=System.Int32; //////////////////////////////////////////////////////////////////////////////// //class TestSet_001__fields__01__VV public static class TestSet_001__fields__01__VV { private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2"; private const string c_NameOf__COL_DATA1 ="COL_BIGINT"; private const string c_NameOf__COL_DATA2 ="COL2_INTEGER"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_DATA1)] public T_DATA1 COL_DATA1 { get; set; } [Column(c_NameOf__COL_DATA2)] public T_DATA2 COL_DATA2 { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001__less() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA1_U c_value1=3; const T_DATA2_U c_value2=4; System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => (((object)r.COL_DATA1) /*OP{*/ != /*}OP*/ ((object)r.COL_DATA2)) && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE ((").N("t",c_NameOf__COL_DATA1).T(" <> ").N("t",c_NameOf__COL_DATA2).T(") OR (").N("t",c_NameOf__COL_DATA2).IS_NULL().T(")) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_001__less //----------------------------------------------------------------------- [Test] public static void Test_002__equal() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA1_U c_value1=4; const T_DATA2_U c_value2=4; System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => (((object)r.COL_DATA1) /*OP{*/ != /*}OP*/ ((object)r.COL_DATA2)) && r.TEST_ID==testID); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE ((").N("t",c_NameOf__COL_DATA1).T(" <> ").N("t",c_NameOf__COL_DATA2).T(") OR (").N("t",c_NameOf__COL_DATA2).IS_NULL().T(")) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); }//using db tr.Rollback(); }//using tr }//using cn }//Test_002__equal //----------------------------------------------------------------------- [Test] public static void Test_003__greater() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA1_U c_value1=5; const T_DATA2_U c_value2=4; System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2); var recs=db.testTable.Where(r => (((object)r.COL_DATA1) /*OP{*/ != /*}OP*/ ((object)r.COL_DATA2)) && r.TEST_ID==testID); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (testID, r.TEST_ID.Value); Assert.AreEqual (c_value1, r.COL_DATA1); Assert.AreEqual (c_value2, r.COL_DATA2); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE ((").N("t",c_NameOf__COL_DATA1).T(" <> ").N("t",c_NameOf__COL_DATA2).T(") OR (").N("t",c_NameOf__COL_DATA2).IS_NULL().T(")) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); Assert.AreEqual (1, nRecs); }//using db tr.Rollback(); }//using tr }//using cn }//Test_003__greater //Helper methods -------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA1 valueForColData1, T_DATA2 valueForColData2) { var newRecord=new MyContext.TEST_RECORD(); newRecord.COL_DATA1 =valueForColData1; newRecord.COL_DATA2 =valueForColData2; db.testTable.Add(newRecord); db.SaveChanges(); db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";")); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet_001__fields__01__VV //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.NotEqual.Complete2__objs.Int64.NullableInt32
29.388
203
0.561862
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/NotEqual/Complete2__objs/Int64/NullableInt32/TestSet_001__fields__01__VV.cs
7,349
C#
using CustomerManager.Application.Responses.Identity; using System.Collections.Generic; namespace CustomerManager.Application.Requests.Identity { public class UpdateUserRolesRequest { public string UserId { get; set; } public IList<UserRoleModel> UserRoles { get; set; } } }
27.636364
59
0.736842
[ "MIT" ]
kennyas/CustomerManager
src/Application/Requests/Identity/UpdateUserRolesRequest.cs
306
C#
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #pragma warning disable CS8653 // A default expression introduces a null value for a type parameter. using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Spreads.Collections { // This is based on slow Span<T> implementation. // 1. Working with untyped/unconstrained generic Vec/Vec<T> is simpler // than using ifs everywhere. // 2. There is one if on every path, but if we always use native memory // for blittable types then this if should be predicted perfectly. // Every generic method has it's own compilation for value types // and shared path for reference types, for CPU they are different // branches that are predicted independently. // 3. One day Span<T> could be stored as a field of a normal (not ref) // struct and we will only need to change Vec implementation. /// <summary> /// Typed native or managed vector. /// </summary> /// <remarks>Not thread safe and not safe at all</remarks> [StructLayout(LayoutKind.Auto)] public readonly unsafe struct Vec<T> : IEnumerable<T>// TODO , ISegment<Vec<T>, T> { // // If the Vec was constructed from an object, // // _pinnable = that object (unsafe-casted to a Pinnable<T>) // _byteOffset = offset in bytes from "ref _pinnable.Data" to "ref vec[0]" // // If the Span was constructed from a native pointer, // // _pinnable = null // _byteOffset = the pointer // internal readonly Box<T>? _pinnable; internal readonly IntPtr _byteOffset; private readonly int _length; internal readonly RuntimeTypeId _runtimeTypeId; // padded anyway due to obj usage, no additional mem vs portable span /// <summary> /// Creates a new Vec over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// <exception cref="ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vec(T[]? array) { if (array == null) { this = default; return; // returns default } if (default(T) is null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); _length = array.Length; _pinnable = Unsafe.As<Box<T>>(array); _byteOffset = (IntPtr) TypeHelper<T>.ArrayOffset; _runtimeTypeId = TypeHelper<T>.RuntimeTypeId; } // This is a constructor that takes an array and start but not length. The reason we expose it as a static method as a constructor // is to mirror the actual api shape. This overload of the constructor was removed from the api surface area due to possible // confusion with other overloads that take an int parameter that don't represent a start index. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Vec<T> Create(T[]? array, int start) { if (array == null) { if (start != 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); return default; } if (default(T) is null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); if (unchecked((uint) start) > unchecked((uint) array.Length)) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); IntPtr byteOffset = (IntPtr) Unsafe.Add<T>((byte*) TypeHelper<T>.ArrayOffset, start); int length = array.Length - start; return new Vec<T>(pinnable: Unsafe.As<Box<T>>(array), byteOffset: byteOffset, length: length, runtimeTypeId: TypeHelper<T>.RuntimeTypeId); } /// <summary> /// Creates a new Vec over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the Vec.</param> /// <param name="length">The number of items in the Vec.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vec(T[]? array, int start, int length) { if (array == null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); this = default; return; // returns default } if (default(T) is null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); ThrowHelper.EnsureOffsetLength(start, length, array.Length); _length = length; _pinnable = Unsafe.As<Box<T>>(array); _byteOffset = (IntPtr) Unsafe.Add<T>((byte*) TypeHelper<T>.ArrayOffset, start); _runtimeTypeId = TypeHelper<T>.RuntimeTypeId; } /// <summary> /// Creates a new Vec over the target unmanaged buffer. Clearly this /// is quite dangerous, because we are creating arbitrarily typed T's /// out of a void*-typed block of memory. And the length is not checked. /// But if this creation is correct, then all subsequent uses are correct. /// </summary> /// <param name="pointer">An unmanaged pointer to memory.</param> /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="length"/> is negative. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vec(void* pointer, int length) { if (TypeHelper<T>.IsReferenceOrContainsReferences) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); if (length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); _length = length; _pinnable = null; _byteOffset = new IntPtr(pointer); // negative _runtimeTypeId = TypeHelper<T>.RuntimeTypeId; } // Constructor for internal use only. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Vec(Box<T>? pinnable, IntPtr byteOffset, int length, RuntimeTypeId runtimeTypeId) { Debug.Assert(length >= 0); _length = length; _pinnable = pinnable; _byteOffset = byteOffset; _runtimeTypeId = runtimeTypeId; } /// <summary> /// Returns untyped <see cref="Vec"/> with the same data as this <see cref="Vec{T}"/> /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vec AsVec() { return new Vec(Unsafe.As<Array>(_pinnable), _byteOffset, _length, _runtimeTypeId); } public Span<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (_pinnable == null) return new Span<T>((void*) _byteOffset, _length); return new Span<T>(Unsafe.As<T[]>(_pinnable), (int) (checked((uint) _byteOffset - TypeHelper<T>.ArrayOffset)) / Unsafe.SizeOf<T>(), _length); } } internal Span<T> UnsafeSpan { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (TypeHelper<T>.IsReferenceOrContainsReferences) return new Span<T>(Unsafe.As<T[]>(_pinnable), (int) (checked((uint) _byteOffset - TypeHelper<T>.ArrayOffset)) / Unsafe.SizeOf<T>(), _length); return new Span<T>((void*) _byteOffset, _length); } } /// <summary> /// Get the total number of elements in Vec. /// </summary> public int Length { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _length; } /// <summary> /// Returns true if Vec is created via a pointer. Vec could still be manually pinned if it was created with an array of blittable types. /// </summary> public bool IsPinned { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _pinnable == null; } internal int RuntimeTypeId { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _runtimeTypeId; } /// <summary> /// Fetches the element at the specified index. /// </summary> /// <exception cref="IndexOutOfRangeException"> /// Thrown when the specified index is not in range. /// </exception> public T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (unchecked((uint) index) >= unchecked((uint) _length)) ThrowHelper.ThrowIndexOutOfRangeException(); return DangerousGetUnaligned(index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { if (unchecked((uint) index) >= unchecked((uint) _length)) ThrowHelper.ThrowIndexOutOfRangeException(); DangerousSetUnaligned(index, value); } } /// <summary> /// Returns a reference to a value at index. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref T GetRef(int index) { if (unchecked((uint) index) >= unchecked((uint) _length)) ThrowHelper.ThrowIndexOutOfRangeException(); return ref DangerousGetRef(index); } /// <summary> /// Returns a reference to a value at index without bound checks. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref T DangerousGetRef(int index) { if (_pinnable == null) { return ref Unsafe.Add(ref Unsafe.AsRef<T>((void*) _byteOffset), index); } return ref Unsafe.Add(ref Unsafe.AddByteOffset(ref _pinnable.Value, _byteOffset), index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T DangerousGetUnaligned(int index) { return Unsafe.ReadUnaligned<T>(ref Unsafe.As<T, byte>(ref DangerousGetRef(index))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DangerousSetUnaligned(int index, T value) { Unsafe.WriteUnaligned(ref Unsafe.As<T, byte>(ref DangerousGetRef(index)), value); } /// <summary> /// See <see cref="Vec.UnsafeGetRef{T}"/>. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ref T UnsafeGetRef(IntPtr index) { if (TypeHelper<T>.IsReferenceOrContainsReferences) return ref Unsafe.Add(ref Unsafe.AddByteOffset(ref _pinnable!.Value, _byteOffset), index); return ref Unsafe.Add(ref Unsafe.AsRef<T>((void*) _byteOffset), index); } /// <summary> /// See <see cref="Vec.UnsafeGetRef{T}"/>. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal T UnsafeGetUnaligned(IntPtr index) { return Unsafe.ReadUnaligned<T>(ref Unsafe.As<T, byte>(ref UnsafeGetRef(index))); } /// <summary> /// See <see cref="Vec.UnsafeGetRef{T}"/>. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void UnsafeSetUnaligned(IntPtr index, T value) { Unsafe.WriteUnaligned(ref Unsafe.As<T, byte>(ref UnsafeGetRef(index)), value); } /// <summary> /// Forms a slice out of the given Vec, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vec<T> Slice(int start) { if ((uint) start > (uint) _length) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); IntPtr newOffset = (IntPtr) Unsafe.Add<T>((byte*) _byteOffset, start); int length = _length - start; return new Vec<T>(_pinnable, newOffset, length, _runtimeTypeId); } /// <summary> /// Forms a slice out of the given Vec, beginning at 'start', of given length /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vec<T> Slice(int start, int length) { ThrowHelper.EnsureOffsetLength(start, length, _length); var newOffset = (IntPtr) Unsafe.Add<T>((byte*) _byteOffset, start); return new Vec<T>(_pinnable, newOffset, length, _runtimeTypeId); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Vec<T> DangerousSlice(int start, int length) { IntPtr newOffset = (IntPtr) Unsafe.Add<T>((byte*) _byteOffset, start); return new Vec<T>(_pinnable, newOffset, length, _runtimeTypeId); } /// <summary> /// Copies the contents of this span into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes /// necessary to bridge the gap with APIs written in terms of arrays. /// </summary> public T[] ToArray() { return Span.ToArray(); } /// <summary> /// Returns a reference to the 0th element of the Vec. If the Span is empty, returns null reference. /// It can be used for pinning and is required to support the use of Vec within a fixed statement. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref T GetPinnableReference() { if (_length != 0) { if (_pinnable == null) { return ref Unsafe.AsRef<T>((void*) _byteOffset); } return ref Unsafe.AddByteOffset(ref _pinnable.Value, _byteOffset); } return ref Unsafe.AsRef<T>(source: null); } /// <summary> /// This method is obsolete, use System.Runtime.InteropServices.MemoryMarshal.GetReference instead. /// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element /// would have been stored. Such a reference can be used for pinning but must never be dereferenced. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] [EditorBrowsable(EditorBrowsableState.Never)] internal ref T DangerousGetPinnableReference() { if (_pinnable == null) { return ref Unsafe.AsRef<T>((void*) _byteOffset); } else { return ref Unsafe.AddByteOffset(ref _pinnable.Value, _byteOffset); } } /// <summary> /// Clears the contents of this Vec. /// </summary> public void Clear() { Span.Clear(); } /// <summary> /// Fills the contents of this Vec with the given value. /// </summary> public void Fill(T value) { Span.Fill(value); } internal void FillNonGeneric(object value) { Span.Fill((T) value); } /// <summary> /// Copies the contents of this Vec into destination Vec. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// /// <param name="destination">The Vec to copy items into.</param> /// <exception cref="System.ArgumentException"> /// Thrown when the destination Span is shorter than the source Span. /// </exception> /// </summary> public void CopyTo(Vec<T> destination) { if (!TryCopyTo(destination)) ThrowHelper.ThrowArgumentException_DestinationTooShort(); } /// <summary> /// Copies the contents of this Vec into destination Vec. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// /// <returns>If the destination Vec is shorter than the source Vec, this method /// return false and no data is written to the destination.</returns> /// </summary> /// <param name="destination">The Vec to copy items into.</param> public bool TryCopyTo(Vec<T> destination) { return Span.TryCopyTo(destination.Span); } /// <summary> /// Returns true if left and right point at the same memory and have the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ReferenceEquals(Vec<T> other) { return _length == other._length && Unsafe.AreSame(ref DangerousGetPinnableReference(), ref other.DangerousGetPinnableReference()) && _runtimeTypeId == other._runtimeTypeId; } /// <summary> /// Returns a <see cref="String"/> with the name of the type and the number of elements. /// </summary> public override string ToString() { // ReSharper disable once HeapView.BoxingAllocation return $"Spreads.Vec<{typeof(T).Name}>[{_length}]"; } /// <summary> /// Returns an enumerator over the Slice's entire contents. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { // ReSharper disable once HeapView.BoxingAllocation return GetEnumerator(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { // ReSharper disable once HeapView.BoxingAllocation return GetEnumerator(); } /// <summary> /// A struct-based enumerator, to make fast enumerations possible. /// This isn't designed for direct use, instead see GetEnumerator. /// </summary> public struct Enumerator : IEnumerator<T> { private int _position; // The current position. private Vec<T> _vec; // The slice being enumerated. [MethodImpl(MethodImplOptions.AggressiveInlining)] public Enumerator(Vec<T> vec) { _vec = vec; _position = -1; } public T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _vec.DangerousGetUnaligned(_position); } // ReSharper disable once HeapView.BoxingAllocation object IEnumerator.Current => Current!; public void Dispose() { _vec = default; _position = -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { _position++; return _vec._length > _position; } public void Reset() { _position = -1; } } } /// <summary> /// Untyped native or managed vector. /// </summary> /// <remarks>Not thread safe and not safe at all</remarks> [StructLayout(LayoutKind.Auto)] public readonly unsafe struct Vec : IEnumerable { internal readonly Array? _pinnable; internal readonly IntPtr _byteOffset; private readonly int _length; internal readonly RuntimeTypeId _runtimeTypeId; /// <summary> /// Creates a new Vec over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// <exception cref="ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vec(Array? array) { if (array == null) { this = default; return; // returns default } if (array.Rank != 1 || array.GetLowerBound(0) != 0) ThrowHelper.ThrowInvalidOperationException_ArrayNotVector(); _length = array.Length; _pinnable = array; _byteOffset = TypeHelper.ArrayOffset; _runtimeTypeId = TypeHelper.GetRuntimeTypeInfo(array.GetType().GetElementType()!).RuntimeTypeId; } // This is a constructor that takes an array and start but not length. The reason we expose it as a static method as a constructor // is to mirror the actual api shape. This overload of the constructor was removed from the api surface area due to possible // confusion with other overloads that take an int parameter that don't represent a start index. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Vec Create(Array? array, int start) { if (array == null) { if (start != 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); return default; } if (array.Rank != 1 || array.GetLowerBound(0) != 0) ThrowHelper.ThrowInvalidOperationException_ArrayNotVector(); if (unchecked((uint) start) > unchecked((uint) array.Length)) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); ref readonly var vti = ref TypeHelper.GetRuntimeTypeInfo(array.GetType().GetElementType()!); IntPtr byteOffset = TypeHelper.ArrayOffset + start * vti.ElemSize; int length = array.Length - start; return new Vec(array: array, byteOffset: byteOffset, length: length, runtimeTypeId: vti.RuntimeTypeId); } /// <summary> /// Creates a new Vec over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the Vec.</param> /// <param name="length">The number of items in the Vec.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length). /// </exception> public Vec(Array? array, int start, int length) { if (array == null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); this = default; return; // returns default } if (array.Rank != 1 || array.GetLowerBound(0) != 0) ThrowHelper.ThrowInvalidOperationException_ArrayNotVector(); // ReSharper disable once PossibleNullReferenceException ref readonly var vti = ref TypeHelper.GetRuntimeTypeInfo(array.GetType().GetElementType()!); ThrowHelper.EnsureOffsetLength(start, length, array.Length); _length = length; _pinnable = array; _byteOffset = TypeHelper.ArrayOffset + start * vti.ElemSize; _runtimeTypeId = vti.RuntimeTypeId; } /// <summary> /// Creates a new Vec over the target unmanaged buffer. Clearly this /// is quite dangerous, because we are creating arbitrarily typed T's /// out of a void*-typed block of memory. And the length is not checked. /// But if this creation is correct, then all subsequent uses are correct. /// </summary> /// <param name="pointer">An unmanaged pointer to memory.</param> /// <param name="length">The number of elements the memory contains.</param> /// <param name="elementType">Element type.</param> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="length"/> is negative. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vec(void* pointer, int length, Type? elementType) { if (elementType == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType); ref readonly var vti = ref TypeHelper.GetRuntimeTypeInfo(elementType); if (vti.IsReferenceOrContainsReferences) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(elementType); if (length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); if (pointer == null && length != 0) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.pointer); _pinnable = null; _byteOffset = (IntPtr) pointer!; _length = length; _runtimeTypeId = vti.RuntimeTypeId; } /// <summary> /// An internal helper for creating Vecs. Not for public use. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Vec(Array? array, IntPtr byteOffset, int length, RuntimeTypeId runtimeTypeId) { #if DEBUG Debug.Assert(array == null || runtimeTypeId == TypeHelper.GetRuntimeTypeInfo(array.GetType().GetElementType()!).RuntimeTypeId); #endif _pinnable = array; _byteOffset = byteOffset; _length = length; _runtimeTypeId = runtimeTypeId; } /// <summary> /// Returns typed <see cref="Vec{T}"/> with the same data as this <see cref="Vec"/> /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vec<T> As<T>() { if (TypeHelper<T>.RuntimeTypeId != _runtimeTypeId) ThrowHelper.ThrowVecRuntimeTypeMismatchException(); return new Vec<T>(Unsafe.As<Box<T>>(_pinnable), _byteOffset, _length, _runtimeTypeId); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> AsSpan<T>() { if (TypeHelper<T>.RuntimeTypeId != _runtimeTypeId) ThrowHelper.ThrowVecRuntimeTypeMismatchException(); if (_pinnable == null) return new Span<T>((void*) _byteOffset, _length); return new Span<T>(Unsafe.As<T[]>(_pinnable), (int) (checked((uint) _byteOffset - TypeHelper<T>.ArrayOffset)) / Unsafe.SizeOf<T>(), _length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> UnsafeAsSpan<T>() { Debug.Assert(TypeHelper<T>.RuntimeTypeId != _runtimeTypeId); if (TypeHelper<T>.IsReferenceOrContainsReferences) return new Span<T>(Unsafe.As<T[]>(_pinnable), (int) (checked((uint) _byteOffset - TypeHelper<T>.ArrayOffset)) / Unsafe.SizeOf<T>(), _length); return new Span<T>((void*) _byteOffset, _length); } /// <summary> /// Get the total number of elements in Vec. /// </summary> public int Length { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _length; } /// <summary> /// Returns true if Vec is created via a pointer. Vec could still be manually pinned if it was create with an array of blittable types. /// </summary> public bool IsPinned { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _pinnable == null; } public int RuntimeTypeId { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _runtimeTypeId; } public Type ItemType { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => TypeHelper.GetRuntimeTypeInfo(_runtimeTypeId).Type; } /// <summary> /// Returns the element at the specified index. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public T Get<T>(int index) { if (TypeHelper<T>.RuntimeTypeId != _runtimeTypeId || unchecked((uint) index) >= unchecked((uint) _length)) ThrowWrongLengthOrType<T>(index); return DangerousGetUnaligned<T>(index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Set<T>(int index, T value) { if (TypeHelper<T>.RuntimeTypeId != _runtimeTypeId || unchecked((uint) index) >= unchecked((uint) _length)) ThrowWrongLengthOrType<T>(index); DangerousSetUnaligned(index, value); } /// <summary> /// Get a typed reference to a value at index. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref T GetRef<T>(int index) { if (TypeHelper<T>.RuntimeTypeId != _runtimeTypeId || unchecked((uint) index) >= unchecked((uint) _length)) ThrowWrongLengthOrType<T>(index); return ref DangerousGetRef<T>(index); } [MethodImpl(MethodImplOptions.NoInlining)] private void ThrowWrongLengthOrType<T>(int index) { if (unchecked((uint) index) >= unchecked((uint) _length)) ThrowHelper.ThrowIndexOutOfRangeException(); if (TypeHelper<T>.RuntimeTypeId != _runtimeTypeId) ThrowHelper.ThrowInvalidOperationException("Wrong type in object to T conversion: T is " + typeof(T).Name); } /// <summary> /// Get a typed reference to a value at index without type or bounds check. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref T DangerousGetRef<T>(int index) { if (_pinnable != null) return ref Unsafe.Add(ref Unsafe.AddByteOffset(ref Unsafe.As<Box<T>>(_pinnable)!.Value, _byteOffset), index); return ref Unsafe.Add(ref Unsafe.AsRef<T>((void*) _byteOffset), index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static object? DangerousGetObject<T>(in Vec vec, int index) { // ReSharper disable once HeapView.PossibleBoxingAllocation return vec.DangerousGetRef<T>(index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public object DangerousGetObject(int index) { return TypeHelper.GetRuntimeTypeInfo(_runtimeTypeId).DangerousGetObjectDelegate(this, index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T DangerousGetUnaligned<T>(int index) { return Unsafe.ReadUnaligned<T>(ref Unsafe.As<T, byte>(ref DangerousGetRef<T>(index))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void DangerousSetUnaligned<T>(int index, T value) { // For underlying pointers it just works as casting pointers/refs is simple. // For refs/non-blittable types it's more complicated: // `As<T, byte>` is a simple `ret` instruction, so we get // ``` // unaligned. 0x01 // stobj !!T // ``` // to !!T& // ECMA-335 doesn't say anything about that .unaligned could only // be applied to value types. "The operation of the stobj // instruction can be altered by an immediately preceding unaligned. prefix instruction." // This should work fine: https://github.com/dotnet/runtime/issues/1650 Unsafe.WriteUnaligned(ref Unsafe.As<T, byte>(ref DangerousGetRef<T>(index)), value); } /// <summary> /// This method assumes that types without references are always backed with pinned/native memory (pointer != null). /// The reference check is done via <see cref="TypeHelper{T}.IsReferenceOrContainsReferences"/>. /// This check should be JIT-time constant and the performance should be closer to native <see cref="Span{T}"/>. /// Dangerous-prefixed methods only skip bounds check while this method is *very unsafe*. /// It should be used together with Spreads.Buffers.PrivateMemory. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ref T UnsafeGetRef<T>(IntPtr index) { if (TypeHelper<T>.IsReferenceOrContainsReferences) return ref Unsafe.Add(ref Unsafe.AddByteOffset(ref Unsafe.As<Box<T>>(_pinnable)!.Value, _byteOffset), index); return ref Unsafe.Add(ref Unsafe.AsRef<T>((void*) _byteOffset), index); } /// <summary> /// See <see cref="Vec.UnsafeGetRef{T}"/>. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal T UnsafeGetUnaligned<T>(IntPtr index) { return Unsafe.ReadUnaligned<T>(ref Unsafe.As<T, byte>(ref UnsafeGetRef<T>(index))); } /// <summary> /// See <see cref="Vec.UnsafeGetRef{T}"/>. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void UnsafeSetUnaligned<T>(IntPtr index, T value) { Unsafe.WriteUnaligned(ref Unsafe.As<T, byte>(ref UnsafeGetRef<T>(index)), value); } /// <summary> /// Forms a slice out of the given Vec, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vec Slice(int start) { if ((uint) start > (uint) _length) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); IntPtr newOffset = _byteOffset + start * TypeHelper.GetRuntimeTypeInfo(_runtimeTypeId).ElemSize; int length = _length - start; return new Vec(_pinnable, newOffset, length, _runtimeTypeId); } /// <summary> /// Forms a slice out of the given Vec, beginning at 'start', of given length /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vec Slice(int start, int length) { ThrowHelper.EnsureOffsetLength(start, length, _length); IntPtr newOffset = _byteOffset + start * TypeHelper.GetRuntimeTypeInfo(_runtimeTypeId).ElemSize; return new Vec(_pinnable, newOffset, length, _runtimeTypeId); } /// <summary> /// Checks to see if two Vecs point at the same memory. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public bool ReferenceEquals(Vec other) { return _pinnable == other._pinnable && _byteOffset == other._byteOffset && _length == other._length && _runtimeTypeId == other._runtimeTypeId; } /// <summary> /// Returns a <see cref="String"/> with the name of the type and the number of elements. /// </summary> public override string ToString() { // ReSharper disable once HeapView.BoxingAllocation return $"Spreads.Vec[{_length}] of {ItemType.Name}"; } /// <summary> /// Returns an enumerator over the Slice's entire contents. /// </summary> public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { // ReSharper disable once HeapView.BoxingAllocation return GetEnumerator(); } /// <summary> /// A struct-based enumerator, to make fast enumerations possible. /// This isn't designed for direct use, instead see GetEnumerator. /// </summary> public struct Enumerator : IEnumerator<object> { private Vec _vec; // The slice being enumerated. private int _position; // The current position. [MethodImpl(MethodImplOptions.AggressiveInlining)] public Enumerator(Vec vec) { _vec = vec; _position = -1; } public object Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _vec.DangerousGetObject(_position); } object IEnumerator.Current => Current; [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { _vec = default; _position = -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { return ++_position < _vec.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Reset() { _position = -1; } } } }
40.549852
162
0.592692
[ "MPL-2.0-no-copyleft-exception", "MPL-2.0", "Apache-2.0" ]
Spreads/Spreads
src/Spreads.Core/Collections/Vec.cs
41,079
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MorseCodeUpgraded")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MorseCodeUpgraded")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b8700322-ce1f-4770-8e46-914f7ac0578f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.891892
84
0.749643
[ "MIT" ]
StefanLB/Programming-Fundamentals---September-2017
26. Strings and Regular Expressions - More Exercises/MorseCodeUpgraded/Properties/AssemblyInfo.cs
1,405
C#
using BeckyApi.AddressBook; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AutoAddressBookImpl { public partial class ConfigurationForm : Form { private string beckyDataPath; private string defaultAddressBook; private string defaultGroupPath; public string ChosenAddressBook => ((AbstractAddressBook)cbAddressBook.SelectedItem).Name; public string ChosenGroupPath => (string)cbGroupPath.SelectedItem; public ConfigurationForm() { InitializeComponent(); } public ConfigurationForm(string beckyDataPath, string defaultAddressBook, string defaultGroupPath) : this (){ this.beckyDataPath = beckyDataPath; this.defaultAddressBook = defaultAddressBook; this.defaultGroupPath = defaultGroupPath; } private void btnOk_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.OK; this.Close(); } private void btnCancel_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; this.Close(); } private void ConfigurationForm_Load(object sender, EventArgs e) { AddressBookFactory factory = new AddressBookFactory(beckyDataPath); var addressBooks = factory.GetAddressBooks().ToList(); cbAddressBook.Items.Clear(); foreach (var addrBook in addressBooks) { // disabled item would be nice... if (addrBook.Chooseable) { cbAddressBook.Items.Add(addrBook); } } var selected = addressBooks.FirstOrDefault(x => x.Name == defaultAddressBook); if (selected != null) { cbAddressBook.SelectedItem = selected; if (!selected.GroupPathes.Contains(defaultGroupPath)) { cbGroupPath.Items.Add(defaultGroupPath); } cbGroupPath.SelectedItem = defaultGroupPath; } else { cbGroupPath.Items.Add(defaultGroupPath); cbGroupPath.SelectedItem = defaultGroupPath; if (cbAddressBook.Items.Count == 0) { return; // don't kill myself } // there is one chosen, even if it was wrong cbAddressBook.SelectedIndex = 0; } // Select the default group path, even if it does not exist // for clicking on "OK" without changing should not do nothing wrong } private void cbAddressBook_SelectedIndexChanged(object sender, EventArgs e) { var selectedAddressBook = (AbstractAddressBook)cbAddressBook.SelectedItem; var groupPathes = selectedAddressBook.GroupPathes; cbGroupPath.Items.Clear(); foreach (var groupPath in groupPathes.ToList()) { cbGroupPath.Items.Add(groupPath); } if (groupPathes.Contains(defaultGroupPath)) { cbGroupPath.SelectedItem = defaultGroupPath; cbGroupPath.Enabled = true; } else if (cbGroupPath.Items.Count > 0){ cbGroupPath.SelectedIndex = 0; cbGroupPath.Enabled = true; } else { cbGroupPath.Enabled = false; } } } }
38.083333
118
0.589716
[ "MIT" ]
HeikoStudt/BeckyPlugin.Net
pluginimpl/AutoAddressBookImpl/ConfigurationForm.cs
3,658
C#
using Bing.Maps; using Eqstra.BusinessLogic; using Eqstra.BusinessLogic.DocumentDelivery; using Eqstra.BusinessLogic.Helpers; using Eqstra.DocumentDelivery.UILogic.Helpers; using Microsoft.Practices.Prism.StoreApps; using Microsoft.Practices.Prism.StoreApps.Interfaces; using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.Windows.Input; using Windows.Storage; using Windows.System; namespace Eqstra.DocumentDelivery.UILogic.ViewModels { public class DrivingDirectionPageViewModel : BaseViewModel { private INavigationService _navigationService; private CollectDeliveryTask _deliveryTask; public DrivingDirectionPageViewModel(INavigationService navigationService) : base(navigationService) { _navigationService = navigationService; this._deliveryTask = PersistentData.Instance.CollectDeliveryTask; this.CustomerDetails = PersistentData.Instance.CustomerDetails; GetDirectionsCommand = DelegateCommand<Location>.FromAsyncHandler(async (location) => { var stringBuilder = new StringBuilder("bingmaps:?rtp=pos."); stringBuilder.Append(location.Latitude); stringBuilder.Append("_"); stringBuilder.Append(location.Longitude); stringBuilder.Append("~adr." + Regex.Replace(this.CustomerDetails.Address, "\n", ",")); await Launcher.LaunchUriAsync(new Uri(stringBuilder.ToString())); }); this.GoToDocumentDeliveryCommand = new DelegateCommand(() => { _navigationService.Navigate("CollectionOrDeliveryDetails", string.Empty); }); this.StartDrivingCommand = new DelegateCommand(async () => { this.IsStartDriving = false; this.IsArrived = true; await SqliteHelper.Storage.InsertSingleRecordAsync(new CDDrivingDuration { StartDateTime = DateTime.Now, CaseNumber = ApplicationData.Current.LocalSettings.Values["CaseNumber"].ToString()}); }); this.ArrivedCommand = new DelegateCommand(async () => { if (this._deliveryTask != null) { var CaseNumber = ApplicationData.Current.LocalSettings.Values["CaseNumber"].ToString(); var dd = await SqliteHelper.Storage.GetSingleRecordAsync<CDDrivingDuration>(x => x.CaseNumber.Equals(CaseNumber)); dd.StopDateTime = DateTime.Now; this._deliveryTask.TaskType = BusinessLogic.Enums.CDTaskType.Delivery; await SqliteHelper.Storage.UpdateSingleRecordAsync(this._deliveryTask); await SqliteHelper.Storage.UpdateSingleRecordAsync(dd); } this.IsStartDelivery = true; this.IsStartDriving = false; this.IsArrived = false; }); } async public override void OnNavigatedTo(object navigationParameter, Windows.UI.Xaml.Navigation.NavigationMode navigationMode, Dictionary<string, object> viewModelState) { try { base.OnNavigatedTo(navigationParameter, navigationMode, viewModelState); var dd = await SqliteHelper.Storage.GetSingleRecordAsync<CDDrivingDuration>(x => x.CaseNumber == _deliveryTask.CaseNumber); if (dd != null) { this.IsArrived = dd.StopDateTime == DateTime.MinValue; this.IsStartDelivery = !this.IsArrived; } else { this.IsStartDriving = true; this.IsArrived = false; this.IsStartDelivery = false; } } catch (Exception ex) { AppSettings.Instance.ErrorMessage = ex.Message; } } private CDCustomerDetails customerDetails; public CDCustomerDetails CustomerDetails { get { return customerDetails; } set { SetProperty(ref customerDetails, value); } } public DelegateCommand ArrivedCommand { get; set; } public ICommand GetDirectionsCommand { get; set; } public DelegateCommand GoToDocumentDeliveryCommand { get; set; } public DelegateCommand StartDrivingCommand { get; set; } private bool isStartDelivery; public bool IsStartDelivery { get { return isStartDelivery; } set { SetProperty(ref isStartDelivery, value); } } private bool isStartDriving; public bool IsStartDriving { get { return isStartDriving; } set { SetProperty(ref isStartDriving, value); } } private bool isArrived; public bool IsArrived { get { return isArrived; } set { SetProperty(ref isArrived, value); } } } }
42.041322
206
0.615294
[ "MIT" ]
pithline/FMS
Pithline.FMS.DocumentDelivery.UILogic/ViewModels/DrivingDirectionPageViewModel.cs
5,089
C#
using System.Diagnostics; using PdfSharp.Xps.XpsModel; namespace PdfSharp.Xps.Parsing { partial class XpsParser { /// <summary> /// Parses a StoryFragmentReference element. /// </summary> StoryFragmentReference ParseStoryFragmentReference() { Debug.Assert(reader.Name == ""); bool isEmptyElement = reader.IsEmptyElement; StoryFragmentReference storyFragmentReference = new StoryFragmentReference(); while (MoveToNextAttribute()) { switch (reader.Name) { case "Page": storyFragmentReference.Page = int.Parse(reader.Value); break; case "FragmentName": storyFragmentReference.FragmentName = reader.Value; break; default: UnexpectedAttribute(reader.Name); break; } } MoveToNextElement(); return storyFragmentReference; } } }
25.081081
83
0.615302
[ "MIT" ]
XpsToPdf/XpsToPdf
XpsToPdf/PdfSharp.Xps.Parsing/XpsParser.StoryFragmentReference.cs
930
C#
version https://git-lfs.github.com/spec/v1 oid sha256:7bae5111da8fef850900191ac036ce5e5211294670afe05fea9ddd54832d8ad3 size 5212
32.25
75
0.883721
[ "MIT" ]
kenx00x/ahhhhhhhhhhhh
ahhhhhhhhhh/Library/PackageCache/com.unity.render-pipelines.core@7.1.8/Runtime/Common/XRGraphics.cs
129
C#
// ---------------------------------------------------------------------------------- // Microsoft Developer & Platform Evangelism // // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. // ---------------------------------------------------------------------------------- // The example companies, organizations, products, domain names, // e-mail addresses, logos, people, places, and events depicted // herein are fictitious. No association with any real company, // organization, product, domain name, email address, logo, person, // places, or events is intended or should be inferred. // ---------------------------------------------------------------------------------- namespace Microsoft.Samples.SocialGames.Entities { public class Board { public int Id { get; set; } public string Name { get; set; } public Score[] Scores { get; set; } } }
41.888889
86
0.553492
[ "Apache-2.0" ]
PankajRawat333/MicrosoftAzureTrainingKit
HOLs/HOL-BuildingSocialGame/Source/Assets/SocialGames.Core/Entities/Board.cs
1,133
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections; using System.ComponentModel; using System.Diagnostics; namespace System.Windows.Forms { /// <summary> /// Represents a collection of <see cref='DataGridViewCell'/> objects in the <see cref='DataGridView'/> /// control. /// </summary> [ListBindable(false)] public class DataGridViewCellCollection : BaseCollection, IList { private CollectionChangeEventHandler _onCollectionChanged; private readonly ArrayList _items = new ArrayList(); private readonly DataGridViewRow _owner; int IList.Add(object value) { return Add((DataGridViewCell)value); } void IList.Clear() { Clear(); } bool IList.Contains(object value) { return _items.Contains(value); } int IList.IndexOf(object value) { return _items.IndexOf(value); } void IList.Insert(int index, object value) { Insert(index, (DataGridViewCell)value); } void IList.Remove(object value) { Remove((DataGridViewCell)value); } void IList.RemoveAt(int index) { RemoveAt(index); } bool IList.IsFixedSize { get { return false; } } bool IList.IsReadOnly { get { return false; } } object IList.this[int index] { get { return this[index]; } set { this[index] = (DataGridViewCell)value; } } void ICollection.CopyTo(Array array, int index) { _items.CopyTo(array, index); } int ICollection.Count { get { return _items.Count; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return this; } } IEnumerator IEnumerable.GetEnumerator() { return _items.GetEnumerator(); } public DataGridViewCellCollection(DataGridViewRow dataGridViewRow) { Debug.Assert(dataGridViewRow is not null); _owner = dataGridViewRow; } protected override ArrayList List { get { return _items; } } /// <summary> /// Retrieves the DataGridViewCell with the specified index. /// </summary> public DataGridViewCell this[int index] { get { return (DataGridViewCell)_items[index]; } set { DataGridViewCell dataGridViewCell = value.OrThrowIfNull(); if (dataGridViewCell.DataGridView is not null) { throw new InvalidOperationException(SR.DataGridViewCellCollection_CellAlreadyBelongsToDataGridView); } if (dataGridViewCell.OwningRow is not null) { throw new InvalidOperationException(SR.DataGridViewCellCollection_CellAlreadyBelongsToDataGridViewRow); } if (_owner.DataGridView is not null) { _owner.DataGridView.OnReplacingCell(_owner, index); } DataGridViewCell oldDataGridViewCell = (DataGridViewCell)_items[index]; _items[index] = dataGridViewCell; dataGridViewCell.OwningRow = _owner; dataGridViewCell.State = oldDataGridViewCell.State; if (_owner.DataGridView is not null) { dataGridViewCell.DataGridView = _owner.DataGridView; dataGridViewCell.OwningColumn = _owner.DataGridView.Columns[index]; _owner.DataGridView.OnReplacedCell(_owner, index); } oldDataGridViewCell.DataGridView = null; oldDataGridViewCell.OwningRow = null; oldDataGridViewCell.OwningColumn = null; if (oldDataGridViewCell.ReadOnly) { oldDataGridViewCell.ReadOnlyInternal = false; } if (oldDataGridViewCell.Selected) { oldDataGridViewCell.SelectedInternal = false; } } } /// <summary> /// Retrieves the DataGridViewCell with the specified column name. /// </summary> public DataGridViewCell this[string columnName] { get { DataGridViewColumn dataGridViewColumn = null; if (_owner.DataGridView is not null) { dataGridViewColumn = _owner.DataGridView.Columns[columnName]; } if (dataGridViewColumn is null) { throw new ArgumentException(string.Format(SR.DataGridViewColumnCollection_ColumnNotFound, columnName), nameof(columnName)); } return (DataGridViewCell)_items[dataGridViewColumn.Index]; } set { DataGridViewColumn dataGridViewColumn = null; if (_owner.DataGridView is not null) { dataGridViewColumn = _owner.DataGridView.Columns[columnName]; } if (dataGridViewColumn is null) { throw new ArgumentException(string.Format(SR.DataGridViewColumnCollection_ColumnNotFound, columnName), nameof(columnName)); } this[dataGridViewColumn.Index] = value; } } public event CollectionChangeEventHandler CollectionChanged { add => _onCollectionChanged += value; remove => _onCollectionChanged -= value; } /// <summary> /// Adds a <see cref='DataGridViewCell'/> to this collection. /// </summary> public virtual int Add(DataGridViewCell dataGridViewCell) { if (_owner.DataGridView is not null) { throw new InvalidOperationException(SR.DataGridViewCellCollection_OwningRowAlreadyBelongsToDataGridView); } if (dataGridViewCell.OwningRow is not null) { throw new InvalidOperationException(SR.DataGridViewCellCollection_CellAlreadyBelongsToDataGridViewRow); } return AddInternal(dataGridViewCell); } internal int AddInternal(DataGridViewCell dataGridViewCell) { Debug.Assert(!dataGridViewCell.Selected); int index = _items.Add(dataGridViewCell); dataGridViewCell.OwningRow = _owner; DataGridView dataGridView = _owner.DataGridView; if (dataGridView is not null && dataGridView.Columns.Count > index) { dataGridViewCell.OwningColumn = dataGridView.Columns[index]; } OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, dataGridViewCell)); return index; } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual void AddRange(params DataGridViewCell[] dataGridViewCells) { ArgumentNullException.ThrowIfNull(dataGridViewCells); if (_owner.DataGridView is not null) { throw new InvalidOperationException(SR.DataGridViewCellCollection_OwningRowAlreadyBelongsToDataGridView); } foreach (DataGridViewCell dataGridViewCell in dataGridViewCells) { if (dataGridViewCell is null) { throw new InvalidOperationException(SR.DataGridViewCellCollection_AtLeastOneCellIsNull); } if (dataGridViewCell.OwningRow is not null) { throw new InvalidOperationException(SR.DataGridViewCellCollection_CellAlreadyBelongsToDataGridViewRow); } } // Make sure no two cells are identical int cellCount = dataGridViewCells.Length; for (int cell1 = 0; cell1 < cellCount - 1; cell1++) { for (int cell2 = cell1 + 1; cell2 < cellCount; cell2++) { if (dataGridViewCells[cell1] == dataGridViewCells[cell2]) { throw new InvalidOperationException(SR.DataGridViewCellCollection_CannotAddIdenticalCells); } } } _items.AddRange(dataGridViewCells); foreach (DataGridViewCell dataGridViewCell in dataGridViewCells) { dataGridViewCell.OwningRow = _owner; Debug.Assert(!dataGridViewCell.Selected); } OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null)); } public virtual void Clear() { if (_owner.DataGridView is not null) { throw new InvalidOperationException(SR.DataGridViewCellCollection_OwningRowAlreadyBelongsToDataGridView); } foreach (DataGridViewCell dataGridViewCell in _items) { dataGridViewCell.OwningRow = null; } _items.Clear(); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null)); } public void CopyTo(DataGridViewCell[] array, int index) { _items.CopyTo(array, index); } /// <summary> /// Checks to see if a DataGridViewCell is contained in this collection. /// </summary> public virtual bool Contains(DataGridViewCell dataGridViewCell) { int index = _items.IndexOf(dataGridViewCell); return index != -1; } public int IndexOf(DataGridViewCell dataGridViewCell) { return _items.IndexOf(dataGridViewCell); } public virtual void Insert(int index, DataGridViewCell dataGridViewCell) { if (_owner.DataGridView is not null) { throw new InvalidOperationException(SR.DataGridViewCellCollection_OwningRowAlreadyBelongsToDataGridView); } if (dataGridViewCell.OwningRow is not null) { throw new InvalidOperationException(SR.DataGridViewCellCollection_CellAlreadyBelongsToDataGridViewRow); } Debug.Assert(!dataGridViewCell.ReadOnly); Debug.Assert(!dataGridViewCell.Selected); _items.Insert(index, dataGridViewCell); dataGridViewCell.OwningRow = _owner; OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, dataGridViewCell)); } internal void InsertInternal(int index, DataGridViewCell dataGridViewCell) { Debug.Assert(!dataGridViewCell.Selected); _items.Insert(index, dataGridViewCell); dataGridViewCell.OwningRow = _owner; DataGridView dataGridView = _owner.DataGridView; if (dataGridView is not null && dataGridView.Columns.Count > index) { dataGridViewCell.OwningColumn = dataGridView.Columns[index]; } OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, dataGridViewCell)); } protected void OnCollectionChanged(CollectionChangeEventArgs e) { _onCollectionChanged?.Invoke(this, e); } public virtual void Remove(DataGridViewCell cell) { if (_owner.DataGridView is not null) { throw new InvalidOperationException(SR.DataGridViewCellCollection_OwningRowAlreadyBelongsToDataGridView); } int cellIndex = -1; int itemsCount = _items.Count; for (int i = 0; i < itemsCount; ++i) { if (_items[i] == cell) { cellIndex = i; break; } } if (cellIndex == -1) { throw new ArgumentException(SR.DataGridViewCellCollection_CellNotFound); } else { RemoveAt(cellIndex); } } public virtual void RemoveAt(int index) { if (_owner.DataGridView is not null) { throw new InvalidOperationException(SR.DataGridViewCellCollection_OwningRowAlreadyBelongsToDataGridView); } RemoveAtInternal(index); } internal void RemoveAtInternal(int index) { DataGridViewCell dataGridViewCell = (DataGridViewCell)_items[index]; _items.RemoveAt(index); dataGridViewCell.DataGridView = null; dataGridViewCell.OwningRow = null; if (dataGridViewCell.ReadOnly) { dataGridViewCell.ReadOnlyInternal = false; } if (dataGridViewCell.Selected) { dataGridViewCell.SelectedInternal = false; } OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, dataGridViewCell)); } } }
32.961995
143
0.568711
[ "MIT" ]
AraHaan/winforms
src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewCellCollection.cs
13,879
C#
using System.Collections.Generic; namespace Dynu.API.Model.Domain { public class NameServers : List<string> { } }
13.8
44
0.637681
[ "MIT" ]
JTOne123/Dynu.API
Dynu.API/Model/Domain/NameServers.cs
140
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace ExaminationSystem { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
26.136364
70
0.711304
[ "Apache-2.0" ]
QiYuOr2/exam-system
ExaminationSystem/Global.asax.cs
575
C#
using WDE.Common.Services; using WDE.Module.Attributes; namespace WDE.RemoteSOAP.Providers { [AutoRegister] [SingleInstance] public class ConnectionSettingsProvider : IConnectionSettingsProvider { private readonly IUserSettings userSettings; public ConnectionSettingsProvider(IUserSettings userSettings) { this.userSettings = userSettings; SoapAccess = userSettings.Get(new RemoteSoapAccess())!; } private RemoteSoapAccess SoapAccess { get; } public RemoteSoapAccess GetSettings() => SoapAccess; public void UpdateSettings(string? user, string? password, string? host, int? port) { SoapAccess.User = user; SoapAccess.Password = password; SoapAccess.Host = host; SoapAccess.Port = port; userSettings.Update(SoapAccess); } } }
29.225806
91
0.649007
[ "Unlicense" ]
BAndysc/WoWDatabaseEditor
WDE.RemoteSOAP/Providers/ConnectionSettingsProvider.cs
908
C#
/* * Copyright (c) 2014 Universal Technical Resource Services, Inc. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using ATMLModelLibrary.model.common; using ATMLModelLibrary.model.equipment; namespace ATMLCommonLibrary.controls.common { public partial class ConnectorPinControl : UserControl { private ConnectorPin connectorPin = null; [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ConnectorPin ConnectorPin { get { ControlsToData(); return connectorPin; } set { connectorPin = value; DataToControls(); } } public ConnectorPinControl() { InitializeComponent(); } private void DataToControls() { if (connectorPin != null) { edtBaseIndex.Text = ""+connectorPin.baseIndex; edtCount.Text = ""+connectorPin.count; edtId.Text = connectorPin.ID; edtIncrementBy.Text = ""+connectorPin.incrementBy; edtName.Text = connectorPin.name; edtReplacementCharacter.Text = connectorPin.replacementCharacter; edtName.Focus(); edtName.SelectAll(); } } private void ControlsToData() { if (connectorPin == null ) connectorPin = new ConnectorPin(); connectorPin.baseIndexSpecified = !String.IsNullOrEmpty(edtReplacementCharacter.Text); connectorPin.countSpecified = !String.IsNullOrEmpty(edtCount.Text) && int.Parse(edtCount.Text) > 0; connectorPin.incrementBySpecified = !String.IsNullOrEmpty(edtIncrementBy.Text) && int.Parse(edtIncrementBy.Text) > 0; if (connectorPin.baseIndexSpecified ) connectorPin.baseIndex = connectorPin.baseIndexSpecified ? int.Parse(edtBaseIndex.Text) : 0; if (connectorPin.countSpecified ) connectorPin.count = connectorPin.countSpecified ? int.Parse(edtCount.Text) : 0; if (connectorPin.incrementBySpecified) connectorPin.incrementBy = connectorPin.incrementBySpecified ? int.Parse(edtIncrementBy.Text) : 0; connectorPin.ID = edtId.Text; connectorPin.name = edtName.Text; connectorPin.replacementCharacter = !String.IsNullOrEmpty(edtReplacementCharacter.Text) ? edtReplacementCharacter.Text : null; } } }
40.208333
139
0.63696
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
UtrsSoftware/ATMLWorkBench
ATMLLibraries/ATMLCommonLibrary/controls/connector/ConnectorPinControl.cs
2,897
C#
using System.Text.Json.Serialization; namespace MCDSaveEdit.Save.Models.Profiles { public partial class TowerMissionState { [JsonPropertyName("completedOnce")] public bool CompletedOnce { get; set; } [JsonPropertyName("guid")] public string Guid { get; set; } [JsonPropertyName("livesLost")] public int LivesLost { get; set; } [JsonPropertyName("missionDifficulty")] public MissionDifficulty MissionDifficulty { get; set; } [JsonPropertyName("offeredEnchantmentPoints")] public int OfferedEnchantmentPoints { get; set; } [JsonPropertyName("offeredItems")] public object OfferedItems { get; set; } [JsonPropertyName("ownedDLCs")] public object OwnedDLCs { get; set; } [JsonPropertyName("partsDiscovered")] public int PartsDiscovered { get; set; } [JsonPropertyName("seed")] public int Seed { get; set; } [JsonPropertyName("towerInfo")] public TowerInfo TowerInfo { get; set; } } }
26.625
64
0.635681
[ "MIT" ]
ACKREIK/MCDSaveEdit
MCDSaveEdit/Models/Profiles/TheTower/TowerMissionState.cs
1,067
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; namespace GON.BeatKnuckle { public class StatusHolder : MonoBehaviour { private static StatusHolder instance; public static StatusHolder Instance { get { if (instance == null) instance = FindObjectOfType<StatusHolder>(); return instance; } } /* タグや共通で使うEasingカーブなど * 一箇所でステータス管理するクラス */ [Header("Tag")] [SerializeField] private string _noteTag; public string NoteTag { get { return _noteTag; } } [SerializeField] private string _handTag; public string HandTag { get { return _handTag; } } [Header("Ease")] [SerializeField] private Ease _moveEase; public Ease MoveEase { get { return _moveEase; } } [SerializeField] private Ease _scaleEase; public Ease ScaleEase { get { return _scaleEase; } } [Header("Clap")] [SerializeField] private float _clapSpeed; public float ClapSpeed { get { return _clapSpeed; } } [Header("Debug")] [SerializeField] private bool _isAuto; public bool IsAuto { get { return _isAuto; } } } }
25.673077
82
0.578277
[ "Apache-2.0" ]
GONBEEEproject/VR-Academy-rhythmgame
Assets/Beat_Knuckle/My_Assets/Scripts/Managers/StatusHolder.cs
1,395
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.KeyVault.Models { using Azure; using KeyVault; using Rest; using Rest.Azure; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; /// <summary> /// Defines a page in Azure responses. /// </summary> /// <typeparam name="T">Type of the page content items</typeparam> [JsonObject] public class Page<T> : IPage<T> { /// <summary> /// Gets the link to the next page. /// </summary> [JsonProperty("nextLink")] public string NextPageLink { get; private set; } [JsonProperty("value")] private IList<T> Items{ get; set; } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>A an enumerator that can be used to iterate through the collection.</returns> public IEnumerator<T> GetEnumerator() { return Items == null ? System.Linq.Enumerable.Empty<T>().GetEnumerator() : Items.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>A an enumerator that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
31.8
111
0.615209
[ "MIT" ]
AzureAutomationTeam/azure-sdk-for-net
src/SDKs/KeyVault/dataPlane/Microsoft.Azure.KeyVault/Generated/Models/Page.cs
1,749
C#
namespace XenAdmin.Dialogs { partial class RoleElevationDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RoleElevationDialog)); this.labelBlurb = new System.Windows.Forms.Label(); this.buttonCancel = new System.Windows.Forms.Button(); this.labelCurrentRoleValue = new System.Windows.Forms.Label(); this.labelCurrentRole = new System.Windows.Forms.Label(); this.labelCurrentUserValue = new System.Windows.Forms.Label(); this.labelCurrentUser = new System.Windows.Forms.Label(); this.labelRequiredRole = new System.Windows.Forms.Label(); this.labelRequiredRoleValue = new System.Windows.Forms.Label(); this.TextBoxUsername = new System.Windows.Forms.TextBox(); this.labelPassword = new System.Windows.Forms.Label(); this.labelUserName = new System.Windows.Forms.Label(); this.buttonAuthorize = new System.Windows.Forms.Button(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.labelCurrentAction = new System.Windows.Forms.Label(); this.labelCurrentActionValue = new System.Windows.Forms.Label(); this.labelServer = new System.Windows.Forms.Label(); this.labelServerValue = new System.Windows.Forms.Label(); this.divider = new System.Windows.Forms.GroupBox(); this.labelBlurb2 = new System.Windows.Forms.Label(); this.TextBoxPassword = new System.Windows.Forms.TextBox(); this.panel1 = new System.Windows.Forms.Panel(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // labelBlurb // resources.ApplyResources(this.labelBlurb, "labelBlurb"); this.tableLayoutPanel1.SetColumnSpan(this.labelBlurb, 2); this.labelBlurb.Name = "labelBlurb"; // // buttonCancel // resources.ApplyResources(this.buttonCancel, "buttonCancel"); this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.UseVisualStyleBackColor = true; this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); // // labelCurrentRoleValue // resources.ApplyResources(this.labelCurrentRoleValue, "labelCurrentRoleValue"); this.labelCurrentRoleValue.Name = "labelCurrentRoleValue"; // // labelCurrentRole // resources.ApplyResources(this.labelCurrentRole, "labelCurrentRole"); this.labelCurrentRole.Name = "labelCurrentRole"; // // labelCurrentUserValue // resources.ApplyResources(this.labelCurrentUserValue, "labelCurrentUserValue"); this.labelCurrentUserValue.Name = "labelCurrentUserValue"; // // labelCurrentUser // resources.ApplyResources(this.labelCurrentUser, "labelCurrentUser"); this.labelCurrentUser.Name = "labelCurrentUser"; // // labelRequiredRole // resources.ApplyResources(this.labelRequiredRole, "labelRequiredRole"); this.labelRequiredRole.Name = "labelRequiredRole"; // // labelRequiredRoleValue // resources.ApplyResources(this.labelRequiredRoleValue, "labelRequiredRoleValue"); this.labelRequiredRoleValue.Name = "labelRequiredRoleValue"; // // TextBoxUsername // resources.ApplyResources(this.TextBoxUsername, "TextBoxUsername"); this.TextBoxUsername.Name = "TextBoxUsername"; this.TextBoxUsername.TextChanged += new System.EventHandler(this.TextBoxUsername_TextChanged); // // labelPassword // resources.ApplyResources(this.labelPassword, "labelPassword"); this.labelPassword.Name = "labelPassword"; // // labelUserName // resources.ApplyResources(this.labelUserName, "labelUserName"); this.labelUserName.Name = "labelUserName"; // // buttonAuthorize // resources.ApplyResources(this.buttonAuthorize, "buttonAuthorize"); this.buttonAuthorize.Name = "buttonAuthorize"; this.buttonAuthorize.UseVisualStyleBackColor = true; this.buttonAuthorize.Click += new System.EventHandler(this.buttonAuthorize_Click); // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.pictureBox1, 0, 0); this.tableLayoutPanel1.Controls.Add(this.labelBlurb, 1, 0); this.tableLayoutPanel1.Controls.Add(this.labelCurrentAction, 1, 1); this.tableLayoutPanel1.Controls.Add(this.labelCurrentActionValue, 2, 1); this.tableLayoutPanel1.Controls.Add(this.labelServer, 1, 2); this.tableLayoutPanel1.Controls.Add(this.labelServerValue, 2, 2); this.tableLayoutPanel1.Controls.Add(this.labelCurrentUser, 1, 3); this.tableLayoutPanel1.Controls.Add(this.labelCurrentUserValue, 2, 3); this.tableLayoutPanel1.Controls.Add(this.labelCurrentRole, 1, 4); this.tableLayoutPanel1.Controls.Add(this.labelCurrentRoleValue, 2, 4); this.tableLayoutPanel1.Controls.Add(this.divider, 1, 5); this.tableLayoutPanel1.Controls.Add(this.labelBlurb2, 1, 6); this.tableLayoutPanel1.Controls.Add(this.labelRequiredRole, 1, 7); this.tableLayoutPanel1.Controls.Add(this.labelRequiredRoleValue, 3, 7); this.tableLayoutPanel1.Controls.Add(this.labelUserName, 1, 8); this.tableLayoutPanel1.Controls.Add(this.TextBoxUsername, 2, 8); this.tableLayoutPanel1.Controls.Add(this.labelPassword, 1, 9); this.tableLayoutPanel1.Controls.Add(this.TextBoxPassword, 2, 9); this.tableLayoutPanel1.Controls.Add(this.panel1, 2, 10); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // pictureBox1 // resources.ApplyResources(this.pictureBox1, "pictureBox1"); this.pictureBox1.Name = "pictureBox1"; this.tableLayoutPanel1.SetRowSpan(this.pictureBox1, 2); this.pictureBox1.TabStop = false; // // labelCurrentAction // resources.ApplyResources(this.labelCurrentAction, "labelCurrentAction"); this.labelCurrentAction.Name = "labelCurrentAction"; // // labelCurrentActionValue // resources.ApplyResources(this.labelCurrentActionValue, "labelCurrentActionValue"); this.labelCurrentActionValue.Name = "labelCurrentActionValue"; // // labelServer // resources.ApplyResources(this.labelServer, "labelServer"); this.labelServer.Name = "labelServer"; // // labelServerValue // resources.ApplyResources(this.labelServerValue, "labelServerValue"); this.labelServerValue.Name = "labelServerValue"; // // divider // this.tableLayoutPanel1.SetColumnSpan(this.divider, 2); resources.ApplyResources(this.divider, "divider"); this.divider.Name = "divider"; this.divider.TabStop = false; // // labelBlurb2 // resources.ApplyResources(this.labelBlurb2, "labelBlurb2"); this.tableLayoutPanel1.SetColumnSpan(this.labelBlurb2, 2); this.labelBlurb2.Name = "labelBlurb2"; // // TextBoxPassword // resources.ApplyResources(this.TextBoxPassword, "TextBoxPassword"); this.TextBoxPassword.Name = "TextBoxPassword"; this.TextBoxPassword.UseSystemPasswordChar = true; this.TextBoxPassword.TextChanged += new System.EventHandler(this.TextBoxPassword_TextChanged); // // panel1 // resources.ApplyResources(this.panel1, "panel1"); this.panel1.Controls.Add(this.buttonCancel); this.panel1.Controls.Add(this.buttonAuthorize); this.panel1.Name = "panel1"; // // RoleElevationDialog // this.AcceptButton = this.buttonAuthorize; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.CancelButton = this.buttonCancel; this.Controls.Add(this.tableLayoutPanel1); this.Name = "RoleElevationDialog"; this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.panel1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label labelBlurb; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.Label labelCurrentRoleValue; private System.Windows.Forms.Label labelCurrentRole; private System.Windows.Forms.Label labelCurrentUserValue; private System.Windows.Forms.Label labelCurrentUser; private System.Windows.Forms.Label labelRequiredRole; private System.Windows.Forms.Label labelRequiredRoleValue; internal System.Windows.Forms.TextBox TextBoxUsername; private System.Windows.Forms.Label labelPassword; private System.Windows.Forms.Label labelUserName; private System.Windows.Forms.Button buttonAuthorize; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; internal System.Windows.Forms.TextBox TextBoxPassword; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label labelBlurb2; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.GroupBox divider; private System.Windows.Forms.Label labelCurrentActionValue; private System.Windows.Forms.Label labelCurrentAction; private System.Windows.Forms.Label labelServer; private System.Windows.Forms.Label labelServerValue; } }
49.593496
152
0.612295
[ "BSD-2-Clause" ]
CraigOrendi/xenadmin
XenAdmin/Dialogs/RoleElevationDialog.Designer.cs
12,200
C#
using Sitecore.Web; namespace Cognifide.PowerShell.Core.VersionDecoupling.Interfaces { public interface IUrlHandleWrapper { bool TryGetHandle(out UrlHandle handle); bool DisposeHandle(UrlHandle handle); } }
21.545455
64
0.729958
[ "MIT" ]
orifjonmelibayev/Console
Cognifide.PowerShell/Core/VersionDecoupling/Interfaces/IUrlHandleWrapper.cs
239
C#
//------------------------------------------------------------------------------ // <copyright file="TreeNodeConverter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ namespace System.Windows.Forms { using System.Runtime.Serialization.Formatters; using System.Runtime.Remoting; using System.Runtime.InteropServices; using Microsoft.Win32; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Drawing; using System.Diagnostics; using System.Globalization; using System.Reflection; /// <include file='doc\TreeNodeConverter.uex' path='docs/doc[@for="TreeNodeConverter"]/*' /> /// <devdoc> /// TreeNodeConverter is a class that can be used to convert /// TreeNode objects from one data type to another. Access this /// class through the TypeDescriptor. /// </devdoc> public class TreeNodeConverter : TypeConverter { /// <include file='doc\TreeNodeConverter.uex' path='docs/doc[@for="TreeNodeConverter.CanConvertTo"]/*' /> /// <devdoc> /// <para>Gets a value indicating whether this converter can /// convert an object to the given destination type using the context.</para> /// </devdoc> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(InstanceDescriptor)) { return true; } return base.CanConvertTo(context, destinationType); } /// <include file='doc\TreeNodeConverter.uex' path='docs/doc[@for="TreeNodeConverter.ConvertTo"]/*' /> /// <devdoc> /// Converts the given object to another type. The most common types to convert /// are to and from a string object. The default implementation will make a call /// to ToString on the object if the object is valid and if the destination /// type is string. If this cannot convert to the desitnation type, this will /// throw a NotSupportedException. /// </devdoc> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (destinationType == typeof(InstanceDescriptor) && value is TreeNode) { TreeNode node = (TreeNode)value; MemberInfo info = null; object[] args = null; if (node.ImageIndex == -1 || node.SelectedImageIndex == -1) { if (node.Nodes.Count == 0) { info = typeof(TreeNode).GetConstructor(new Type[] {typeof(string)}); args = new object[] {node.Text}; } else { info = typeof(TreeNode).GetConstructor(new Type[] {typeof(string), typeof(TreeNode[])}); TreeNode[] nodesArray = new TreeNode[node.Nodes.Count]; node.Nodes.CopyTo(nodesArray, 0); args = new object[] {node.Text, nodesArray}; } } else { if (node.Nodes.Count == 0) { info = typeof(TreeNode).GetConstructor(new Type[] { typeof(string), typeof(int), typeof(int)}); args = new object[] { node.Text, node.ImageIndex, node.SelectedImageIndex}; } else { info = typeof(TreeNode).GetConstructor(new Type[] { typeof(string), typeof(int), typeof(int), typeof(TreeNode[])}); TreeNode[] nodesArray = new TreeNode[node.Nodes.Count]; node.Nodes.CopyTo(nodesArray, 0); args = new object[] { node.Text, node.ImageIndex, node.SelectedImageIndex, nodesArray}; } } if (info != null) { return new InstanceDescriptor(info, args); } } return base.ConvertTo(context, culture, value, destinationType); } } }
45.482456
132
0.470781
[ "Unlicense" ]
bestbat/Windows-Server
com/netfx/src/framework/winforms/managed/system/winforms/treenodeconverter.cs
5,185
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.Extensions.Configuration; using EricABP.Configuration; using EricABP.Web; namespace EricABP.EntityFrameworkCore { /* This class is needed to run "dotnet ef ..." commands from command line on development. Not used anywhere else */ public class EricABPDbContextFactory : IDesignTimeDbContextFactory<EricABPDbContext> { public EricABPDbContext CreateDbContext(string[] args) { var builder = new DbContextOptionsBuilder<EricABPDbContext>(); var configuration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder()); EricABPDbContextConfigurer.Configure(builder, configuration.GetConnectionString(EricABPConsts.ConnectionStringName)); return new EricABPDbContext(builder.Options); } } }
38.913043
129
0.757542
[ "MIT" ]
eric33230/EricABP
src/EricABP.EntityFrameworkCore/EntityFrameworkCore/EricABPDbContextFactory.cs
897
C#
using System; using System.IO; using Azure.Storage.Blobs; using CharlieBackend.Core; using System.Threading.Tasks; using Azure.Storage.Blobs.Models; using Microsoft.Extensions.Logging; using CharlieBackend.Business.Services.Interfaces; using CharlieBackend.Core.Entities; namespace CharlieBackend.Business.Services { public class BlobService : IBlobService { private readonly AzureStorageBlobAccount _blobAccount; private readonly ILogger<BlobService> _logger; public BlobService( AzureStorageBlobAccount blobAccount, ILogger<BlobService> logger ) { _blobAccount = blobAccount; _logger = logger; } public string GetUrl(Attachment attachment) { BlobClient blob = new BlobClient ( _blobAccount.ConnectionString, attachment.ContainerName, attachment.FileName ); return blob.Uri.AbsoluteUri; } public async Task<BlobClient> UploadAsync(string fileName, Stream fileStream, bool isPublic = false) { string containerName = Guid.NewGuid().ToString("N"); BlobContainerClient container = new BlobContainerClient(_blobAccount.ConnectionString, containerName); await container.CreateIfNotExistsAsync(); if(isPublic) container.SetAccessPolicy(PublicAccessType.BlobContainer); BlobClient blob = container.GetBlobClient(fileName); _logger.LogInformation("FileName: " + fileName); _logger.LogInformation("Uri: " + blob.Uri); await blob.UploadAsync(fileStream); return blob; } public async Task<BlobDownloadInfo> DownloadAsync(string containerName, string fileName) { BlobClient blob = new BlobClient ( _blobAccount.ConnectionString, containerName, fileName ); BlobDownloadInfo download = await blob.DownloadAsync(); return download; } public async Task<bool> DeleteAsync(string containerName) { BlobContainerClient container = new BlobContainerClient ( _blobAccount.ConnectionString, containerName ); var response = await container.DeleteIfExistsAsync(); return response; } } }
30.314607
108
0.569311
[ "MIT" ]
ITA-Dnipro/WhatBackend
CharlieBackend.Business/Services/BlobService.cs
2,700
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.LanguageClient; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient; using Microsoft.VisualStudio.Threading; using Moq; using Nerdbank.Streams; using Newtonsoft.Json.Linq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using StreamJsonRpc; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Roslyn.VisualStudio.Next.UnitTests.Services { [UseExportProvider] public class LspDiagnosticsTests : AbstractLanguageServerProtocolTests { [Fact] public async Task AddDiagnosticTestAsync() { using var workspace = CreateTestLspServer("", out _).TestWorkspace; var document = workspace.CurrentSolution.Projects.First().Documents.First(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Create a mock that returns a diagnostic for the document. SetupMockWithDiagnostics(diagnosticsMock, document.Id, await CreateMockDiagnosticDataAsync(document, "id").ConfigureAwait(false)); // Publish one document change diagnostic notification -> // 1. doc1 with id. // // We expect one publish diagnostic notification -> // 1. from doc1 with id. var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 1, document).ConfigureAwait(false); var result = Assert.Single(results); Assert.Equal(new Uri(document.FilePath), result.Uri); Assert.Equal("id", result.Diagnostics.Single().Code); } [Fact] public async Task NoDiagnosticsWhenInPullMode() { using var workspace = CreateTestLspServer("", out _).TestWorkspace; workspace.SetOptions(workspace.Options.WithChangedOption( InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Pull)); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Create a mock that returns a diagnostic for the document. SetupMockWithDiagnostics(diagnosticsMock, document.Id, await CreateMockDiagnosticDataAsync(document, "id").ConfigureAwait(false)); var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 0, document).ConfigureAwait(false); Assert.Empty(results); } [Fact] public async Task AddDiagnosticWithMappedFilesTestAsync() { using var workspace = CreateTestLspServer("", out _).TestWorkspace; var document = workspace.CurrentSolution.Projects.First().Documents.First(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Create two mapped diagnostics for the document. SetupMockWithDiagnostics(diagnosticsMock, document.Id, await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id1", document.FilePath + "m1"), ("id2", document.FilePath + "m2")).ConfigureAwait(false)); // Publish one document change diagnostic notification -> // 1. doc1 with id1 = mapped file m1 and id2 = mapped file m2. // // We expect two publish diagnostic notifications -> // 1. from m1 with id1 (from 1 above). // 2. from m2 with id2 (from 1 above). var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, expectedNumberOfCallbacks: 2, document).ConfigureAwait(false); Assert.Equal(2, results.Count); Assert.Equal(new Uri(document.FilePath + "m1"), results[0].Uri); Assert.Equal("id1", results[0].Diagnostics.Single().Code); Assert.Equal(new Uri(document.FilePath + "m2"), results[1].Uri); Assert.Equal("id2", results[1].Diagnostics.Single().Code); } [Fact] public async Task AddDiagnosticWithMappedFileToManyDocumentsTestAsync() { using var workspace = CreateTestLspServer(new string[] { "", "" }, out _).TestWorkspace; var documents = workspace.CurrentSolution.Projects.First().Documents.ToImmutableArray(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Create diagnostic for the first document that has a mapped location. var mappedFilePath = documents[0].FilePath + "m1"; var documentOneDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[0], ("doc1Diagnostic", mappedFilePath)).ConfigureAwait(false); // Create diagnostic for the second document that maps to the same location as the first document diagnostic. var documentTwoDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[1], ("doc2Diagnostic", mappedFilePath)).ConfigureAwait(false); SetupMockWithDiagnostics(diagnosticsMock, documents[0].Id, documentOneDiagnostic); SetupMockWithDiagnostics(diagnosticsMock, documents[1].Id, documentTwoDiagnostic); // Publish two document change diagnostic notifications -> // 1. doc1 with doc1Diagnostic = mapped file m1. // 2. doc2 with doc2Diagnostic = mapped file m1. // // We expect two publish diagnostic notifications -> // 1. from m1 with doc1Diagnostic (from 1 above). // 2. from m1 with doc1Diagnostic and doc2Diagnostic (from 2 above adding doc2Diagnostic to m1). var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 2, documents[0], documents[1]).ConfigureAwait(false); Assert.Equal(2, results.Count); var expectedUri = new Uri(mappedFilePath); Assert.Equal(expectedUri, results[0].Uri); Assert.Equal("doc1Diagnostic", results[0].Diagnostics.Single().Code); Assert.Equal(expectedUri, results[1].Uri); Assert.Equal(2, results[1].Diagnostics.Length); Assert.Contains(results[1].Diagnostics, d => d.Code == "doc1Diagnostic"); Assert.Contains(results[1].Diagnostics, d => d.Code == "doc2Diagnostic"); } [Fact] public async Task RemoveDiagnosticTestAsync() { using var workspace = CreateTestLspServer("", out _).TestWorkspace; var document = workspace.CurrentSolution.Projects.First().Documents.First(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Setup the mock so the first call for a document returns a diagnostic, but the second returns empty. SetupMockDiagnosticSequence(diagnosticsMock, document.Id, await CreateMockDiagnosticDataAsync(document, "id").ConfigureAwait(false), ImmutableArray<DiagnosticData>.Empty); // Publish two document change diagnostic notifications -> // 1. doc1 with id. // 2. doc1 with empty. // // We expect two publish diagnostic notifications -> // 1. from doc1 with id. // 2. from doc1 with empty (from 2 above clearing out diagnostics from doc1). var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 2, document, document).ConfigureAwait(false); Assert.Equal(2, results.Count); Assert.Equal(new Uri(document.FilePath), results[0].Uri); Assert.Equal("id", results[0].Diagnostics.Single().Code); Assert.Equal(new Uri(document.FilePath), results[1].Uri); Assert.True(results[1].Diagnostics.IsEmpty()); Assert.Empty(testAccessor.GetDocumentIdsInPublishedUris()); Assert.Empty(testAccessor.GetFileUrisInPublishDiagnostics()); } [Fact] public async Task RemoveDiagnosticForMappedFilesTestAsync() { using var workspace = CreateTestLspServer("", out _).TestWorkspace; var document = workspace.CurrentSolution.Projects.First().Documents.First(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); var mappedFilePathM1 = document.FilePath + "m1"; var mappedFilePathM2 = document.FilePath + "m2"; // Create two mapped diagnostics for the document on first call. // On the second call, return only the second mapped diagnostic for the document. SetupMockDiagnosticSequence(diagnosticsMock, document.Id, await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id1", mappedFilePathM1), ("id2", mappedFilePathM2)).ConfigureAwait(false), await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id2", mappedFilePathM2)).ConfigureAwait(false)); // Publish three document change diagnostic notifications -> // 1. doc1 with id1 = mapped file m1 and id2 = mapped file m2. // 2. doc1 with just id2 = mapped file m2. // // We expect four publish diagnostic notifications -> // 1. from m1 with id1 (from 1 above). // 2. from m2 with id2 (from 1 above). // 3. from m1 with empty (from 2 above clearing out diagnostics for m1). // 4. from m2 with id2 (from 2 above clearing out diagnostics for m1). var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 4, document, document).ConfigureAwait(false); var mappedFileURIM1 = new Uri(mappedFilePathM1); var mappedFileURIM2 = new Uri(mappedFilePathM2); Assert.Equal(4, results.Count); // First document update. Assert.Equal(mappedFileURIM1, results[0].Uri); Assert.Equal("id1", results[0].Diagnostics.Single().Code); Assert.Equal(mappedFileURIM2, results[1].Uri); Assert.Equal("id2", results[1].Diagnostics.Single().Code); // Second document update. Assert.Equal(mappedFileURIM1, results[2].Uri); Assert.True(results[2].Diagnostics.IsEmpty()); Assert.Equal(mappedFileURIM2, results[3].Uri); Assert.Equal("id2", results[3].Diagnostics.Single().Code); Assert.Single(testAccessor.GetFileUrisForDocument(document.Id), mappedFileURIM2); Assert.Equal("id2", testAccessor.GetDiagnosticsForUriAndDocument(document.Id, mappedFileURIM2).Single().Code); Assert.Empty(testAccessor.GetDiagnosticsForUriAndDocument(document.Id, mappedFileURIM1)); } [Fact] public async Task RemoveDiagnosticForMappedFileToManyDocumentsTestAsync() { using var workspace = CreateTestLspServer(new string[] { "", "" }, out _).TestWorkspace; var documents = workspace.CurrentSolution.Projects.First().Documents.ToImmutableArray(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Create diagnostic for the first document that has a mapped location. var mappedFilePath = documents[0].FilePath + "m1"; var documentOneDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[0], ("doc1Diagnostic", mappedFilePath)).ConfigureAwait(false); // Create diagnostic for the second document that maps to the same location as the first document diagnostic. var documentTwoDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[1], ("doc2Diagnostic", mappedFilePath)).ConfigureAwait(false); // On the first call for this document, return the mapped diagnostic. On the second, return nothing. SetupMockDiagnosticSequence(diagnosticsMock, documents[0].Id, documentOneDiagnostic, ImmutableArray<DiagnosticData>.Empty); // Always return the mapped diagnostic for this document. SetupMockWithDiagnostics(diagnosticsMock, documents[1].Id, documentTwoDiagnostic); // Publish three document change diagnostic notifications -> // 1. doc1 with doc1Diagnostic = mapped file path m1 // 2. doc2 with doc2Diagnostic = mapped file path m1 // 3. doc1 with empty. // // We expect three publish diagnostics -> // 1. from m1 with doc1Diagnostic (triggered by 1 above to add doc1Diagnostic). // 2. from m1 with doc1Diagnostic and doc2Diagnostic (triggered by 2 above to add doc2Diagnostic). // 3. from m1 with just doc2Diagnostic (triggered by 3 above to remove doc1Diagnostic). var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 3, documents[0], documents[1], documents[0]).ConfigureAwait(false); Assert.Equal(3, results.Count); var expectedUri = new Uri(mappedFilePath); Assert.Equal(expectedUri, results[0].Uri); Assert.Equal("doc1Diagnostic", results[0].Diagnostics.Single().Code); Assert.Equal(expectedUri, results[1].Uri); Assert.Equal(2, results[1].Diagnostics.Length); Assert.Contains(results[1].Diagnostics, d => d.Code == "doc1Diagnostic"); Assert.Contains(results[1].Diagnostics, d => d.Code == "doc2Diagnostic"); Assert.Equal(expectedUri, results[2].Uri); Assert.Equal(1, results[2].Diagnostics.Length); Assert.Contains(results[2].Diagnostics, d => d.Code == "doc2Diagnostic"); Assert.Single(testAccessor.GetFileUrisForDocument(documents[1].Id), expectedUri); Assert.Equal("doc2Diagnostic", testAccessor.GetDiagnosticsForUriAndDocument(documents[1].Id, expectedUri).Single().Code); Assert.Empty(testAccessor.GetDiagnosticsForUriAndDocument(documents[0].Id, expectedUri)); } [Fact] public async Task ClearAllDiagnosticsForMappedFilesTestAsync() { using var workspace = CreateTestLspServer("", out _).TestWorkspace; var document = workspace.CurrentSolution.Projects.First().Documents.First(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); var mappedFilePathM1 = document.FilePath + "m1"; var mappedFilePathM2 = document.FilePath + "m2"; // Create two mapped diagnostics for the document on first call. // On the second call, return only empty diagnostics. SetupMockDiagnosticSequence(diagnosticsMock, document.Id, await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id1", mappedFilePathM1), ("id2", mappedFilePathM2)).ConfigureAwait(false), ImmutableArray<DiagnosticData>.Empty); // Publish two document change diagnostic notifications -> // 1. doc1 with id1 = mapped file m1 and id2 = mapped file m2. // 2. doc1 with empty. // // We expect four publish diagnostic notifications - the first two are the two mapped files from 1. // The second two are the two mapped files being cleared by 2. var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 4, document, document).ConfigureAwait(false); var mappedFileURIM1 = new Uri(document.FilePath + "m1"); var mappedFileURIM2 = new Uri(document.FilePath + "m2"); Assert.Equal(4, results.Count); // Document's first update. Assert.Equal(mappedFileURIM1, results[0].Uri); Assert.Equal("id1", results[0].Diagnostics.Single().Code); Assert.Equal(mappedFileURIM2, results[1].Uri); Assert.Equal("id2", results[1].Diagnostics.Single().Code); // Document's second update. Assert.Equal(mappedFileURIM1, results[2].Uri); Assert.True(results[2].Diagnostics.IsEmpty()); Assert.Equal(mappedFileURIM2, results[3].Uri); Assert.True(results[3].Diagnostics.IsEmpty()); Assert.Empty(testAccessor.GetDocumentIdsInPublishedUris()); Assert.Empty(testAccessor.GetFileUrisInPublishDiagnostics()); } [Fact] public async Task ClearAllDiagnosticsForMappedFileToManyDocumentsTestAsync() { using var workspace = CreateTestLspServer(new string[] { "", "" }, out _).TestWorkspace; var documents = workspace.CurrentSolution.Projects.First().Documents.ToImmutableArray(); var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict); // Create diagnostic for the first document that has a mapped location. var mappedFilePath = documents[0].FilePath + "m1"; var documentOneDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[0], ("doc1Diagnostic", mappedFilePath)).ConfigureAwait(false); // Create diagnostic for the second document that maps to the same location as the first document diagnostic. var documentTwoDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[1], ("doc2Diagnostic", mappedFilePath)).ConfigureAwait(false); // On the first call for the documents, return the mapped diagnostic. On the second, return nothing. SetupMockDiagnosticSequence(diagnosticsMock, documents[0].Id, documentOneDiagnostic, ImmutableArray<DiagnosticData>.Empty); SetupMockDiagnosticSequence(diagnosticsMock, documents[1].Id, documentTwoDiagnostic, ImmutableArray<DiagnosticData>.Empty); // Publish four document change diagnostic notifications -> // 1. doc1 with doc1Diagnostic = mapped file m1. // 2. doc2 with doc2Diagnostic = mapped file m1. // 3. doc1 with empty diagnostics. // 4. doc2 with empty diagnostics. // // We expect four publish diagnostics -> // 1. from URI m1 with doc1Diagnostic (triggered by 1 above to add doc1Diagnostic). // 2. from URI m1 with doc1Diagnostic and doc2Diagnostic (triggered by 2 above to add doc2Diagnostic). // 3. from URI m1 with just doc2Diagnostic (triggered by 3 above to clear doc1 diagnostic). // 4. from URI m1 with empty (triggered by 4 above to also clear doc2 diagnostic). var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 4, documents[0], documents[1], documents[0], documents[1]).ConfigureAwait(false); Assert.Equal(4, results.Count); var expectedUri = new Uri(mappedFilePath); Assert.Equal(expectedUri, results[0].Uri); Assert.Equal("doc1Diagnostic", results[0].Diagnostics.Single().Code); Assert.Equal(expectedUri, results[1].Uri); Assert.Equal(2, results[1].Diagnostics.Length); Assert.Contains(results[1].Diagnostics, d => d.Code == "doc1Diagnostic"); Assert.Contains(results[1].Diagnostics, d => d.Code == "doc2Diagnostic"); Assert.Equal(expectedUri, results[2].Uri); Assert.Equal(1, results[2].Diagnostics.Length); Assert.Contains(results[2].Diagnostics, d => d.Code == "doc2Diagnostic"); Assert.Equal(expectedUri, results[3].Uri); Assert.True(results[3].Diagnostics.IsEmpty()); Assert.Empty(testAccessor.GetDocumentIdsInPublishedUris()); Assert.Empty(testAccessor.GetFileUrisInPublishDiagnostics()); } private async Task<(VisualStudioInProcLanguageServer.TestAccessor, List<LSP.PublishDiagnosticParams>)> RunPublishDiagnosticsAsync( TestWorkspace workspace, IDiagnosticService diagnosticService, int expectedNumberOfCallbacks, params Document[] documentsToPublish) { var (clientStream, serverStream) = FullDuplexStream.CreatePair(); var languageServer = CreateLanguageServer(serverStream, serverStream, workspace, diagnosticService); // Notification target for tests to receive the notification details var callback = new Callback(expectedNumberOfCallbacks); using var jsonRpc = new JsonRpc(clientStream, clientStream, callback) { ExceptionStrategy = ExceptionProcessing.ISerializable, }; // The json rpc messages won't necessarily come back in order by default. // So use a synchronization context to preserve the original ordering. // https://github.com/microsoft/vs-streamjsonrpc/blob/bc970c61b90db5db135a1b3d1c72ef355c2112af/doc/resiliency.md#when-message-order-is-important jsonRpc.SynchronizationContext = new RpcOrderPreservingSynchronizationContext(); jsonRpc.StartListening(); // Triggers language server to send notifications. await languageServer.ProcessDiagnosticUpdatedBatchAsync( diagnosticService, documentsToPublish.SelectAsArray(d => d.Id), CancellationToken.None); // Waits for all notifications to be received. await callback.CallbackCompletedTask.ConfigureAwait(false); return (languageServer.GetTestAccessor(), callback.Results); static VisualStudioInProcLanguageServer CreateLanguageServer(Stream inputStream, Stream outputStream, TestWorkspace workspace, IDiagnosticService mockDiagnosticService) { var dispatcherFactory = workspace.ExportProvider.GetExportedValue<RequestDispatcherFactory>(); var listenerProvider = workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>(); var lspWorkspaceRegistrationService = workspace.ExportProvider.GetExportedValue<ILspWorkspaceRegistrationService>(); var capabilitiesProvider = workspace.ExportProvider.GetExportedValue<DefaultCapabilitiesProvider>(); var jsonRpc = new JsonRpc(new HeaderDelimitedMessageHandler(outputStream, inputStream)) { ExceptionStrategy = ExceptionProcessing.ISerializable, }; var globalOptions = workspace.GetService<IGlobalOptionService>(); var languageServer = new VisualStudioInProcLanguageServer( dispatcherFactory, jsonRpc, capabilitiesProvider, lspWorkspaceRegistrationService, globalOptions, listenerProvider, NoOpLspLogger.Instance, mockDiagnosticService, ProtocolConstants.RoslynLspLanguages, clientName: null, userVisibleServerName: string.Empty, telemetryServerTypeName: string.Empty); jsonRpc.StartListening(); return languageServer; } } private void SetupMockWithDiagnostics(Mock<IDiagnosticService> diagnosticServiceMock, DocumentId documentId, ImmutableArray<DiagnosticData> diagnostics) { diagnosticServiceMock.Setup(d => d.GetPushDiagnosticsAsync( It.IsAny<Workspace>(), It.IsAny<ProjectId>(), documentId, It.IsAny<object>(), It.IsAny<bool>(), It.IsAny<Option2<DiagnosticMode>>(), It.IsAny<CancellationToken>())).Returns(new ValueTask<ImmutableArray<DiagnosticData>>(diagnostics)); } private void SetupMockDiagnosticSequence(Mock<IDiagnosticService> diagnosticServiceMock, DocumentId documentId, ImmutableArray<DiagnosticData> firstDiagnostics, ImmutableArray<DiagnosticData> secondDiagnostics) { diagnosticServiceMock.SetupSequence(d => d.GetPushDiagnosticsAsync( It.IsAny<Workspace>(), It.IsAny<ProjectId>(), documentId, It.IsAny<object>(), It.IsAny<bool>(), It.IsAny<Option2<DiagnosticMode>>(), It.IsAny<CancellationToken>())) .Returns(new ValueTask<ImmutableArray<DiagnosticData>>(firstDiagnostics)) .Returns(new ValueTask<ImmutableArray<DiagnosticData>>(secondDiagnostics)); } private async Task<ImmutableArray<DiagnosticData>> CreateMockDiagnosticDataAsync(Document document, string id) { var descriptor = new DiagnosticDescriptor(id, "", "", "", DiagnosticSeverity.Error, true); var location = Location.Create(await document.GetRequiredSyntaxTreeAsync(CancellationToken.None).ConfigureAwait(false), new TextSpan()); return ImmutableArray.Create(DiagnosticData.Create(Diagnostic.Create(descriptor, location), document)); } private async Task<ImmutableArray<DiagnosticData>> CreateMockDiagnosticDatasWithMappedLocationAsync(Document document, params (string diagnosticId, string mappedFilePath)[] diagnostics) { var tree = await document.GetRequiredSyntaxTreeAsync(CancellationToken.None).ConfigureAwait(false); return diagnostics.Select(d => CreateMockDiagnosticDataWithMappedLocation(document, tree, d.diagnosticId, d.mappedFilePath)).ToImmutableArray(); static DiagnosticData CreateMockDiagnosticDataWithMappedLocation(Document document, SyntaxTree tree, string id, string mappedFilePath) { var descriptor = new DiagnosticDescriptor(id, "", "", "", DiagnosticSeverity.Error, true); var location = Location.Create(tree, new TextSpan()); var diagnostic = Diagnostic.Create(descriptor, location); return new DiagnosticData(diagnostic.Id, diagnostic.Descriptor.Category, null, null, diagnostic.Severity, diagnostic.DefaultSeverity, diagnostic.Descriptor.IsEnabledByDefault, diagnostic.WarningLevel, diagnostic.Descriptor.ImmutableCustomTags(), diagnostic.Properties, document.Project.Id, GetDataLocation(document, mappedFilePath), additionalLocations: default, document.Project.Language, diagnostic.Descriptor.Title.ToString(), diagnostic.Descriptor.Description.ToString(), null, diagnostic.IsSuppressed); } static DiagnosticDataLocation GetDataLocation(Document document, string mappedFilePath) => new DiagnosticDataLocation(document.Id, originalFilePath: document.FilePath, mappedFilePath: mappedFilePath); } /// <summary> /// Synchronization context to preserve ordering of the RPC messages /// Adapted from https://dev.azure.com/devdiv/DevDiv/VS%20Cloud%20Kernel/_git/DevCore?path=%2Fsrc%2Fclr%2FMicrosoft.ServiceHub.Framework%2FServiceRpcDescriptor%2BRpcOrderPreservingSynchronizationContext.cs /// https://github.com/microsoft/vs-streamjsonrpc/issues/440 tracks exposing functionality so we don't need to copy this. /// </summary> private class RpcOrderPreservingSynchronizationContext : SynchronizationContext, IDisposable { /// <summary> /// The queue of work to execute. /// </summary> private readonly AsyncQueue<(SendOrPostCallback, object?)> _queue = new AsyncQueue<(SendOrPostCallback, object?)>(); public RpcOrderPreservingSynchronizationContext() { // Process the work in the background. this.ProcessQueueAsync().Forget(); } public override void Post(SendOrPostCallback d, object? state) => this._queue.Enqueue((d, state)); public override void Send(SendOrPostCallback d, object? state) => throw new NotSupportedException(); public override SynchronizationContext CreateCopy() => throw new NotSupportedException(); /// <summary> /// Causes this <see cref="SynchronizationContext"/> to reject all future posted work and /// releases the queue processor when it is empty. /// </summary> public void Dispose() => this._queue.Complete(); /// <summary> /// Executes queued work on the thread-pool, one at a time. /// Don't catch exceptions - let them bubble up to fail the test. /// </summary> private async Task ProcessQueueAsync() { while (!this._queue.IsCompleted) { var work = await this._queue.DequeueAsync().ConfigureAwait(false); work.Item1(work.Item2); } } } private class Callback { private readonly TaskCompletionSource<object?> _callbackCompletedTaskSource = new(); /// <summary> /// Task that can be awaited for the all callbacks to complete. /// </summary> public Task CallbackCompletedTask => _callbackCompletedTaskSource.Task; /// <summary> /// Serialized results of all publish diagnostic notifications received by this callback. /// </summary> public List<LSP.PublishDiagnosticParams> Results { get; } /// <summary> /// Lock to guard concurrent callbacks. /// </summary> private readonly object _lock = new(); /// <summary> /// The expected number of times this callback should be hit. /// Used in conjunction with <see cref="_currentNumberOfCallbacks"/> /// to determine if the callbacks are complete. /// </summary> private readonly int _expectedNumberOfCallbacks; /// <summary> /// The current number of callbacks that this callback has been hit. /// </summary> private int _currentNumberOfCallbacks; public Callback(int expectedNumberOfCallbacks) { Results = new List<LSP.PublishDiagnosticParams>(); _expectedNumberOfCallbacks = expectedNumberOfCallbacks; _currentNumberOfCallbacks = 0; if (expectedNumberOfCallbacks == 0) _callbackCompletedTaskSource.SetResult(null); } [JsonRpcMethod(LSP.Methods.TextDocumentPublishDiagnosticsName)] public Task OnDiagnosticsPublished(JToken input) { lock (_lock) { _currentNumberOfCallbacks++; Contract.ThrowIfTrue(_currentNumberOfCallbacks > _expectedNumberOfCallbacks, "received too many callbacks"); var diagnosticParams = input.ToObject<LSP.PublishDiagnosticParams>(); Assumes.Present(diagnosticParams); Results.Add(diagnosticParams); if (_currentNumberOfCallbacks == _expectedNumberOfCallbacks) _callbackCompletedTaskSource.SetResult(null); return Task.CompletedTask; } } } private class TestLanguageClient : AbstractInProcLanguageClient { public TestLanguageClient() : base(null!, null!, null, null!, null!, null!, null!, null) { } protected override ImmutableArray<string> SupportedLanguages => ProtocolConstants.RoslynLspLanguages; public override string Name => nameof(LspDiagnosticsTests); public override bool ShowNotificationOnInitializeFailed => false; public override LSP.ServerCapabilities GetCapabilities(LSP.ClientCapabilities clientCapabilities) => new(); } } }
53.1584
213
0.653203
[ "MIT" ]
NewellClark/roslyn
src/VisualStudio/Core/Test.Next/Services/LspDiagnosticsTests.cs
33,226
C#
using System; using System.Globalization; namespace Microsoft.Msagl.Core.Geometry.Curves { /// <summary> /// Contains the result of the intersection of two ICurves. /// </summary> public class IntersectionInfo { /* The following conditions should hold: * X=seg0[par0]=seg1[par1] */ double par0, par1; Point x; ICurve seg0, seg1; /// <summary> /// the parameter on the first curve /// </summary> public double Par0 { get { return par0; } set { par0 = value; } } /// <summary> /// the parameter on the second curve /// </summary> public double Par1 { get { return par1; } set { par1 = value; } } /// <summary> /// the intersection point /// </summary> public Point IntersectionPoint { get { return x; } set { x = value; } } /// <summary> /// the segment of the first curve where the intersection point belongs /// </summary> public ICurve Segment0 { get { return seg0; } set { seg0=value; } } /// <summary> /// the segment of the second curve where the intersection point belongs /// </summary> public ICurve Segment1 { get { return seg1; } set { seg1 = value; } } /// <summary> /// the constructor /// </summary> /// <param name="pr0"></param> /// <param name="pr1"></param> /// <param name="x"></param> /// <param name="s0"></param> /// <param name="s1"></param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object,System.Object)")] internal IntersectionInfo(double pr0, double pr1, Point x, ICurve s0, ICurve s1) { par0 = pr0; par1 = pr1; this.x = x; seg0 = s0; seg1 = s1; #if DETAILED_DEBUG System.Diagnostics.Debug.Assert(ApproximateComparer.Close(x, s0[pr0], ApproximateComparer.IntersectionEpsilon*10), string.Format("intersection not at curve[param]; x = {0}, s0[pr0] = {1}, diff = {2}", x, s0[pr0], x - s0[pr0])); System.Diagnostics.Debug.Assert(ApproximateComparer.Close(x, s1[pr1], ApproximateComparer.IntersectionEpsilon*10), string.Format("intersection not at curve[param]; x = {0}, s1[pr1] = {1}, diff = {2}", x, s1[pr1], x - s1[pr1])); #endif } /// <summary> /// /// </summary> /// <returns></returns> public override string ToString() { return String.Format(CultureInfo.InvariantCulture, "XX({0} {1} {2})", par0, par1, x); } } }
32.522222
210
0.532627
[ "MIT" ]
0xbeecaffe/MSAGL
GraphLayout/MSAGL/Core/Geometry/Curves/IntersectionInfo.cs
2,927
C#
/* * Copyright(c) 2017 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Runtime.InteropServices; using Tizen.NUI.BaseComponents; using System.ComponentModel; namespace Tizen.NUI { /// <summary> /// The StyleManager informs applications of the system theme change, and supports application theme change at runtime.<br /> /// Applies various styles to controls using the properties system.<br /> /// On theme change, it automatically updates all controls, then raises a event to inform the application.<br /> /// If the application wants to customize the theme, RequestThemeChange needs to be called.<br /> /// It provides the path to the application resource root folder, from there the filename can be specified along with any subfolders, for example, Images, Models, etc.<br /> /// </summary> /// <since_tizen> 3 </since_tizen> public class StyleManager : BaseHandle { private global::System.Runtime.InteropServices.HandleRef swigCPtr; internal StyleManager(global::System.IntPtr cPtr, bool cMemoryOwn) : base(NDalicPINVOKE.StyleManager_SWIGUpcast(cPtr), cMemoryOwn) { swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(StyleManager obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } private static readonly StyleManager instance = StyleManager.Get(); /// <summary> /// Gets the singleton of the StyleManager object. /// </summary> /// <since_tizen> 5 </since_tizen> public static StyleManager Instance { get { return instance; } } /// <summary> /// Style changed event arguments. /// </summary> /// <since_tizen> 3 </since_tizen> public class StyleChangedEventArgs : EventArgs { private StyleManager _styleManager; private StyleChangeType _styleChange; /// <summary> /// StyleManager. /// </summary> /// <since_tizen> 3 </since_tizen> public StyleManager StyleManager { get { return _styleManager; } set { _styleManager = value; } } /// <summary> /// StyleChange - contains the style change information (default font changed or /// default font size changed or theme has changed).<br /> /// </summary> /// <since_tizen> 3 </since_tizen> public StyleChangeType StyleChange { get { return _styleChange; } set { _styleChange = value; } } } [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void StyleChangedCallbackDelegate(IntPtr styleManager, Tizen.NUI.StyleChangeType styleChange); private EventHandler<StyleChangedEventArgs> _styleManagerStyleChangedEventHandler; private StyleChangedCallbackDelegate _styleManagerStyleChangedCallbackDelegate; /// <summary> /// An event for the StyleChanged signal which can be used to subscribe or unsubscribe the /// event handler provided by the user.<br /> /// The StyleChanged signal is emitted after the style (for example, theme or font change) has changed /// and the controls have been informed.<br /> /// </summary> /// <since_tizen> 3 </since_tizen> public event EventHandler<StyleChangedEventArgs> StyleChanged { add { if (_styleManagerStyleChangedEventHandler == null) { _styleManagerStyleChangedCallbackDelegate = (OnStyleChanged); StyleChangedSignal().Connect(_styleManagerStyleChangedCallbackDelegate); } _styleManagerStyleChangedEventHandler += value; } remove { _styleManagerStyleChangedEventHandler -= value; if (_styleManagerStyleChangedEventHandler == null && StyleChangedSignal().Empty() == false) { StyleChangedSignal().Disconnect(_styleManagerStyleChangedCallbackDelegate); } } } // Callback for StyleManager StyleChangedsignal private void OnStyleChanged(IntPtr styleManager, StyleChangeType styleChange) { StyleChangedEventArgs e = new StyleChangedEventArgs(); // Populate all members of "e" (StyleChangedEventArgs) with real data. e.StyleManager = Registry.GetManagedBaseHandleFromNativePtr(styleManager) as StyleManager; e.StyleChange = styleChange; if (_styleManagerStyleChangedEventHandler != null) { //Here we send all data to user event handlers. _styleManagerStyleChangedEventHandler(this, e); } } /// <summary> /// Creates a StyleManager handle.<br /> /// This can be initialized with StyleManager::Get().<br /> /// </summary> /// <since_tizen> 3 </since_tizen> public StyleManager() : this(NDalicPINVOKE.new_StyleManager(), true) { if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets the singleton of StyleManager object. /// </summary> /// <returns>A handle to the StyleManager control.</returns> /// <since_tizen> 3 </since_tizen> public static StyleManager Get() { StyleManager ret = new StyleManager(NDalicPINVOKE.StyleManager_Get(), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Applies a new theme to the application.<br /> /// This will be merged on the top of the default Toolkit theme.<br /> /// If the application theme file doesn't style all controls that the /// application uses, then the default Toolkit theme will be used /// instead for those controls.<br /> /// </summary> /// <param name="themeFile">A relative path is specified for style theme.</param> /// <since_tizen> 3 </since_tizen> public void ApplyTheme(string themeFile) { NDalicPINVOKE.StyleManager_ApplyTheme(swigCPtr, themeFile); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Applies the default Toolkit theme. /// </summary> /// <since_tizen> 3 </since_tizen> public void ApplyDefaultTheme() { NDalicPINVOKE.StyleManager_ApplyDefaultTheme(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Sets a constant for use when building styles. /// </summary> /// <param name="key">The key of the constant.</param> /// <param name="value">The value of the constant.</param> /// <since_tizen> 3 </since_tizen> public void AddConstant(string key, PropertyValue value) { NDalicPINVOKE.StyleManager_SetStyleConstant(swigCPtr, key, PropertyValue.getCPtr(value)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Returns the style constant set for a specific key. /// </summary> /// <param name="key">The key of the constant.</param> /// <param name="valueOut">The value of the constant if it exists.</param> /// <returns></returns> /// <since_tizen> 3 </since_tizen> public bool GetConstant(string key, PropertyValue valueOut) { bool ret = NDalicPINVOKE.StyleManager_GetStyleConstant(swigCPtr, key, PropertyValue.getCPtr(valueOut)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Applies the specified style to the control. /// </summary> /// <param name="control">The control to which to apply the style.</param> /// <param name="jsonFileName">The name of the JSON style file to apply.</param> /// <param name="styleName">The name of the style within the JSON file to apply.</param> /// <since_tizen> 3 </since_tizen> public void ApplyStyle(View control, string jsonFileName, string styleName) { NDalicPINVOKE.StyleManager_ApplyStyle(swigCPtr, View.getCPtr(control), jsonFileName, styleName); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } internal StyleChangedSignal StyleChangedSignal() { StyleChangedSignal ret = new StyleChangedSignal(NDalicPINVOKE.StyleManager_StyleChangedSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } } }
41.546185
177
0.61827
[ "Apache-2.0" ]
sameerppradhan/TizenFX
src/Tizen.NUI/src/public/StyleManager.cs
10,345
C#
using System; using System.Collections; using System.Collections.Generic; using StrawberryShake; namespace CoolStore.UI.Blazor { [System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public interface IGetProducts { IReadOnlyList<ICatalogProductDto> Products { get; } } }
22.285714
72
0.737179
[ "MIT" ]
Magicianred/coolstore-moduliths
src/CoolStore.UI.Blazor/GraphQL/Generated/IGetProducts.cs
314
C#