text
stringlengths
13
6.01M
using UnityEngine; using System.Collections; public class SkyOrbitor : MonoBehaviour { /// <summary> /// Denne funksjonen roterer et objekt på Y aksen til gitt fart /// Det gjør at objekter knyttet til dette objektet som child roterer i en omkrets tilsvarende (avstand til parent center * 2Pi) /// Altså jo lengere unna objektet fra senter jo større fart får det. /// Denne classen er brukt på skyene /// </summary> //minste farten på rotasjonen public float minFart = 0.2f; //Maks fart på rotasjonen public float maksFart = 600f; //Utgjevnings fart public float smoothTime = 0.3f; //Startpunkt for natt private float startNatt = 0.001f; //Startpunkt for dag private float StartDag = 0.999f; //Farten som det økes med private float yVelocity = 0.0f; //Halvveis i faseskiftet private float midten = 55f; public float rotSpeed; //Setter fart på rotering //Verdien hentet fra skyboxen som sier hvor langt i faseskiftet man er kommet og om det er satt igang private float faseSkifte; void Start (){ rotSpeed = minFart; } void Update () { //Sjekker om faseskiftet har startet dersom > eller < enn Start natt eller Start dag faseSkifte = RenderSettings.skybox.GetFloat ("_Blend"); //Hvis den ligger faseskiftet er < 1 og > 0 //Reduseres og økes farten etter hvor lang man har kommet. if (faseSkifte > startNatt && faseSkifte < StartDag) { if (faseSkifte < midten) { rotSpeed = Mathf.SmoothDamp (minFart, maksFart, ref yVelocity, smoothTime); transform.Rotate (0, rotSpeed * Time.deltaTime, 0);//Roter på Yaksen } else if (faseSkifte > midten) { rotSpeed = Mathf.SmoothDamp (maksFart, minFart, ref yVelocity, smoothTime); transform.Rotate (0, rotSpeed * Time.deltaTime, 0);//Roter på Yaksen } } } }
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== // // // Notes: // // ============================================================================ // using System; namespace EnhancedEditor { /// <summary> /// Class that exist only for the use of its <see cref="ScriptingDefineSymbolAttribute"/>, /// allowing to enable / disable the <see cref="EnhancedLogger"/> from the BuildPipeline window. /// </summary> [Serializable] [ScriptingDefineSymbol("ENHANCED_LOGGER", "Enhanced Logger")] [ScriptingDefineSymbol("ENHANCED_LOGS", "Development / Debug Logs")] internal sealed class EnhancedLoggerScriptingSymbol { } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="WizardController.cs" company="Soloplan GmbH"> // Copyright (c) Soloplan GmbH. All rights reserved. // Licensed under the MIT License. See License-file in the project root for license information. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Soloplan.WhatsON.GUI.Configuration.Wizard { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using MaterialDesignThemes.Wpf; using NLog; using Soloplan.WhatsON.Composition; using Soloplan.WhatsON.Configuration; using Soloplan.WhatsON.GUI.Common.VisualConfig; using Soloplan.WhatsON.GUI.Configuration.ViewModel; using Soloplan.WhatsON.Model; /// <summary> /// Controls the execution of a wizard which allows to create or edit a project connection. /// </summary> /// <seealso cref="System.ComponentModel.INotifyPropertyChanged" /> public class WizardController : INotifyPropertyChanged { /// <summary> /// The timeout used to detect timeouts when querying build servers. /// </summary> private const int QueryTimeout = 10000; /// <summary> /// Logger instance used by this class. /// </summary> private static readonly Logger log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType?.ToString()); /// <summary> /// The owner window. /// </summary> private readonly Window ownerWindow; private readonly ApplicationConfiguration config; /// <summary> /// The wizard dialog settings. /// </summary> private readonly WindowSettings wizardDialogSettings; /// <summary> /// The wizard window. /// </summary> private WizardWindow wizardWindow; /// <summary> /// The current page. /// </summary> private Page currentPage; /// <summary> /// The projects view model. /// </summary> private ProjectViewModelList projects; /// <summary> /// Is any project checked. /// </summary> private bool isAnyProjectChecked; /// <summary> /// Is finish enabled. /// </summary> private bool isFinishEnabled; /// <summary> /// The proposed server address. /// </summary> private string proposedServerAddress; /// <summary> /// Is proposed address empty flag. /// </summary> private bool isProposedAddressEmpty = true; /// <summary> /// Is automatical connector type enabled. /// </summary> private bool isAutoDetectionEnabled = true; /// <summary> /// Is automatical connector type disabled. /// </summary> private bool isAutoDetectionDisabled = false; private ConnectorPlugin selectedConnectorType; /// <summary> /// The connector view model. /// </summary> private ConnectorViewModel editedConnectorViewModel; /// <summary> /// The force of <see cref="IsPreviousStepEnabled"/> flag. /// </summary> private bool? forceIsPreviousStepEnabled; /// <summary> /// The selected grouping setting. /// </summary> private GrouppingSetting selectedGroupingSetting; /// <summary> /// Initializes a new instance of the <see cref="WizardController" /> class. /// </summary> /// <param name="ownerWindow">The owner window.</param> /// <param name="config">The configuration.</param> /// <param name="wizardDialogSettings">The wizard dialog settings.</param> public WizardController(Window ownerWindow, ApplicationConfiguration config, WindowSettings wizardDialogSettings) { this.ownerWindow = ownerWindow; this.config = config; this.wizardDialogSettings = wizardDialogSettings; this.GroupingSettings = this.InitializeGrouppingSettings(); } /// <summary> /// Occurs when property was changed. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets the projects tree. /// </summary> public ProjectViewModelList Projects => this.projects ?? (this.projects = new ProjectViewModelList()); /// <summary> /// Gets the projects tree. /// </summary> public IReadOnlyList<GrouppingSetting> GroupingSettings { get; } /// <summary> /// Gets or sets the selected grouping setting. /// </summary> public GrouppingSetting SelectedGroupingSetting { get => this.selectedGroupingSetting; set { this.selectedGroupingSetting = value; this.OnPropertyChanged(nameof(this.SelectedGroupingSetting)); } } /// <summary> /// Gets a value indicating whether wizard is NOT on it's first step. /// </summary> public bool IsNotFirstStep => this.currentPage != null && !(this.currentPage is ConnectionWizardPage); /// <summary> /// Gets a value indicating whether wizard is on it's last step. /// </summary> public bool IsLastStep => this.currentPage is ProjectSelectionWizardPage; /// <summary> /// Gets a value indicating whether wizard is NOT on it's last step. /// </summary> public bool IsNotLastStep => !this.IsLastStep; /// <summary> /// Gets a value indicating whether this the next step button is enabled. /// </summary> public bool IsNextStepEnabled => this.IsNotLastStep && !this.IsProposedAddressEmpty; /// <summary> /// Gets or sets a value indicating whether this the previous step button is enabled. /// </summary> public bool IsPreviousStepEnabled { get { if (this.forceIsPreviousStepEnabled.HasValue) { return this.forceIsPreviousStepEnabled.Value; } return this.IsNotFirstStep; } set => this.forceIsPreviousStepEnabled = value; } /// <summary> /// Gets a value indicating whether the proposed address is empty. /// </summary> /// <value> /// <c>true</c> if the proposed address is empty; otherwise, <c>false</c>. /// </value> public bool IsProposedAddressEmpty { get => this.isProposedAddressEmpty; private set { this.isProposedAddressEmpty = value; this.OnPropertyChanged(nameof(this.IsNextStepEnabled)); } } /// <summary> /// Indicates if auto detection is enabled, when set also updates <seealso cref="IsAutoDetectionDisabled"/> /// trough public setter so the OnPropertyChanged on both are called and view is notified. /// </summary> public bool IsAutoDetectionEnabled { get => this.isAutoDetectionEnabled; set { this.isAutoDetectionEnabled = value; this.IsAutoDetectionDisabled = !value; this.OnPropertyChanged(nameof(this.isAutoDetectionEnabled)); } } /// <summary> /// Indicates if auto detection is disabled. When set also changes <seealso cref="isAutoDetectionDisabled"/> /// through private setter. /// </summary> public bool IsAutoDetectionDisabled { get => this.isAutoDetectionDisabled; set { this.isAutoDetectionDisabled = value; this.isAutoDetectionEnabled = !value; this.OnPropertyChanged(nameof(this.isAutoDetectionDisabled)); } } /// <summary> /// Gets or sets a value indicating whether multi selection mode is active. /// </summary> public bool MultiSelectionMode { get; set; } = true; /// <summary> /// Gets or sets the proposed server address. /// </summary> public string ProposedServerAddress { get { if (!this.IsProposedAddressEmpty) { return new Uri(this.proposedServerAddress).AbsoluteUri; } return this.proposedServerAddress; } set { this.proposedServerAddress = value; this.IsProposedAddressEmpty = string.IsNullOrWhiteSpace(value); this.OnPropertyChanged(nameof(this.IsProposedAddressEmpty)); } } public List<string> AvailableServers { get { if (this.isAutoDetectionEnabled) { return this.config.ConnectorsConfiguration.Where(x => x.GetConfigurationByKey(Connector.ServerAddress) != null && !string.IsNullOrEmpty(x.GetConfigurationByKey(Connector.ServerAddress).Value)).Select(x => new Uri(x.GetConfigurationByKey(Connector.ServerAddress).Value).AbsoluteUri).Distinct().ToList(); } if (this.SelectedConnectorType == null) { return new List<string>(); } return this.config.ConnectorsConfiguration.Where(x => x.Type == this.SelectedConnectorType.Name && x.GetConfigurationByKey(Connector.ServerAddress) != null && !string.IsNullOrEmpty(x.GetConfigurationByKey(Connector.ServerAddress).Value)).Select(x => new Uri(x.GetConfigurationByKey(Connector.ServerAddress).Value).AbsoluteUri).Distinct().ToList(); } } public List<ConnectorPlugin> AvailableConnectorTypes { get { return PluginManager.Instance.ConnectorPlugins.OrderByDescending(x => this.config.ConnectorsConfiguration.Count(y => y.Type == x.Name)).ToList(); } } public ConnectorPlugin SelectedConnectorType { get { if (this.selectedConnectorType == null) { this.selectedConnectorType = this.AvailableConnectorTypes.FirstOrDefault(); } return this.selectedConnectorType; } set { this.selectedConnectorType = value; this.OnPropertyChanged(nameof(this.SelectedConnectorType)); this.OnPropertyChanged(nameof(this.AvailableServers)); } } /// <summary> /// Gets a value indicating whether any project is checked. /// </summary> public bool IsAnyProjectChecked { get => this.isAnyProjectChecked; private set { this.isAnyProjectChecked = value; this.OnPropertyChanged(); } } /// <summary> /// Gets a value indicating whether finish button should be enabled. /// </summary> /// <value> /// <c>true</c> if this the finish button should be enabled; otherwise, <c>false</c>. /// </value> public bool IsFinishEnabled { get => this.isFinishEnabled; private set { this.isFinishEnabled = value; this.OnPropertyChanged(); } } /// <summary> /// Gets the wizard frame. /// </summary> private Frame WizardFrame => this.wizardWindow?.Frame; /// <summary> /// Starts the wizard. /// </summary> /// <param name="connector">The connector view model.</param> /// <returns> /// True if the wizard was finished correctly and not canceled in any way. /// </returns> public bool Start(ConnectorViewModel connector) { this.editedConnectorViewModel = connector; this.IsPreviousStepEnabled = false; return this.Start(false); } /// <summary> /// Starts the wizard and applies the results to given configuration. /// Multiple, new connectors might be created. /// </summary> /// <param name="applyConfig">if set to <c>true</c> [apply configuration].</param> /// <returns> /// True if the wizard was finished correctly and not canceled in any way. /// </returns> public bool Start(bool applyConfig = true) { this.wizardWindow = new WizardWindow(this); this.wizardWindow.Owner = this.ownerWindow; this.wizardWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner; if (this.editedConnectorViewModel == null) { this.GoToConnectionStep(); } else { this.ProposedServerAddress = this.editedConnectorViewModel.GetConfigurationByKey(Connector.ServerAddress)?.Value; void OnActivated(object sender, EventArgs e) { this.GoToProjectSelectionStep(); this.wizardWindow.Activated -= OnActivated; } this.wizardWindow.Activated += OnActivated; } this.wizardDialogSettings.Apply(this.wizardWindow); var wizardShowResult = this.wizardWindow.ShowDialog(); this.wizardDialogSettings.Parse(this.wizardWindow); if (wizardShowResult == true) { if (applyConfig) { this.ApplyToConfiguration(); } return true; } return false; } /// <summary> /// Retrieves selected projects. /// </summary> /// <returns>The selected projects.</returns> public IList<Project> GetSelectedProjects() { if (this.Projects == null || this.Projects.Count == 0) { return new List<Project>(); } var serverProjects = new List<Project>(); var checkedProjects = this.Projects.GetChecked(); foreach (var checkedProject in checkedProjects.Where(p => p.Projects.Count == 0)) { var newProject = new Project(checkedProject.Address, checkedProject.Name, checkedProject.DirectAddress, checkedProject.FullName, checkedProject.Description, this.Projects.PlugIn, this.CreateParentProjectStructure(checkedProject)); serverProjects.Add(newProject); } return serverProjects; } /// <summary> /// Goes to next page of the wizard. /// </summary> public void GoToNextPage() { if (this.WizardFrame.Content is ConnectionWizardPage) { this.GoToProjectSelectionStep(); } if (this.WizardFrame.Content is ProjectSelectionWizardPage) { this.Finish(); } } /// <summary> /// Goes to previous page of the wizard. /// </summary> public void GoToPrevPage() { if (this.WizardFrame.Content is ProjectSelectionWizardPage) { this.GoToConnectionStep(); } } /// <summary> /// Finishes this wizard. /// </summary> public void Finish() { if (this.IsAnyProjectChecked) { this.wizardWindow.DialogResult = true; this.wizardWindow.Close(); } } /// <summary> /// Called when property was changed. /// </summary> /// <param name="propertyName">Name of the property.</param> protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); if (propertyName == nameof(this.isAutoDetectionEnabled)) { if (this.isAutoDetectionEnabled) { this.selectedConnectorType = null; } } } /// <summary> /// Creates the group name from project tree. /// </summary> /// <param name="project">The project.</param> /// <param name="currentName">Name of the current.</param> /// <returns>Group name.</returns> private string CreateGroupNameFromProjectTree(Project project, string currentName = null) { if (project == null) { return currentName; } if (currentName?.Length > 0) { currentName = currentName.Insert(0, "/"); } currentName = project.Name + currentName; if (project.Parent == null) { return currentName; } return this.CreateGroupNameFromProjectTree(project.Parent, currentName); } /// <summary> /// Applies the results of the wizard to configuration. /// </summary> /// <exception cref="InvalidOperationException">At least one selected project is required.</exception> private void ApplyToConfiguration() { var selectedProjects = this.GetSelectedProjects(); if (selectedProjects.Count < 1) { throw new InvalidOperationException("At least one selected project is required."); } var configurationViewModel = new ConfigViewModel(); configurationViewModel.Load(this.config); foreach (var selectedProject in selectedProjects) { var newConnector = new ConnectorViewModel(); newConnector.SourceConnectorPlugin = selectedProject.Plugin; newConnector.Name = selectedProject.Name; newConnector.Load(null); if (this.SelectedGroupingSetting.Id == WizardWindow.AssignGroupsForAddedProjects) { var groupName = this.CreateGroupNameFromProjectTree(selectedProject.Parent); if (!string.IsNullOrWhiteSpace(groupName)) { newConnector.GetConfigurationByKey(Connector.Category).Value = groupName; } } configurationViewModel.Connectors.Add(newConnector); selectedProject.Plugin.Configure(selectedProject, newConnector, this.proposedServerAddress); } if (configurationViewModel.ConfigurationIsModified) { configurationViewModel.Connectors.ApplyToConfiguration(this.config); SerializationHelper.Instance.SaveConfiguration(this.config); } } /// <summary> /// Called when page was changed. /// </summary> private void OnPageChanged() { this.OnPropertyChanged(nameof(this.IsNotFirstStep)); this.OnPropertyChanged(nameof(this.IsLastStep)); this.OnPropertyChanged(nameof(this.IsNotLastStep)); this.OnPropertyChanged(nameof(this.IsFinishEnabled)); this.OnPropertyChanged(nameof(this.IsNextStepEnabled)); this.OnPropertyChanged(nameof(this.IsPreviousStepEnabled)); } /// <summary> /// Goes to connection step of the wizard. /// </summary> private void GoToConnectionStep() { this.currentPage = new ConnectionWizardPage(this); this.currentPage.DataContext = this; this.WizardFrame.Content = this.currentPage; if (this.editedConnectorViewModel != null) { this.SelectedConnectorType = this.editedConnectorViewModel.SourceConnectorPlugin; } this.OnPageChanged(); } private void ProcessServerSubProjects(IList<Project> projects, ProjectViewModel projectViewModel) { foreach (var project in projects.OrderBy(x => x.Name)) { var newProject = projectViewModel.AddProject(project); newProject.Parent = projectViewModel; newProject.Address = project.Address; newProject.DirectAddress = project.DirectAddress; var alreadyExists = this.config.ConnectorsConfiguration.Where(x => { var address = x.GetConfigurationByKey(Connector.ServerAddress)?.Value; if (string.IsNullOrWhiteSpace(address)) { return false; } return x.Type == this.SelectedConnectorType.Name && new Uri(address).AbsoluteUri.Equals(this.ProposedServerAddress) && x.GetConfigurationByKey(Connector.ProjectName)?.Value == (!string.IsNullOrWhiteSpace(project.FullName) ? project.FullName : project.Name); }).ToList(); newProject.AlreadyAdded = alreadyExists.Any(); newProject.AddedProject = alreadyExists.Any() ? string.Join(" - ", alreadyExists.Select(x => $"{x.GetConfigurationByKey(Connector.Category).Value}/{x.Name}")) : null; this.ProcessServerSubProjects(project.Children, newProject); } } /// <summary> /// Prepares the projects list. /// </summary> /// <returns>The task.</returns> private async Task PrepareProjectsList() { Tuple<ConnectorPlugin, ProjectViewModelList> pluginToQueryWithModel; if (this.editedConnectorViewModel != null) { pluginToQueryWithModel = new Tuple<ConnectorPlugin, ProjectViewModelList>(this.editedConnectorViewModel.SourceConnectorPlugin, new ProjectViewModelList { MultiSelectionMode = this.MultiSelectionMode, PlugIn = this.editedConnectorViewModel.SourceConnectorPlugin }); } else { var plugin = PluginManager.Instance.ConnectorPlugins.FirstOrDefault(x => x.Name.Equals(this.SelectedConnectorType.Name)); pluginToQueryWithModel = new Tuple<ConnectorPlugin, ProjectViewModelList>(plugin, new ProjectViewModelList { MultiSelectionMode = this.MultiSelectionMode, PlugIn = plugin }); } var taskList = new Dictionary<Task, ProjectViewModelList>(); var timeoutTask = Task.Delay(QueryTimeout); taskList.Add(timeoutTask, null); var task = this.LoadProjectsFromPlugin(pluginToQueryWithModel); taskList.Add(task, pluginToQueryWithModel.Item2); while (taskList.Count > 0) { var completedTask = await Task.WhenAny(taskList.Keys.ToArray()); if (completedTask == timeoutTask) { throw new Exception("Discovery of suitable plugin or server query timed out"); } if (completedTask.Status == TaskStatus.RanToCompletion) { this.projects = taskList.First(tkv => tkv.Key == completedTask).Value; this.AttachToProjectsPropertyChanged(); break; } log.Debug($"Projects discovery for a plugin task completed not successfully. Status:{completedTask.Status}; Exception: {completedTask.Exception}"); taskList.Remove(completedTask); } if (taskList.Count == 0) { throw new Exception("Couldn't find suitable plugin or the address is invalid"); } } /// <summary> /// Prepares the projects list. Uses all available plugins to try to get correct result from the server. /// </summary> /// <returns>The task.</returns> private async Task PrepareProjectsListWithTypeDetection() { Collection<Tuple<ConnectorPlugin, ProjectViewModelList>> pluginToQueryWithModels = new Collection<Tuple<ConnectorPlugin, ProjectViewModelList>>(); if (this.editedConnectorViewModel != null) { pluginToQueryWithModels.Add(new Tuple<ConnectorPlugin, ProjectViewModelList>(this.editedConnectorViewModel.SourceConnectorPlugin, new ProjectViewModelList { MultiSelectionMode = this.MultiSelectionMode, PlugIn = this.editedConnectorViewModel.SourceConnectorPlugin })); } else { foreach (var plugin in PluginManager.Instance.ConnectorPlugins) { pluginToQueryWithModels.Add(new Tuple<ConnectorPlugin, ProjectViewModelList>(plugin, new ProjectViewModelList { MultiSelectionMode = this.MultiSelectionMode, PlugIn = plugin })); } } var taskList = new Dictionary<Task, ProjectViewModelList>(); var timeoutTask = Task.Delay(QueryTimeout); taskList.Add(timeoutTask, null); foreach (var pluginToQueryWithModel in pluginToQueryWithModels) { var task = this.LoadProjectsFromPlugin(pluginToQueryWithModel); taskList.Add(task, pluginToQueryWithModel.Item2); } while (taskList.Count > 0) { try { var completedTask = await Task.WhenAny(taskList.Keys.ToArray()); if (completedTask == timeoutTask) { throw new Exception("Discovery of suitable plugin or server query timed out"); } if (completedTask.Status == TaskStatus.RanToCompletion) { this.projects = taskList.First(tkv => tkv.Key == completedTask).Value; this.AttachToProjectsPropertyChanged(); break; } log.Debug($"Projects discovery for a plugin task completed not successfully. Status:{completedTask.Status}; Exception: {completedTask.Exception}"); taskList.Remove(completedTask); } catch (Exception ex) { } } if (taskList.Count == 0) { throw new Exception("Couldn't find suitable plugin or the address is invalid"); } } /// <summary> /// Loads the projects from plugin. /// </summary> /// <param name="listQueryingPlugin">The list querying plugin.</param> /// <returns>The task.</returns> private async Task LoadProjectsFromPlugin(Tuple<ConnectorPlugin, ProjectViewModelList> listQueryingPlugin) { try { var serverProjects = await listQueryingPlugin.Item1.GetProjects(this.ProposedServerAddress.Last() != '/' ? this.ProposedServerAddress += '/' : this.ProposedServerAddress); foreach (var serverProject in serverProjects.OrderBy(x => x.Name)) { var newProject = listQueryingPlugin.Item2.AddProject(serverProject); newProject.Address = serverProject.Address; newProject.DirectAddress = serverProject.DirectAddress; this.ProcessServerSubProjects(serverProject.Children, newProject); } } catch (Exception ex) { throw ex; } return; } /// <summary> /// Attaches action to each project PropertyChanged event. /// </summary> private void AttachToProjectsPropertyChanged() { var projectCheckedChangedAction = new Action(() => this.IsAnyProjectChecked = this.Projects.Any(p => p.IsAnyChecked())); foreach (var project in this.Projects) { this.AttachToProjectPropertyChanged(project, projectCheckedChangedAction); } } /// <summary> /// Attaches action to each project PropertyChanged event. Applies the same action tosub projects. /// </summary> /// <param name="project">The project.</param> /// <param name="action">The action.</param> private void AttachToProjectPropertyChanged(ProjectViewModel project, Action action) { project.PropertyChanged += (s, e) => action(); foreach (var subProject in project.Projects) { this.AttachToProjectPropertyChanged(subProject, action); } } /// <summary> /// Goes to project selection step of the wizard. /// </summary> private async void GoToProjectSelectionStep() { var error = false; var errorMessage = string.Empty; var waitControl = new WaitControl(); var waitDailogTask = DialogHost.Show(waitControl, "WizardWaitDialogHostId"); try { if (this.isAutoDetectionEnabled) { await this.PrepareProjectsListWithTypeDetection(); } else { await this.PrepareProjectsList(); } } catch (Exception e) { error = true; errorMessage = $"There was a project error,{Environment.NewLine}details: {e.Message}"; // TODO load from resources } DialogHost.CloseDialogCommand.Execute("WizardWaitDialogHostId", this.wizardWindow.WizardWaitDialogHost); if (!error) { this.currentPage = new ProjectSelectionWizardPage(this); this.currentPage.DataContext = this; this.WizardFrame.Content = this.currentPage; this.OnPageChanged(); } else if (this.wizardWindow.IsVisible) { var errorDialog = new MessageControl(errorMessage); await DialogHost.Show(errorDialog, "WizardWaitDialogHostId"); if (this.editedConnectorViewModel != null) { this.wizardWindow.Close(); } } } /// <summary> /// Initializes the groupping settings. /// </summary> /// <returns>The list with initlized groupping settings.</returns> private List<GrouppingSetting> InitializeGrouppingSettings() { var grouppingSettings = new List<GrouppingSetting>(); grouppingSettings.Add(new GrouppingSetting("Assign parent as group", WizardWindow.AssignGroupsForAddedProjects)); grouppingSettings.Add(new GrouppingSetting("Add hierarchy to project name", WizardWindow.AddProjectPathToProjectName)); grouppingSettings.Add(new GrouppingSetting("No automatic grouping", WizardWindow.DoNotAssignAnyGroups)); return grouppingSettings; } /// <summary> /// Creates the parent project structure. /// </summary> /// <param name="viewModel">The view model.</param> /// <returns>Parent project.</returns> private Project CreateParentProjectStructure(ProjectViewModel viewModel) { if (viewModel.Parent == null) { return null; } var newParent = new Project(viewModel.Parent.Address, viewModel.Parent.Name, viewModel.Parent.DirectAddress, viewModel.Parent.FullName, viewModel.Parent.Description, this.Projects.PlugIn, this.CreateParentProjectStructure(viewModel.Parent)); return newParent; } } }
using System; using System.Collections.Generic; using System.Text; namespace SistemaToners.Entidades { public class Area { private int id; private string nombre_area; public int Id { get => id; set => id = value; } public string Nombre_area { get => nombre_area; set => nombre_area = value; } public Area(int _id, string _nombre_area) { this.id = _id; this.nombre_area = _nombre_area; } public Area() { } } }
namespace VoxelEngine.Utils { public enum RenderMode { None, Wire3D } }
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== // // // Notes: // // ============================================================================ // using System; using System.Collections; using System.Collections.Generic; namespace EnhancedEditor { /// <summary> /// Base collection class to display its content as a block in the inspector. /// </summary> [Serializable] public abstract class BlockCollection<T> : IEnumerable<T> { #region Global Members /// <summary> /// The total amount of element in this collection. /// </summary> public abstract int Count { get; } /// <summary> /// Whether this collection size can be edited in the editor. /// </summary> public bool IsEditable = true; /// <summary> /// Whether this collection content can be reordered in the editor. /// </summary> public bool IsReorderable = true; /// <summary> /// Whether this collection content is displayed as readonly or not. /// </summary> public bool IsReadonly = false; // ------------------------------------------- // Constructor(s) // ------------------------------------------- /// <inheritdoc cref="BlockCollection(bool, bool, bool)"/> public BlockCollection() : this(true, true) { } /// <param name="_isEditable"><inheritdoc cref="IsEditable" path="/summary"/></param> /// <param name="_isReorderable"><inheritdoc cref="IsReorderable" path="/summary"/></param> /// <param name="_isReadonly"><inheritdoc cref="IsReadonly" path="/summary"/></param> /// <inheritdoc cref="BlockCollection{T}"/> public BlockCollection(bool _isEditable, bool _isReorderable = true, bool _isReadonly = false) { IsEditable = _isEditable; IsReorderable = _isReorderable; IsReadonly = _isReadonly; } #endregion #region Operator public abstract T this[int _index] { get;set; } #endregion #region IEnumerable public IEnumerator<T> GetEnumerator() { for (int i = 0; i < Count; i++) { yield return this[i]; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region Utility /// <summary> /// Adds an element to this collection. /// </summary> /// <param name="_element">Element to add.</param> public abstract void Add(T _element); /// <summary> /// Clears this collection content. /// </summary> public abstract void Clear(); #endregion } /// <summary> /// Displays an array as a block in the inspector. /// </summary> /// <typeparam name="T">Array content type.</typeparam> [Serializable] public class BlockArray<T> : BlockCollection<T> { #region Global Members /// <summary> /// This wrapper array. /// </summary> [Block(false)] public T[] Array = new T[] { }; public override int Count { get { return Array.Length; } } // ----------------------- /// <inheritdoc cref="BlockCollection{T}.BlockCollection()"/> public BlockArray() : base() { } /// <inheritdoc cref="BlockCollection{T}.BlockCollection(bool, bool, bool)"/> public BlockArray(bool _isEditable, bool _isReorderable = true, bool _isReadonly = false) : base(_isEditable, _isReorderable, _isReadonly) { } #endregion #region Operator public override T this[int _index] { get { return Array[_index]; } set { Array[_index] = value; } } public static implicit operator T[](BlockArray<T> _collection) { return _collection.Array; } #endregion #region Utility public override void Add(T _element) { ArrayUtility.Add(ref Array, _element); } public override void Clear() { System.Array.Resize(ref Array, 0); } #endregion } /// <summary> /// Displays a list as a block in the inspector. /// </summary> /// <typeparam name="T">List content type.</typeparam> [Serializable] public class BlockList<T> : BlockCollection<T> { #region Global Members /// <summary> /// This wrapper list. /// </summary> [Block(false)] public List<T> List = new List<T>(); public override int Count { get { return List.Count; } } // ----------------------- /// <inheritdoc cref="BlockCollection{T}.BlockCollection()"/> public BlockList() : base() { } /// <inheritdoc cref="BlockCollection{T}.BlockCollection(bool, bool, bool)"/> public BlockList(bool _isEditable, bool _isReorderable = true, bool _isReadonly = false) : base(_isEditable, _isReorderable, _isReadonly) { } #endregion #region Operator public override T this[int _index] { get { return List[_index]; } set { List[_index] = value; } } public static implicit operator List<T>(BlockList<T> _collection) { return _collection.List; } #endregion #region Utility public override void Add(T _element) { List.Add(_element); } public override void Clear() { List.Clear(); } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Net; using OpenQA.Selenium; using OpenQA.Selenium.PhantomJS; using HtmlAgilityPack; using System.Threading; using System.Diagnostics; using SpiderStandard; namespace Spider { class Program { //尽然有人看我写的代码Σ(っ °Д °;)っ //欢迎欢迎 //我写的代码很乱(没有专业训练 //注释也很少而且不太精确(或许这样接地气 //别喷我写的代码我还是个新手 //没有了... static int aisle = 0;//浏览器线程数量 static bool notstop = true;//不结束运行 static bool opti = true;//根据性能优化 static int mixing = 20;//搅拌(打乱?)一下抓到的连接 static List<IWebDriver> WebDriver = new List<IWebDriver>();//浏览器页面 static List<XUrl> ALLUrl = new List<XUrl>();//已抓取到的所有链接 static List<string> ReadUrl = new List<string>();//已抓取到但未读取的链接 static PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");//获取CPU的总占用率 static float cpumax = 70;//默认cpu的最大占用,超过限速 // static List<string> UnReadUrl = new List<string>();//读取到的链接 已弃用 static void Main(string[] args) { // Console.ForegroundColor=ConsoleColor.Blue; Console.WriteLine(@" _____ _ _ " + "\r\n" + @" / ____| (_) | | " + "\r\n" + @" | (___ _ __ _ __| | ___ _ __ " + "\r\n" + @" \___ \| '_ \| |/ _` |/ _ \ '__|" + "\r\n" + @" ____) | |_) | | (_| | __/ | " + "\r\n" + @" |_____/| .__/|_|\__,_|\___|_| " + "\r\n" + @" | | " + "\r\n" + @" |_| "); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("by slacksoft"); Console.ForegroundColor = ConsoleColor.White; // //判断并加载保存的文件 if (File.Exists("ALLUrl.bin")) { ALLUrl = (List<XUrl>)Ser_Des.BytesToObject(File.ReadAllBytes("ALLUrl.bin")); } if (File.Exists("ReadUrl.bin")) { ReadUrl = (List<string>)Ser_Des.BytesToObject(File.ReadAllBytes("ReadUrl.bin")); } else//没有文件?自行输入起始要抓取的连接 { Console.Write("你需要添加链接,输入ok停止添加"); bool i = true; while (i) { string url = Console.ReadLine(); if (url == "ok") { i = false; } else { ReadUrl.Add(url); } } } //线程数量 Console.Write("输入浏览器线程数(推荐2-6)"); aisle = int.Parse(Console.ReadLine()); //创建浏览器 for (int i = 0; i != aisle; i++) { WebDriver.Add(CreateDriver()); Console.WriteLine("成功创建浏览器:" + i); } //我推荐的起始链接? //ReadUrl.Add(@"https://news.sogou.com/"); // ReadUrl.Add(@"https://www.csdn.net/"); //ReadUrl.Add(@"https://www.bilibili.com/"); //启动抓取线程的开启线程 Task SpideTask = new Task(() => SpiderStart()); SpideTask.Start(); Console.Write("程序已开始运行,可输入help或?查看帮助"); //是否运行、 bool Run = true; #region 程序命令 //十分硬核的command while (Run) { string cmd = Console.ReadLine(); if (cmd == "stop") { notstop = false; Console.WriteLine("开始关闭浏览器"); for (int i = 0; i != WebDriver.Count; i++) { try { Console.WriteLine("正在关闭浏览器" + i); WebDriver[i].Close(); WebDriver[i].Quit(); Console.WriteLine("关闭浏览器" + i); } catch (Exception ex) { Console.WriteLine(ex); } } Run = false; } else if (cmd == "allurl") { for (int i = 0; i != ALLUrl.Count; i++) { Console.WriteLine(ALLUrl[i].url + ALLUrl[i].Tile); } } else if (cmd == "readurl") { for (int i = 0; i != ReadUrl.Count; i++) { Console.WriteLine(ReadUrl[i]); if (ReadUrl[i] != null) { Console.WriteLine(ReadUrl[i]); } } } else if (cmd == "donenum") { Console.WriteLine(TaskDone); } else if (cmd == "echo") { if (echo) { echo = false; Console.WriteLine("已关闭"); } else { echo = true; Console.WriteLine("已开启"); } } else if (cmd == "runum") { Console.WriteLine(ReadUrl.Count); } else if (cmd == "aunum") { Console.WriteLine(ALLUrl.Count); } else if (cmd == "save") { Console.WriteLine("save ALLUrl"); File.WriteAllBytes("ALLUrl.bin", Ser_Des.ObjectToBytes(ALLUrl)); Console.WriteLine("save ReadUrl"); List<string> Buff = new List<string>(); for (int i = aisle - 1; i != ReadUrl.Count; i++) { if (ReadUrl[i] != null) { Buff.Add(ReadUrl[i]); } } File.WriteAllBytes("ReadUrl.bin", Ser_Des.ObjectToBytes(Buff)); Console.WriteLine("Done"); } else if (cmd == "cpumax") { Console.Write("输入CPU最大占用率(0-100)"); cpumax = float.Parse(Console.ReadLine()); Console.Write("设置成功"); } else if (cmd == "opti") { if (opti) { opti = false; Console.WriteLine("已关闭"); } else { opti = true; Console.WriteLine("已开启"); } } else if (cmd == "mixing") { Console.Write("链接混合程度(默认20)"); mixing = int.Parse(Console.ReadLine()); Console.Write("设置成功"); } else if (cmd == "clear") { Console.Clear(); } else if (cmd == "help" || cmd == "?") { Console.WriteLine("================================================================"); Console.WriteLine("SlackSpider Beta 1.2"); Console.WriteLine("save - 保存抓取到的链接"); Console.WriteLine("stop - 停止抓取"); Console.WriteLine("aunum - 抓取到的总链接数量"); Console.WriteLine("runum - 未抓取和正在抓取的链接数量"); Console.WriteLine("donenum - 完成的主线程"); Console.WriteLine("echo - 开启/关闭部分输出(默认关闭)"); Console.WriteLine("cpumax - 设置CPU最大占用率(在开启优化时,默认70)"); Console.WriteLine("opti - 开启/关闭线程优化(效果拔群默认启动,关掉会有飞一般的速度)"); Console.WriteLine("mixing - 链接混合程度(默认20)"); Console.WriteLine("clear - 清屏"); Console.WriteLine("help - 帮助"); Console.WriteLine("================================================================"); } else { Console.WriteLine("未知的命令:" + cmd + " 输入help或?查看帮助"); } #endregion } } #region 抓取线程的开启线程 /// <summary> /// 抓取线程的开启线程 /// </summary> public static void SpiderStart() { //如果程序没有被停止 if (notstop) { Console.WriteLine("新的抓取线程"); TaskDone = 0; for (int i = 0; i != aisle; i++)//添加抓取线程 { if (ReadUrl.Count - 1 < i)//链接不够创建 { TaskDone++; if (echo) { Console.WriteLine("未添加的线程:" + i); } } else//创建 { int Buffe = i; if (echo) { Console.WriteLine("启动线程:" + Buffe); } Task spidersun = new Task(() => SpiderCore(Buffe)); spidersun.Start(); } } while (TaskDone != aisle) { }//等待扔出去的线程回来 List<string> Buff = new List<string>();//把未读取的链接往上挪 for (int i = aisle; i != ReadUrl.Count; i++) { Buff.Add(ReadUrl[i]); } Console.WriteLine("混淆"); ReadUrl = Randomlist(Buff); SpiderStart(); } } #endregion static bool echo = false;//是否输出(为啥我当时要把它要叫做echo static int TaskDone = 0;//已经完成的线程 static object TaskLockCore = new object();//线程锁 #region 抓取线程 /// <summary> /// 抓取线程 /// </summary> /// <param name="Taskaisle">线程id</param> public static void SpiderCore(int Taskaisle) { try { if (echo) { Console.WriteLine("访问:" + ReadUrl[Taskaisle]); } WebDriver[Taskaisle].Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(3)); WebDriver[Taskaisle].Navigate().GoToUrl(ReadUrl[Taskaisle]); /* XUrl DoneUrl = new XUrl(); DoneUrl.url = ReadUrl[Taskaisle]; DoneUrl.Tile = WebDriver[Taskaisle].Title; Console.WriteLine("添加链接:"+ ReadUrl[Taskaisle]+ "标题:"+ WebDriver[Taskaisle].Title); ALLUrl.Add(DoneUrl);*/ HtmlDocument page = new HtmlDocument(); page.LoadHtml(WebDriver[Taskaisle].PageSource); HtmlNodeCollection hrefList = page.DocumentNode.SelectNodes(".//a[@href]"); int hrefList_Count = 0; if (hrefList != null) { hrefList_Count = hrefList.Count; } for (int i2 = 0; i2 != hrefList_Count; i2++)//循环遍历抓取到的链接组 { HtmlNode href = hrefList[i2]; HtmlAttribute att = href.Attributes["href"]; bool IsNotOld = true; string HTTPUri = att.Value; //Console.WriteLine(HTTPUri.Length+ HTTPUri); //替换非http开头的路径链接开头,并扔掉一些没用的,格式错误的链接 if (HTTPUri.Length < 2) { HTTPUri = ""; } else if (HTTPUri.IndexOf("http") == -1 && HTTPUri.Substring(0, 2) == @"//") { HTTPUri = HTTPUri.Replace("//", "http://"); } else if (HTTPUri.IndexOf("http") == -1 && HTTPUri.Substring(0, 2) == @"./") { HTTPUri = HTTPUri.Replace("./", ReadUrl[Taskaisle]); } else if (HTTPUri.IndexOf("http") == -1 && HTTPUri.Substring(0, 1) == @"/") { HTTPUri = ReadUrl[Taskaisle] + HTTPUri.Substring(1, HTTPUri.Length - 1); } else if (HTTPUri.IndexOf("http") == -1) { HTTPUri = ""; } //查看是否重复抓取链接 for (int I_repeat = 0; I_repeat != ALLUrl.Count; I_repeat++) { if (ALLUrl[I_repeat].url == HTTPUri) { IsNotOld = false; } } for (int I_repeat = 0; I_repeat != ReadUrl.Count; I_repeat++) { if (ReadUrl[I_repeat] == HTTPUri) { IsNotOld = false; } } if (HTTPUri != "" & IsNotOld & HTTPUri.ToCharArray().Length <= 250) { //Console.WriteLine(HTTPUri.ToCharArray().Length); //标题获取线程 Thread geturl = new Thread(() => { string geturlstring = HTTPUri; try { HtmlAgilityPack.HtmlWeb get = new HtmlWeb(); HtmlDocument tdoc = get.Load(geturlstring); XUrl DoneUrl = new XUrl(); DoneUrl.url = geturlstring; if (tdoc != null) { if (tdoc.DocumentNode.SelectSingleNode("//title").InnerText != null)//获取标题 { DoneUrl.Tile = tdoc.DocumentNode.SelectSingleNode("//title").InnerText; } else { DoneUrl.Tile = geturlstring; } if (DoneUrl.Tile != "" & DoneUrl.Tile.IndexOf("404") == -1 & DoneUrl.Tile.IndexOf("NOT FOUND") == -1 & DoneUrl.Tile.IndexOf("not found") == -1 & DoneUrl.Tile.IndexOf("Not Found") == -1 & DoneUrl.Tile.IndexOf("¤") == -1 & DoneUrl.Tile.IndexOf("¢") == -1)//防止部分标题乱码和无法访问的网页(需要改进 { //把抓到的链接添加进去 ALLUrl.Add(DoneUrl); ReadUrl.Add(geturlstring); if (echo) { Console.WriteLine("添加链接:" + geturlstring + "标题:" + DoneUrl.Tile); } } } } catch (Exception ex) { if (echo) { Console.WriteLine(ex.Message); } } }); geturl.Start();//启动线程 float nowcpu = cpuCounter.NextValue(); if (ReadUrl.Count <= aisle) { while (geturl.ThreadState == System.Threading.ThreadState.Running) { } } else if (nowcpu > cpumax && opti) { if (echo) { Console.WriteLine("CPU总占用" + nowcpu + "超过设定值,开始限速"); } Thread.Sleep(1000); if (geturl.ThreadState == System.Threading.ThreadState.Running) { geturl.Interrupt(); Console.WriteLine("线程超时"); } else { Debug.WriteLine(geturl.ThreadState); } } /* else { Thread threadover = new Thread(() => { Thread.Sleep(1000); if (geturl.ThreadState == System.Threading.ThreadState.Running) { geturl.Abort(); if (echo) { Console.WriteLine("线程超时"); } } else { // Debug.WriteLine("线程不超速"); } }); threadover.Start(); }*/ //CPU去世器↑已弃用 } } ReadUrl[Taskaisle] = null; } catch (Exception ex) { Console.WriteLine(ex); } lock (TaskLockCore) { TaskDone++; } if (echo) { Console.WriteLine("访问完成"); } } #endregion #region 浏览器的配置 public static PhantomJSDriver CreateDriver() { PhantomJSDriverService services = PhantomJSDriverService.CreateDefaultService(); services.HideCommandPromptWindow = true;//隐藏控制台窗口 return new PhantomJSDriver(services); } #endregion #region 打乱链接,防止长时间抓取某个网站 public static List<string> Randomlist(List<string> anylist) { List<string> newanylist = anylist; if (!(anylist.Count <= aisle)) { Random random = new Random(); for (int i = 0; i <= anylist.Count * mixing; i++) { int i1 = random.Next(aisle, anylist.Count); int i2 = random.Next(aisle, anylist.Count); while (i1 == i2) { i2 = random.Next(aisle, anylist.Count); ; } string o1 = newanylist[i1]; string o2 = newanylist[i2]; if (echo) { Console.WriteLine(o1 + ":" + o2); } newanylist[i1] = o2; newanylist[i2] = o1; } } else { Console.WriteLine("链接太少无法混淆"); } return newanylist; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace MessServer { class Program { const int port = 8888; static TcpListener listener; static void Main(string[] args) { try { listener = new TcpListener(IPAddress.Parse("127.0.0.1"), port); listener.Start(); Console.WriteLine("Ожидание подключений..."); while (true) { TcpClient client = listener.AcceptTcpClient(); ClientObject clientObject = new ClientObject(client); // создаем новый поток для обслуживания нового клиента Thread clientThread = new Thread(new ThreadStart(clientObject.Process)); clientThread.Start(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (listener != null) listener.Stop(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using Gensokyo.Components.Primitives; using Gensokyo.Xaml.Commands; namespace Gensokyo.Components.Interactives { public class ToggleSwipeButton : PrimitiveButton { static ToggleSwipeButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ToggleSwipeButton), new FrameworkPropertyMetadata(typeof(ToggleSwipeButton))); } protected override void OnClick() { SwipeRecognitor.IsEnable = !SwipeRecognitor.IsEnable; } } public static class IxContentHostCommands { static IxContentHostCommands() { ToggleIxLeft = Create("ToggleIxLeft"); ToggleIxRight = Create("ToggleIxRight"); ToggleIxUp = Create("ToggleIxUp"); ToggleIxDown = Create("ToggleIxDown"); ToggleSwipe = Create("ToggleSwipe"); } public static RoutedUICommand Create(string name) { return new RoutedUICommand(name, name, typeof(IxContentHostCommands)); } /// <summary> /// /// </summary> public static RoutedUICommand ToggleIxLeft { get; } /// <summary> /// /// </summary> public static RoutedUICommand ToggleIxRight { get; } /// <summary> /// /// </summary> public static RoutedUICommand ToggleIxUp { get; } /// <summary> /// /// </summary> public static RoutedUICommand ToggleIxDown { get; } /// <summary> /// /// </summary> public static RoutedUICommand ToggleSwipe { get; } } }
using CMS.Core.Model; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Linq; namespace CMS.Data.Identity { public static class InitialData { public static List<User> GetAdminUsers() { var users = new List<User> { //admin pass: abc123@ -> change later new User { Id = "e7f18795-000c-4afe-995f-b71ec95fee30", UserName = "Admin", Name = "Admin", LastName = "", PasswordHash = "AF924q+3egq51yXasR/R3JYrcJAD7VzH48vt7ZzSyRf/5X+rC5TGvjoS4dUq6wNv4w==", SecurityStamp = "3656ca8d-bcf0-4e6d-8d49-81e7da37fd6d" }, new User { Id = "061f64c8-1eba-44a8-ac70-04e8c129ee81", UserName = "1", Name = "User 1", LastName = "", PasswordHash = "AF924q+3egq51yXasR/R3JYrcJAD7VzH48vt7ZzSyRf/5X+rC5TGvjoS4dUq6wNv4w==", SecurityStamp = "3656ca8d-bcf0-4e6d-8d49-81e7da37fd6d", } }; return users; } public static List<IdentityRole> GetRoles() { return new List<IdentityRole> { new IdentityRole { Id = "f0ef553e-63bf-465d-b5f2-8abbe9768692", Name = "Admin" }, new IdentityRole { Id = "08ae5d44-fb25-4ec7-b4e2-2aa62a8dfefc", Name = "Operator" } }; } public static List<IdentityUserRole> GetUsersInRoles() { var usersInRoles = new List<IdentityUserRole>(); var adminUsers = GetAdminUsers(); var adminRole = GetRoles().SingleOrDefault(r => r.Name == "Admin"); if (adminRole != null) { foreach (var adminUser in adminUsers) { usersInRoles.Add(new IdentityUserRole { RoleId = adminRole.Id, UserId = adminUser.Id }); } } return usersInRoles; } public static List<AccessPathCategory> GetAccessPathCategories() { return new List<AccessPathCategory> { new AccessPathCategory { Id = Guid.Parse("ec00bcf7-dd13-4952-86dd-3617bcbee784"), Title = "Home" }, new AccessPathCategory { Id = Guid.Parse("b9e05fac-2879-4edb-92c4-02b53e1ae805"), Title = "Role access paths management" }, new AccessPathCategory { Id=Guid.Parse("58e90c18-2c83-4194-89f8-97b9ea3026c3"), Title="Roles management" }, new AccessPathCategory { Id = Guid.Parse("2e98edf9-6c14-442b-a788-320dbf7ecdf5"), Title = "User info management" }, new AccessPathCategory { Id = Guid.Parse("e549df38-c585-479e-8ea8-81a3a11adb24"), Title="User management" }, new AccessPathCategory { Id = Guid.Parse("01705ce9-f696-4390-b092-870240b9a0fc"), Title="Users and role management" }, new AccessPathCategory { Id = Guid.Parse("367f75d6-d126-4130-8903-fb99147ae7dc"), Title = "Time access restrictions management" }, new AccessPathCategory { Id = Guid.Parse("0df91819-eb69-420c-ae9a-463b6d1a0692"), Title = "Restricted IPs management" }, new AccessPathCategory { Id = Guid.Parse("c9bffb79-9fe1-4884-9904-4fe24520933a"), Title = "User logs management" }, new AccessPathCategory { Id = Guid.Parse("c672c807-1f62-4c2f-8e61-a195d48039dc"), Title = "User profile management" }, }; } public static List<AccessPath> GetAccessPaths() { //cms var restrictedAccessTimesControllerPaths = new List<AccessPath> { new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("367f75d6-d126-4130-8903-fb99147ae7dc"), Title = "List", Path = "GET api/cms/restricted/access/times", Priority = 0 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("367f75d6-d126-4130-8903-fb99147ae7dc"), Title = "Details", Path = "GET api/cms/restricted/access/times/{id}", Priority = 1 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("367f75d6-d126-4130-8903-fb99147ae7dc"), Title = "Create", Path = "POST api/cms/restricted/access/times/create", Priority = 2 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("367f75d6-d126-4130-8903-fb99147ae7dc"), Title = "Update", Path = "PUT api/cms/restricted/access/times/update", Priority = 3 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("367f75d6-d126-4130-8903-fb99147ae7dc"), Title = "Delete", Path = "DELETE api/cms/restricted/access/times/permanent/{id}", Priority = 5 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("367f75d6-d126-4130-8903-fb99147ae7dc"), Title = "Delete items", Path = "DELETE api/cms/restricted/access/times", Priority = 6 } }; var restrictedIPsControllerPaths = new List<AccessPath> { new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("0df91819-eb69-420c-ae9a-463b6d1a0692"), Title = "List", Path = "GET api/cms/restricted/ips", Priority = 0 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("0df91819-eb69-420c-ae9a-463b6d1a0692"), Title = "Details", Path = "GET api/cms/restricted/ips/{id}", Priority = 1 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("0df91819-eb69-420c-ae9a-463b6d1a0692"), Title = "Create", Path = "POST api/cms/restricted/ips/create", Priority = 2 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("0df91819-eb69-420c-ae9a-463b6d1a0692"), Title = "Update", Path = "PUT api/cms/restricted/ips/update", Priority = 3 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("0df91819-eb69-420c-ae9a-463b6d1a0692"), Title = "Delete", Path = "DELETE api/cms/restricted/ips/permanent/{id}", Priority = 5 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("0df91819-eb69-420c-ae9a-463b6d1a0692"), Title = "Delete items", Path = "DELETE api/cms/restricted/ips", Priority = 6 } }; var roleAccessPathsControllerPaths = new List<AccessPath> { new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("b9e05fac-2879-4edb-92c4-02b53e1ae805"), Title = "Details", Path = "GET api/cms/role/access/paths/{id}", Priority = 0 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("b9e05fac-2879-4edb-92c4-02b53e1ae805"), Title = "Update", Path = "PUT api/cms/role/access/paths/update", Priority = 1 } }; var rolesControllerPaths = new List<AccessPath> { new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("58e90c18-2c83-4194-89f8-97b9ea3026c3"), Title = "List", Path = "GET api/cms/roles", Priority = 0 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("58e90c18-2c83-4194-89f8-97b9ea3026c3"), Title = "Details", Path = "GET api/cms/roles/{id}", Priority = 1 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("58e90c18-2c83-4194-89f8-97b9ea3026c3"), Title = "Create", Path = "POST api/cms/roles/create", Priority = 2 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("58e90c18-2c83-4194-89f8-97b9ea3026c3"), Title = "Update", Path = "PUT api/cms/roles/update", Priority = 3 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("58e90c18-2c83-4194-89f8-97b9ea3026c3"), Title = "Delete", Path = "DELETE api/cms/roles/{id}", Priority = 4 } }; var userInfoControllerPaths = new List<AccessPath> { new AccessPath { Id = Guid.NewGuid(), ParentId=Guid.Parse("2e98edf9-6c14-442b-a788-320dbf7ecdf5"), Title = "Details", Path = "GET api/cms/user/info/{id}", Priority = 0 }, new AccessPath { Id = Guid.NewGuid(), ParentId=Guid.Parse("2e98edf9-6c14-442b-a788-320dbf7ecdf5"), Title = "Update", Path = "PUT api/cms/user/info/update", Priority = 1 } }; var usersInRolesControllerPaths = new List<AccessPath> { new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("01705ce9-f696-4390-b092-870240b9a0fc"), Title = "List", Path = "GET api/cms/user/in/roles/{userId}", Priority = 0 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("01705ce9-f696-4390-b092-870240b9a0fc"), Title = "Details", Path = "GET api/cms/user/in/roles/{userId}/{roleId}", Priority = 1 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("01705ce9-f696-4390-b092-870240b9a0fc"), Title = "Create", Path = "POST api/cms/user/in/roles/create", Priority = 2 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("01705ce9-f696-4390-b092-870240b9a0fc"), Title = "Delete", Path = "DELETE api/cms/user/in/roles/{userId}/{roleId}", Priority = 3 } }; var userLogsControllerPaths = new List<AccessPath> { new AccessPath { Id = Guid.NewGuid(), ParentId=Guid.Parse("c9bffb79-9fe1-4884-9904-4fe24520933a"), Title = "List", Path = "GET api/cms/user/logs/{userId}", Priority = 0 }, new AccessPath { Id = Guid.NewGuid(), ParentId=Guid.Parse("c9bffb79-9fe1-4884-9904-4fe24520933a"), Title = "Details", Path = "GET api/cms/user/logs/{id}", Priority = 1 } }; var usersControllerPaths = new List<AccessPath> { new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("e549df38-c585-479e-8ea8-81a3a11adb24"), Title = "List", Path = "GET api/cms/users", Priority = 0 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("e549df38-c585-479e-8ea8-81a3a11adb24"), Title = "Details", Path = "GET api/cms/users/{id}", Priority = 1 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("e549df38-c585-479e-8ea8-81a3a11adb24"), Title = "Create", Path = "POST api/cms/users/create", Priority = 2 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("e549df38-c585-479e-8ea8-81a3a11adb24"), Title = "Update", Path = "PUT api/cms/users/update", Priority = 3 }, new AccessPath { Id = Guid.NewGuid(), ParentId = Guid.Parse("e549df38-c585-479e-8ea8-81a3a11adb24"), Title = "Delete", Path = "DELETE api/cms/users/{id}", Priority = 4 } }; var accessPathList = new List<AccessPath>(); //cms accessPathList.AddRange(restrictedAccessTimesControllerPaths); accessPathList.AddRange(restrictedIPsControllerPaths); accessPathList.AddRange(roleAccessPathsControllerPaths); accessPathList.AddRange(rolesControllerPaths); accessPathList.AddRange(userInfoControllerPaths); accessPathList.AddRange(usersInRolesControllerPaths); accessPathList.AddRange(userLogsControllerPaths); accessPathList.AddRange(usersControllerPaths); return accessPathList; } public static List<RoleAccessPath> GetRolesAccessPaths(List<AccessPath> usedAccessPaths) { var roleAccessList = new List<RoleAccessPath>(); var roles = GetRoles(); var adminRole = roles.SingleOrDefault(r => r.Name == "Admin"); if (adminRole != null) { foreach (var accessPath in usedAccessPaths) { roleAccessList.Add(new RoleAccessPath { RoleId = adminRole.Id, AccessPathId = accessPath.Id }); } } return roleAccessList; } } }
using Microsoft.AspNetCore.Hosting; using Serilog; namespace HelloUniverse { public class Program { public static void Main(string[] args) { Serilog.Log.Logger = new Serilog .LoggerConfiguration() .MinimumLevel.Debug() .Enrich.FromLogContext() .WriteTo.LiterateConsole() .CreateLogger(); var test = string.Format("Hello World"); var host = new WebHostBuilder() .UseKestrel() .UseStartup<Startup>() .UseUrls(new [] { "http://*:5000" }) .Build(); host.Run(); } } }
using Logic; using StringSearch; using System; using System.Collections.Generic; namespace ConsoleView { static class Program { static void Main(string[] args) { string text = "1aeee2 1A2 1 a 2 1 A2"; string pattern = "1a2"; foreach (var searcher in SearchAlgorithmsManager.Instance.GetAll()) { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("{0,-60}{1, 20}", searcher.Name, "(v." + searcher.Version + ")"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("- {0,-80}", searcher.Description); WriteResult(searcher.Algorithm.SearchAll(text, pattern)); } Console.ReadKey(); } static void WriteResult(ResultItem result) { Console.ForegroundColor = ConsoleColor.Yellow; if (result != null) Console.WriteLine("{0}: {1}", result.Index, result.Value); Console.ForegroundColor = ConsoleColor.White; } static void WriteResult(IEnumerable<ResultItem> results) { Console.ForegroundColor = ConsoleColor.Yellow; if (results.GetEnumerator().MoveNext() == false) { Console.WriteLine("Not found"); } Console.ForegroundColor = ConsoleColor.White; foreach (var result in results) { WriteResult(result); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; namespace WebApplication24 { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //S'il ne s'agit pas d'un postback if(!IsPostBack) { //On créer une variable pour tenir le compte int compte = 0; //Pour chaque page dans le GridView for (int i = 0; i < GV_Ville.PageCount; i++) { //Pour chaque rangée dans la page for (int x = 0; x < GV_Ville.Rows.Count; x++) { //On incrémente le compteur compte = compte + 1; } } //On assigne le compte en texte au TextBox d'ID de Ville TB_ID_Vile.Text = compte.ToString(); } } protected void BT_ajout_Click(object sender, EventArgs e) { //On créer une connection à la base de donnée using (SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\BD_Ville_Pologne.mdf;Integrated Security=True")) { //On ouvre la connection connection.Open(); //On donne le code SQL à la commande SqlCommand commande = new SqlCommand("INSERT into [Ville] (ID_Ville, Ville) VALUES (@ID_Ville, @Ville)"); //On assigne la connection à la commande commande.Connection = connection; //On ajoute le paramètre ID_Ville commande.Parameters.AddWithValue("@ID_Ville", TB_ID_Vile.Text); //On ajoute le paramètre Ville commande.Parameters.AddWithValue("@Ville", TB_Nom_Ville.Text); //On exécute la commande commande.ExecuteNonQuery(); //On ferme la connection connection.Close(); //On dispose de la connection connection.Dispose(); } } } }
using JOBTIND21.Dominio; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace JOBTIND21.Servicio { public interface IUsuario { void Insertar(Usuario c); void Delete(Usuario c); void Buscar(Usuario c); ICollection<Usuario> ListarCursos(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Climbing : MonoBehaviour { public GameObject player; Animator animator; Rigidbody rb; public float v; private bool climable = false; private float climbSpeed = 0.05f; // Use this for initialization void Start () { animator = player.GetComponent<Animator>(); rb = player.GetComponent<Rigidbody>(); } void FixedUpdate () { Climb(climable); } //void OnTriggerEnter(Collider other) //{ // if(other.tag == "ladderBase") // { // Debug.Log("climb"); // animator.SetBool("Climb_idle", true); // PlayerMovement.isMovable = false; // } //} void OnCollisionEnter(Collision collision) { if (collision.contacts[0].normal == Vector3.right || collision.contacts[0].normal == Vector3.left) { Debug.Log("climb"); //animator.SetBool("Climb_idle", true); PlayerMovement.isMovable = false; climable = true; } } private void OnCollisionExit(Collision collision) { climable = false; PlayerMovement.isMovable = true; rb.useGravity = true; animator.SetBool("Climb_up", false); player.transform.Translate(Vector3.forward*0.2f); } void Climb(bool climable) { if (climable) { v = Input.GetAxis("Vertical"); //Vector3 input = new Vector3(0, 1000.0f, 0); //rb.AddForce(input * v); if (v > 0f) { player.transform.Translate(Vector3.up * v * climbSpeed); player.transform.Translate(Vector3.forward*0.1f); animator.SetBool("Climb_up", true); } if (v < 0) { player.transform.Translate(Vector3.down * Mathf.Abs(v) * climbSpeed); animator.SetBool("Climb_up", true); } if (v == 0) { animator.speed = 0; } else { animator.speed = 1; } rb.useGravity = false; } } }
 using System.Runtime.InteropServices; namespace Service { /// <summary> /// Delegate handler for a command message subscription event. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="SubscribedEventArgs" /> instance containing the event data.</param> [ComVisible(true)] public delegate void SubscriptionEventHandler(object sender, SubscribedEventArgs e); }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class HarmonicAttack : MonoBehaviour { public AudioClip clip; public ParticleSystem particle; public bool changeColor; private SpriteRenderer sprite; private PitchManager pitch; [Range(0f, 1.0f)] public float volume; [Range(0f, 0.2f)] public float colorVariance = 0.02f; private void Awake() { pitch = AudioManager.instance.pitch; sprite = GetComponent<SpriteRenderer>(); } private void Start() { PlayNext(); } public void PlayNext() { Color noteColor = GetColor(); if (clip != null) { AudioManager.instance.PlaySound(clip, true, volume, pitch.GetMajorPitch()); } if (sprite != null && changeColor) { sprite.color = noteColor; } if (particle != null) { var main = particle.main; Color min = noteColor.ShiftHue(-colorVariance); Color max = noteColor.ShiftHue(colorVariance); main.startColor = new ParticleSystem.MinMaxGradient(min, max); } pitch.IncreaseNoteCount(1); } private Color GetColor() { int hue = pitch.NoteCount % PitchManager.pitchCount; return ColorExtension.PastelColor(hue); } }
using System.Data; using System.Threading.Tasks; using ApplicationCore.Interfaces; using Npgsql; namespace Infrastructure.Data { public class UnitOfWork : IUnitOfWork { private readonly string connectionString = "User ID=asp_user;Password=Password123;Host=localhost;Port=5433;Database=IdentityTest;Pooling=true;"; private NpgsqlTransaction _dbTransaction; private NpgsqlConnection _dbConnection; protected IDbConnection DbConnection { get => _dbConnection; } public IDbTransaction DbTransaction { get => _dbTransaction; } public UnitOfWork() { _dbConnection = new NpgsqlConnection(connectionString); _dbConnection.Open(); _dbTransaction = _dbConnection.BeginTransaction(); } public Task CommitAsync() { try { return _dbTransaction.CommitAsync(); } catch { _dbTransaction.Rollback(); throw; } finally { _dbTransaction.Dispose(); DbConnection.Close(); } } public void Dispose() { if (DbTransaction != null) { _dbTransaction.Dispose(); _dbTransaction = null; } if (DbConnection != null) { DbConnection.Dispose(); _dbConnection = null; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LeetCodeCSharp { public class _005_WordLadder { /**/ public int FindWordLadderLength(string[] dict, string start, string end) { Queue<string> q = new Queue<string>(); HashSet<string> hash = new HashSet<string>(); int step = 1; q.Enqueue(start); hash.Add(start); q.Enqueue(null); while (q.Count != 0) { string tmp = q.Dequeue(); if(string.IsNullOrEmpty(tmp)) { step++; if (q.Count != 0) { q.Enqueue(null); } else { break; } continue; } List<string> neighbors = ChangeOneLetter(tmp); foreach(string s in neighbors) { if (s == end) { return step+1; } if (!hash.Contains(s) && dict.Contains(s)) { q.Enqueue(s); hash.Add(s); } } } return -1; } private List<string> ChangeOneLetter(string input) { char[] strCharArray = input.ToCharArray(); List<string> res = new List<string>(); for (int i = 0; i < strCharArray.Length; i++) { for (int j = 0; j < 26; j++) { strCharArray[i] = (char)((int)'a' + j); string s = new string(strCharArray); if (s != input) { res.Add(s); } } strCharArray[i] = input[i]; } return res; } #region word ladder II /* * used DFS method to find all pathes and find shortest path. * not quite sure if this is the best solution. but it works * http://leetcode.com/onlinejudge#question_127 */ public List<List<string>> FindWordLadderII(string[] dict, string start, string end) { Stack<string> tracker = new Stack<string>(); List<List<string>> res = new List<List<string>>(); tracker.Push(start); Find(dict, tracker, end, res); int min = int.MaxValue; foreach (List<string> l in res) { min = min < l.Count ? min : l.Count; } List<List<string>> final = new List<List<string>>(); foreach (List<string> l in res) { if (l.Count == min) { final.Add(l); } } return final; } public void Find(string[] dict, Stack<string> tracker, string end, List<List<string>> res) { string top = tracker.Peek(); List<string> tmp = ChangeOneLetter(top); foreach (string s in tmp) { if (end == s) { CopyToRes(res, tracker, end); } if (dict.Contains(s) && !tracker.Contains(s)) { tracker.Push(s); Find(dict, tracker, end, res); tracker.Pop(); } } } public void CopyToRes(List<List<string>> res, Stack<string> tracker, string end) { Stack<string> tmp = new Stack<string>(); List<string> OneList = new List<string>(); while (tracker.Count != 0) { OneList.Insert(0, tracker.Peek()); tmp.Push(tracker.Pop()); } OneList.Add(end); while (tmp.Count != 0) { tracker.Push(tmp.Pop()); } res.Add(OneList); } #endregion } }
namespace Application.Articles.Commands.UpdateArticleCommands { public class UpdateArticleCommandValidator { } }
using GetLabourManager.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; using ExcelDataReader; using System.Data; using ExcelDataReader.Log; namespace GetLabourManager.Helper { public class DataProcessingHelper { RBACDbContext db; public string MainFolder { get; set; } public DataProcessingHelper(RBACDbContext _db) { this.db = _db; MainFolder = AppDomain.CurrentDomain.BaseDirectory + @"/Doc/Migration"; if (!Directory.Exists(this.MainFolder)) { Directory.CreateDirectory(this.MainFolder); } } public bool ExtractCasualsFromFile(string file_path) { bool complete = false; List<Employee> employees = new List<Employee>(); var branch_entity = db.ClientSetup.FirstOrDefault(x => x.Id > 0); var category = db.EmpCategory.FirstOrDefault(x => x.Id > 0); FileStream stream = new FileStream(file_path, FileMode.Open, FileAccess.Read); try { using (var reader = ExcelReaderFactory.CreateReader(stream)) { int index = 0; while (reader.Read()) { if (index > 0) { Employee employee = new Employee(); employee.Code = reader.GetValue(0).ToString(); employee.FirstName = reader.GetValue(1).ToString(); employee.MiddleName = reader.GetValue(2).ToString(); employee.LastName = reader.GetValue(3).ToString(); employee.Gender = reader.GetValue(4).ToString() == "M" ? "MALE" : "FEMALE"; employee.EmailAddress = reader.GetValue(5).ToString(); employee.Dob = DateTime.Parse(reader.GetValue(6).ToString()); employee.DateJoined = DateTime.Parse(reader.GetValue(7).ToString()); employee.Telephone1 = reader.GetValue(8).ToString(); employee.Address = reader.GetValue(9).ToString(); employee.BranchId = branch_entity.Id; employee.Category = category.Id; employee.Region = "GREATER ACCRA"; employee.Status = "ACTIVE"; employees.Add(employee); } index++; } reader.Close(); } if (employees.Count > 0) { db.Employee.AddRange(employees); db.SaveChanges(); System.IO.File.Delete(file_path); complete = true; } } catch (Exception err) { return complete; // throw; } return complete; } // public bool ExtractGuarantorFromFile(string file_path) { bool complete = false; List<EmployeeRelations> employees = new List<EmployeeRelations>(); var all_casuals = db.Employee.Select(x => x).ToList(); var branch_entity = db.ClientSetup.FirstOrDefault(x => x.Id > 0); var category = db.EmpCategory.FirstOrDefault(x => x.Id > 0); FileStream stream = new FileStream(file_path, FileMode.Open, FileAccess.Read); try { using (var reader = ExcelReaderFactory.CreateReader(stream)) { int index = 0; while (reader.Read()) { if (index > 0) { var code = reader.GetValue(0).ToString(); var entity = all_casuals.FirstOrDefault(x => x.Code == code); EmployeeRelations employee = new EmployeeRelations(); employee.GuarantorName = reader.GetValue(1).ToString() + " " + reader.GetValue(2).ToString(); employee.GuarantorPhone = reader.GetValue(3).ToString(); employee.GuarantorAddress = ""; employee.GuarantorRelation = ""; employee.NextofKinName = ""; employee.NextofKinPhone = ""; employee.NextofKinAddress = ""; employee.NextofKinRelation = ""; employee.StaffId = entity.Id; employees.Add(employee); } index++; } reader.Close(); } if (employees.Count > 0) { db.EmployeeRelation.AddRange(employees); db.SaveChanges(); System.IO.File.Delete(file_path); complete = true; } } catch (Exception) { return complete; } return complete; } public bool ExtractNextOfKinFromFile(string file_path) { bool complete = false; List<EmployeeRelations> employees = new List<EmployeeRelations>(); var all_casuals = db.Employee.Select(x => x).ToList(); var relations = db.EmployeeRelation.Select(x => x).ToList(); FileStream stream = new FileStream(file_path, FileMode.Open, FileAccess.Read); try { using (var reader = ExcelReaderFactory.CreateReader(stream)) { int index = 0; while (reader.Read()) { if (index > 0) { var code = reader.GetValue(0).ToString(); var entity = all_casuals.FirstOrDefault(x => x.Code == code); var employee = relations.FirstOrDefault(x => x.StaffId == entity.Id); if (employee != null) { employee.NextofKinName = reader.GetValue(1).ToString() + " " + reader.GetValue(2).ToString(); employee.NextofKinPhone = reader.GetValue(3).ToString(); employee.NextofKinAddress = ""; employee.NextofKinRelation = ""; employee.StaffId = entity.Id; db.Entry<EmployeeRelations>(employee).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); employees.Add(employee); } } index++; } reader.Close(); } if (employees.Count > 0) { //db.EmployeeRelation.AddRange(employees); //db.SaveChanges(); System.IO.File.Delete(file_path); complete = true; } } catch (Exception) { return complete; } return complete; } public bool ExtractContributionFromFile(string file_path) { bool complete = false; List<EmployeeContributions> contributions = new List<EmployeeContributions>(); var all_casuals = db.Employee.Select(x => x).ToList(); var relations = db.EmployeeRelation.Select(x => x).ToList(); FileStream stream = new FileStream(file_path, FileMode.Open, FileAccess.Read); try { using (var reader = ExcelReaderFactory.CreateReader(stream)) { int index = 0; while (reader.Read()) { if (index > 0) { EmployeeContributions contribution = new EmployeeContributions(); var code = reader.GetValue(0).ToString(); var entity = all_casuals.FirstOrDefault(x => x.Code == code); if (entity != null) { contribution.StaffId = entity.Id; contribution.SSN = ""; if (string.IsNullOrWhiteSpace(reader.GetValue(1).ToString())) { contribution.SSF = false; } else { contribution.SSF = reader.GetValue(1).ToString() == "Y" ? true : false; } if (string.IsNullOrEmpty(reader.GetValue(2).ToString())) { contribution.Welfare = false; } else if ((reader.GetValue(2).ToString()) == "0" || (reader.GetValue(2).ToString()) == "N") { contribution.Welfare = false; } else if ((reader.GetValue(2).ToString()) == "1" || (reader.GetValue(2).ToString()) == "Y") { contribution.Welfare = true; } if (string.IsNullOrEmpty(reader.GetValue(3).ToString())) { contribution.UnionDues = false; } else if ((reader.GetValue(3).ToString()) == "0" || (reader.GetValue(3).ToString()) == "N") { contribution.UnionDues = false; } else if ((reader.GetValue(3).ToString()) == "1" || (reader.GetValue(3).ToString()) == "Y") { contribution.UnionDues = true; } if (string.IsNullOrEmpty(reader.GetValue(4).ToString())) { contribution.SSN = ""; } else if ((reader.GetValue(4).ToString()) == "N/A" || (reader.GetValue(4).ToString()) == "RETIRED") { contribution.SSN = ""; } else { contribution.SSN = reader.GetValue(4).ToString(); } contributions.Add(contribution); } } index++; } reader.Close(); } if (contributions.Count > 0) { db.EmployeeContribution.AddRange(contributions); db.SaveChanges(); System.IO.File.Delete(file_path); complete = true; } } catch (Exception err) { return complete; } return complete; } public bool ExtractFieldClientFromFile(string file_path) { bool complete = false; List<FieldClients> clients = new List<FieldClients>(); var all_casuals = db.Employee.Select(x => x).ToList(); var relations = db.EmployeeRelation.Select(x => x).ToList(); FileStream stream = new FileStream(file_path, FileMode.Open, FileAccess.Read); try { using (var reader = ExcelReaderFactory.CreateReader(stream)) { int index = 0; while (reader.Read()) { if (index > 0) { FieldClients client = new FieldClients(); var name = reader.GetValue(0).ToString(); var telephone = reader.GetValue(1).ToString(); var address = reader.GetValue(2).ToString(); var premium = reader.GetValue(3).ToString(); var email = reader.GetValue(4).ToString(); client.Name = name; client.Telephone1 = string.IsNullOrEmpty(telephone) ? "0000000000" : telephone; client.Address = string.IsNullOrEmpty(address) ? "N/A" : address; client.Premium = string.IsNullOrEmpty(premium) ? 0d : double.Parse(premium); client.EmailAddress = email; clients.Add(client); } index++; } reader.Close(); } if (clients.Count > 0) { db.FieldClient.AddRange(clients); db.SaveChanges(); System.IO.File.Delete(file_path); complete = true; } } catch (Exception err) { return complete; } return complete; } public bool ExtractGangTypeFromFile(string file_path) { bool complete = false; List<EmployeeCategory> gangtypes = new List<EmployeeCategory>(); var all_casuals = db.EmpCategory.Select(x => x).ToList(); FileStream stream = new FileStream(file_path, FileMode.Open, FileAccess.Read); try { using (var reader = ExcelReaderFactory.CreateReader(stream)) { int index = 0; while (reader.Read()) { if (index > 0) { EmployeeCategory gang = new EmployeeCategory(); var name = reader.GetValue(0).ToString(); if (!all_casuals.Exists(x => x.Category.ToLower().Equals(name.ToLower()))) { if (!string.IsNullOrEmpty(name)) { gang.Category = name; gang.GroupId = 0; gangtypes.Add(gang); } } } index++; } reader.Close(); } if (gangtypes.Count > 0) { db.EmpCategory.AddRange(gangtypes); db.SaveChanges(); System.IO.File.Delete(file_path); complete = true; } } catch (Exception err) { return complete; } return complete; } // public bool ExtractGangsFromFile(string file_path) { bool complete = false; List<Gang> gangs = new List<Gang>(); var all_casuals = db.Gang.Select(x => x).ToList(); var branch_entity = db.ClientSetup.FirstOrDefault(x => x.Id > 0); FileStream stream = new FileStream(file_path, FileMode.Open, FileAccess.Read); try { using (var reader = ExcelReaderFactory.CreateReader(stream)) { int index = 0; while (reader.Read()) { if (index > 0) { Gang gang = new Gang(); var name = reader.GetValue(0).ToString(); var code = SequenceHelper.getSequence(db, SequenceHelper.NType.GANG_NUMBER); if (!all_casuals.Exists(x => x.Description.ToLower().Equals(name.ToLower()))) { if (!string.IsNullOrEmpty(name)) { gang.Description = name; gang.Branch = branch_entity.Id; gang.Status = "ACTIVE"; gang.Code = code; } } gangs.Add(gang); SequenceHelper.IncreaseSequence(db, SequenceHelper.NType.GANG_NUMBER); } index++; } reader.Close(); } if (gangs.Count > 0) { db.Gang.AddRange(gangs); db.SaveChanges(); System.IO.File.Delete(file_path); complete = true; } } catch (Exception) { return complete; } return complete; } } }
using System.Collections.Generic; namespace SGDE.Domain.Entities { public class Partida : BaseEntity { public string Codigo { get; set; } public string Orden { get; set; } public string Descripcion { get; set; } public string Unidades { get; set; } public double? UnidadesCertificacionAnterior { get; set; } public double? UnidadesCertificacionActual { get; set; } public double? UnidadesPresupuesto { get; set; } public double? PresupuestoCapitulo { get; set; } public string Type { get; set; } public virtual ICollection<Partida> SubCapitulos { get; set; } = new HashSet<Partida>(); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net.Http; using System.Windows.Input; using City_Center.Models; using City_Center.Services; using GalaSoft.MvvmLight.Command; using Xamarin.Forms; using static City_Center.Models.NotificacionesRecibidasResultado; using static City_Center.Models.NotificacionesResultado; namespace City_Center.ViewModels { public class NotificacionesViewModel:BaseViewModel { #region Services private ApiService apiService; #endregion #region Attributes private NotificacionesRecibidasReturn list; private ObservableCollection<NotificacionesRecibidasDetalle> NotificacionesDetalle; #endregion #region Methods private async void LoadNotificaciones() { var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("nus_id_usuario",Application.Current.Properties["IdUsuario"].ToString()) }); var response = await this.apiService.Get<NotificacionesRecibidasReturn>("/notificaciones/", "NotificacionesRecibidas", content); if (!response.IsSuccess) { return; } this.list = (NotificacionesRecibidasReturn)response.Result; NotificacionesDetalle = new ObservableCollection<NotificacionesRecibidasDetalle>(this.ToPromocionesItemViewModel()); } private IEnumerable<NotificacionesRecibidasDetalle> ToPromocionesItemViewModel() { return this.list.respuesta.Select(l => new NotificacionesRecibidasDetalle { nen_id = l.nen_id, nen_equipo =l.nen_equipo, nen_id_usuario = l.nen_id_usuario, nen_titulo = l.nen_titulo, nen_mensaje =l.nen_mensaje, }); } //nen_fecha_hora_creo =l.nen_fecha_hora_creo, //nen_fecha_hora_modifico =l.nen_fecha_hora_creo, // nen_resultado =l.nen_resultado #endregion #region Contructors public NotificacionesViewModel() { this.apiService = new ApiService(); // LoadNotificaciones(); } #endregion } }
using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; #if PSL_ENABLED using PlayGen.Orchestrator.PSL.Common.LRS; #endif using PlayGen.Unity.Utilities.Localization; using UnityEngine; using UnityEngine.Networking; public class PSL_LRSManager : NetworkBehaviour { #if PSL_ENABLED #region Variables public static PSL_LRSManager Instance; // Our variables needed for sending data [SerializeField] private string _url = "http://lrs-psl.atosresearch.eu/"; [SerializeField] private string _logFileName = "PlayerSkills"; private object _body; // Our variables that identify the players and the match, used when sending data through LRS private string _matchId; private List<string> _playerIds = new List<string>(); // Our tracked variables to be sent throught LRS private int _totalAttempts; private int _totalGoalReached; private int _totalRoundComplete; private List<int> _timeTakenPerRound = new List<int>(); private double _averageTimeTaken { get { return _timeTakenPerRound.Average(); } set { } } // Our variables defined by the current game private int _totalRounds; public int TimeLimit { get; private set; } #endregion void Awake() { TimeLimit = 600; Instance = this; } #region public methods - game tracking /// <summary> /// Save the match Id and player Id locally to use with LRS /// </summary> /// <param name="matchId">The current match id as defined in the orchestrator</param> /// <param name="playerId">The current player id as defined in the orchestrator</param> [ServerAccess] public void JoinedGame(string matchId, string playerId) { var method = MethodBase.GetCurrentMethod(); var attr = (ServerAccess)method.GetCustomAttributes(typeof(ServerAccess), true)[0]; if (!attr.HasAccess) { return; } _matchId = matchId; // Make sure the player has not rejoined without being removed properly if (!_playerIds.Contains(playerId)) { _playerIds.Add(playerId); } } /// <summary> /// Setupd the game variables /// </summary> /// <param name="totalTime">Total time available</param> [ServerAccess] public void SetTotalTime(int totalTime) { var method = MethodBase.GetCurrentMethod(); var attr = (ServerAccess)method.GetCustomAttributes(typeof(ServerAccess), true)[0]; if (!attr.HasAccess) { return; } TimeLimit = totalTime; } /// <summary> /// Setupd the game variables /// </summary> /// <param name="numRounds">Total number of rounds available</param> [ServerAccess] public void SetNumRounds(int numRounds) { var method = MethodBase.GetCurrentMethod(); var attr = (ServerAccess)method.GetCustomAttributes(typeof(ServerAccess), true)[0]; if (!attr.HasAccess) { return; } _totalRounds = numRounds; } /// <summary> /// Players are attempting the level again /// </summary> [ServerAccess] public void NewAttempt() { var method = MethodBase.GetCurrentMethod(); var attr = (ServerAccess)method.GetCustomAttributes(typeof(ServerAccess), true)[0]; if (!attr.HasAccess) { return; } _totalAttempts += 1; } /// <summary> /// Players have made it to the chest /// </summary> [ServerAccess] public void ChestReached() { var method = MethodBase.GetCurrentMethod(); var attr = (ServerAccess)method.GetCustomAttributes(typeof(ServerAccess), true)[0]; if (!attr.HasAccess) { return; } _totalGoalReached += 1; } /// <summary> /// Players have made it to the new round /// </summary> [ServerAccess] public void NewRound(int timeTaken) { var method = MethodBase.GetCurrentMethod(); var attr = (ServerAccess)method.GetCustomAttributes(typeof(ServerAccess), true)[0]; if (!attr.HasAccess) { return; } _timeTakenPerRound.Add(timeTaken); _totalRoundComplete += 1; // Not interested in skill data for standalone if (!SP_Manager.Instance.IsSinglePlayer() && PlatformSelection.ConnectionType != ConnectionType.Testing) { SendSkillData(false, timeTaken); } } /// <summary> /// Game has been completed /// </summary> /// <param name="allChallengesComplete">Are all challenges in mode completed</param> [ServerAccess] public void GameCompleted(int timeTaken) { var method = MethodBase.GetCurrentMethod(); var attr = (ServerAccess)method.GetCustomAttributes(typeof(ServerAccess), true)[0]; if (!attr.HasAccess) { return; } // Not interested in skill data for standalone if (!SP_Manager.Instance.IsSinglePlayer() && PlatformSelection.ConnectionType != ConnectionType.Testing) { SendSkillData(false, timeTaken); } } [ServerAccess] public void PlayerShowedSkill(string playerId, LRSSkillVerb verb, int increment) { var method = MethodBase.GetCurrentMethod(); var attr = (ServerAccess)method.GetCustomAttributes(typeof(ServerAccess), true)[0]; if (!attr.HasAccess) { return; } PlatformSelection.AddSkill(playerId, verb, increment); } [ServerAccess] public void SendSkillData(bool finalResult, int timeTaken) { var method = MethodBase.GetCurrentMethod(); var attr = (ServerAccess)method.GetCustomAttributes(typeof(ServerAccess), true)[0]; if (!attr.HasAccess) { return; } // Send to LRS PlatformSelection.SendSkillData(); SendTrackedData(timeTaken); // Output to file var individualData = PlatformSelection.OutputSkillData(); OutputTrackedData(individualData, finalResult, timeTaken); } #endregion #region private methods - data sending /// <summary> /// Send all the data to the LRS /// </summary> /// <param name="timeTaken">Time taken to complete all rounds</param> [ServerAccess] private void SendTrackedData(int timeTaken) { var method = MethodBase.GetCurrentMethod(); var attr = (ServerAccess)method.GetCustomAttributes(typeof(ServerAccess), true)[0]; if (!attr.HasAccess) { return; } if (_url == "") { return; } var form = new WWWForm(); form.AddField("Attempts", _totalAttempts); form.AddField("ChestsReached", _totalGoalReached); form.AddField("CalculationSuccessRate", Mathf.RoundToInt(((float)_totalRoundComplete / (float)_totalGoalReached) * 100f)); form.AddField("RoundsComplete", _totalRoundComplete); form.AddField("TimeTaken", timeTaken); form.AddField("ProblemsComplete", (Mathf.RoundToInt(((float)_totalRoundComplete / (float)_totalRounds) * 100f))); form.AddField("MatchId", _matchId); foreach (var playerId in _playerIds) { StartCoroutine(SendPlayerData(form, playerId)); } } /// <summary> /// Output the tracked data to log /// </summary> /// <param name="timeTaken"></param> [ServerAccess] private void OutputTrackedData(string individualData, bool finalResult, int timeTaken) { var method = MethodBase.GetCurrentMethod(); var attr = (ServerAccess)method.GetCustomAttributes(typeof(ServerAccess), true)[0]; if (!attr.HasAccess) { return; } if (!finalResult) { StartCoroutine(WriteToFile(individualData + "\nAttempts: " + _totalAttempts + "\nChests Reached: " + _totalGoalReached + "\nCalculation Success Rate: " + Mathf.RoundToInt( ((float) _totalRoundComplete / (float) _totalGoalReached) * 100f) + "%" + "\nRounds Complete: " + _totalRoundComplete + "\nTime Taken: " + timeTaken + //"\nProblems Complete: " + (Mathf.RoundToInt(((float)_totalRoundComplete / (float)_totalRounds) * 100f)) + "\n\n")); } else { StartCoroutine(WriteToFile("\nFinal Result for game\n" + individualData + "\nTotal Attempts: " + _totalAttempts + "\nChests Reached: " + (_totalGoalReached-1) + "\nCalculation Success Rate: " + Mathf.RoundToInt( ((float) _totalRoundComplete / (float) _totalGoalReached) * 100f) + "%" + "\nRounds Complete: " + (_totalRoundComplete-1) + "\nTotal Time Taken: " + timeTaken + //"\nProblems Complete: " + (Mathf.RoundToInt(((float)_totalRoundComplete / (float)_totalRounds) * 100f)) + "\n-----------------------------------------------------\n")); } } [ServerAccess] private IEnumerator SendPlayerData(WWWForm data, string playerId) { var method = MethodBase.GetCurrentMethod(); var arr = method.GetCustomAttributes(typeof(ServerAccess), true); if (arr.Length > 0) { var attr = (ServerAccess)arr[0]; if (attr.HasAccess) { data.AddField("PlayerId", playerId); var www = new WWW(_url, data); yield return www; } } } [ServerAccess] private IEnumerator WriteToFile(string message) { var method = MethodBase.GetCurrentMethod(); var arr = method.GetCustomAttributes(typeof(ServerAccess), true); if (arr.Length > 0) { var attr = (ServerAccess) arr[0]; if (attr.HasAccess) { var path = Application.streamingAssetsPath + "/" + _logFileName; if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WSAPlayerX86 || Application.platform == RuntimePlatform.WSAPlayerX64 || Application.platform == RuntimePlatform.LinuxPlayer) { path = "file:///" + path; } var www = new WWW(path); yield return www; if (www.text != null) { var newtext = www.text + message; using (var sw = new StreamWriter(Application.streamingAssetsPath + "/" + _logFileName)) { sw.Write(newtext); } } } } } #endregion #endif }
using Microsoft.Extensions.Logging; using OmniSharp.Extensions.DebugAdapter.Protocol.Events; using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Client; namespace OmniSharp.Extensions.DebugAdapter.Protocol { class DapOutputFilter : IOutputFilter { private readonly ILogger<DapOutputFilter> _logger; public DapOutputFilter(ILogger<DapOutputFilter> logger) { _logger = logger; } public bool ShouldOutput(object value) { var result = value is OutgoingResponse || value is OutgoingNotification { Params: InitializedEvent } || value is OutgoingRequest { Params: InitializeRequestArguments }; if (!result) { _logger.LogWarning("Tried to send request or notification before initialization was completed and will be sent later {@Request}", value); } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace AsyncDelegates.Examples { public static class AsyncFuncExample { public static void ShowAsyncFunc() { Func<int, int> myDelegate = x => { Thread.Sleep(3000); return x * 2; }; //Invoke delagate asynchronously var asyncResult = myDelegate.BeginInvoke(5, null, null); Console.WriteLine("Main thread is keep working"); int result = myDelegate.EndInvoke(asyncResult); Console.WriteLine(result); } } }
namespace ns17 { using System; internal interface Interface13 : Interface10 { string String_3 { get; } string String_4 { get; set; } string String_5 { get; set; } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace System.Data.Linq.SqlClient { internal class SqlDeflator { SqlValueDeflator vDeflator; SqlColumnDeflator cDeflator; SqlAliasDeflator aDeflator; SqlTopSelectDeflator tsDeflator; SqlDuplicateColumnDeflator dupColumnDeflator; internal SqlDeflator() { this.vDeflator = new SqlValueDeflator(); this.cDeflator = new SqlColumnDeflator(); this.aDeflator = new SqlAliasDeflator(); this.tsDeflator = new SqlTopSelectDeflator(); this.dupColumnDeflator = new SqlDuplicateColumnDeflator(); } internal SqlNode Deflate(SqlNode node) { node = this.vDeflator.Visit(node); node = this.cDeflator.Visit(node); node = this.aDeflator.Visit(node); node = this.tsDeflator.Visit(node); node = this.dupColumnDeflator.Visit(node); return node; } // remove references to literal values class SqlValueDeflator : SqlVisitor { SelectionDeflator sDeflator; bool isTopLevel = true; internal SqlValueDeflator() { this.sDeflator = new SelectionDeflator(); } internal override SqlSelect VisitSelect(SqlSelect select) { if (this.isTopLevel) { select.Selection = sDeflator.VisitExpression(select.Selection); } return select; } internal override SqlExpression VisitSubSelect(SqlSubSelect ss) { bool saveIsTopLevel = this.isTopLevel; try { return base.VisitSubSelect(ss); } finally { this.isTopLevel = saveIsTopLevel; } } class SelectionDeflator : SqlVisitor { internal override SqlExpression VisitColumnRef(SqlColumnRef cref) { SqlExpression literal = this.GetLiteralValue(cref); if (literal != null) { return literal; } return cref; } private SqlValue GetLiteralValue(SqlExpression expr) { while (expr != null && expr.NodeType == SqlNodeType.ColumnRef) { expr = ((SqlColumnRef)expr).Column.Expression; } return expr as SqlValue; } } } // remove unreferenced items in projection list class SqlColumnDeflator : SqlVisitor { Dictionary<SqlNode, SqlNode> referenceMap; bool isTopLevel; bool forceReferenceAll; SqlAggregateChecker aggregateChecker; internal SqlColumnDeflator() { this.referenceMap = new Dictionary<SqlNode, SqlNode>(); this.aggregateChecker = new SqlAggregateChecker(); this.isTopLevel = true; } internal override SqlExpression VisitColumnRef(SqlColumnRef cref) { this.referenceMap[cref.Column] = cref.Column; return cref; } internal override SqlExpression VisitScalarSubSelect(SqlSubSelect ss) { bool saveIsTopLevel = this.isTopLevel; this.isTopLevel = false; bool saveForceReferenceAll = this.forceReferenceAll; this.forceReferenceAll = true; try { return base.VisitScalarSubSelect(ss); } finally { this.isTopLevel = saveIsTopLevel; this.forceReferenceAll = saveForceReferenceAll; } } internal override SqlExpression VisitExists(SqlSubSelect ss) { bool saveIsTopLevel = this.isTopLevel; this.isTopLevel = false; try { return base.VisitExists(ss); } finally { this.isTopLevel = saveIsTopLevel; } } internal override SqlNode VisitUnion(SqlUnion su) { bool saveForceReferenceAll = this.forceReferenceAll; this.forceReferenceAll = true; su.Left = this.Visit(su.Left); su.Right = this.Visit(su.Right); this.forceReferenceAll = saveForceReferenceAll; return su; } internal override SqlSelect VisitSelect(SqlSelect select) { bool saveForceReferenceAll = this.forceReferenceAll; this.forceReferenceAll = false; bool saveIsTopLevel = this.isTopLevel; try { if (this.isTopLevel) { // top-level projection references columns! select.Selection = this.VisitExpression(select.Selection); } this.isTopLevel = false; for (int i = select.Row.Columns.Count - 1; i >= 0; i--) { SqlColumn c = select.Row.Columns[i]; bool safeToRemove = !saveForceReferenceAll && !this.referenceMap.ContainsKey(c) // don't remove anything from a distinct select (except maybe a literal value) since it would change the meaning of the comparison && !select.IsDistinct // don't remove an aggregate expression that may be the only expression that forces the grouping (since it would change the cardinality of the results) && !(select.GroupBy.Count == 0 && this.aggregateChecker.HasAggregates(c.Expression)); if (safeToRemove) { select.Row.Columns.RemoveAt(i); } else { this.VisitExpression(c.Expression); } } select.Top = this.VisitExpression(select.Top); for (int i = select.OrderBy.Count - 1; i >= 0; i--) { select.OrderBy[i].Expression = this.VisitExpression(select.OrderBy[i].Expression); } select.Having = this.VisitExpression(select.Having); for (int i = select.GroupBy.Count - 1; i >= 0; i--) { select.GroupBy[i] = this.VisitExpression(select.GroupBy[i]); } select.Where = this.VisitExpression(select.Where); select.From = this.VisitSource(select.From); } finally { this.isTopLevel = saveIsTopLevel; this.forceReferenceAll = saveForceReferenceAll; } return select; } internal override SqlSource VisitJoin(SqlJoin join) { join.Condition = this.VisitExpression(join.Condition); join.Right = this.VisitSource(join.Right); join.Left = this.VisitSource(join.Left); return join; } internal override SqlNode VisitLink(SqlLink link) { // don't visit expansion... for (int i = 0, n = link.KeyExpressions.Count; i < n; i++) { link.KeyExpressions[i] = this.VisitExpression(link.KeyExpressions[i]); } return link; } } class SqlColumnEqualizer : SqlVisitor { Dictionary<SqlColumn, SqlColumn> map; internal SqlColumnEqualizer() { } internal void BuildEqivalenceMap(SqlSource scope) { this.map = new Dictionary<SqlColumn, SqlColumn>(); this.Visit(scope); } internal bool AreEquivalent(SqlExpression e1, SqlExpression e2) { if (SqlComparer.AreEqual(e1, e2)) return true; SqlColumnRef cr1 = e1 as SqlColumnRef; SqlColumnRef cr2 = e2 as SqlColumnRef; if (cr1 != null && cr2 != null) { SqlColumn c1 = cr1.GetRootColumn(); SqlColumn c2 = cr2.GetRootColumn(); SqlColumn r; return this.map.TryGetValue(c1, out r) && r == c2; } return false; } internal override SqlSource VisitJoin(SqlJoin join) { base.VisitJoin(join); if (join.Condition != null) { this.CheckJoinCondition(join.Condition); } return join; } internal override SqlSelect VisitSelect(SqlSelect select) { base.VisitSelect(select); if (select.Where != null) { this.CheckJoinCondition(select.Where); } return select; } [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification="Microsoft: Cast is dependent on node type and casts do not happen unecessarily in a single code path.")] private void CheckJoinCondition(SqlExpression expr) { switch (expr.NodeType) { case SqlNodeType.And: { SqlBinary b = (SqlBinary)expr; CheckJoinCondition(b.Left); CheckJoinCondition(b.Right); break; } case SqlNodeType.EQ: case SqlNodeType.EQ2V: { SqlBinary b = (SqlBinary)expr; SqlColumnRef crLeft = b.Left as SqlColumnRef; SqlColumnRef crRight = b.Right as SqlColumnRef; if (crLeft != null && crRight != null) { SqlColumn cLeft = crLeft.GetRootColumn(); SqlColumn cRight = crRight.GetRootColumn(); this.map[cLeft] = cRight; this.map[cRight] = cLeft; } break; } } } internal override SqlExpression VisitSubSelect(SqlSubSelect ss) { return ss; } } // remove redundant/trivial aliases class SqlAliasDeflator : SqlVisitor { Dictionary<SqlAlias, SqlAlias> removedMap; internal SqlAliasDeflator() { this.removedMap = new Dictionary<SqlAlias, SqlAlias>(); } internal override SqlExpression VisitAliasRef(SqlAliasRef aref) { SqlAlias alias = aref.Alias; SqlAlias value; if (this.removedMap.TryGetValue(alias, out value)) { throw Error.InvalidReferenceToRemovedAliasDuringDeflation(); } return aref; } internal override SqlExpression VisitColumnRef(SqlColumnRef cref) { if (cref.Column.Alias != null && this.removedMap.ContainsKey(cref.Column.Alias)) { SqlColumnRef c = cref.Column.Expression as SqlColumnRef; if (c != null) { //The following code checks for cases where there are differences between the type returned //by a ColumnRef and the column that refers to it. This situation can occur when conversions //are optimized out of the SQL node tree. As mentioned in the SetClrType comments this is not //an operation that can have adverse effects and should only be used in limited cases, such as //this one. if (c.ClrType != cref.ClrType) { c.SetClrType(cref.ClrType); return this.VisitColumnRef(c); } } return c; } return cref; } internal override SqlSource VisitSource(SqlSource node) { node = (SqlSource)this.Visit(node); SqlAlias alias = node as SqlAlias; if (alias != null) { SqlSelect sel = alias.Node as SqlSelect; if (sel != null && this.IsTrivialSelect(sel)) { this.removedMap[alias] = alias; node = sel.From; } } return node; } internal override SqlSource VisitJoin(SqlJoin join) { base.VisitJoin(join); switch (join.JoinType) { case SqlJoinType.Cross: case SqlJoinType.Inner: // reducing either side would effect cardinality of results break; case SqlJoinType.LeftOuter: case SqlJoinType.CrossApply: case SqlJoinType.OuterApply: // may reduce to left if no references to the right if (this.HasEmptySource(join.Right)) { SqlAlias a = (SqlAlias)join.Right; this.removedMap[a] = a; return join.Left; } break; } return join; } private bool IsTrivialSelect(SqlSelect select) { if (select.OrderBy.Count != 0 || select.GroupBy.Count != 0 || select.Having != null || select.Top != null || select.IsDistinct || select.Where != null) return false; return this.HasTrivialSource(select.From) && this.HasTrivialProjection(select); } private bool HasTrivialSource(SqlSource node) { SqlJoin join = node as SqlJoin; if (join != null) { return this.HasTrivialSource(join.Left) && this.HasTrivialSource(join.Right); } return node is SqlAlias; } [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification="Unknown reason.")] private bool HasTrivialProjection(SqlSelect select) { foreach (SqlColumn c in select.Row.Columns) { if (c.Expression != null && c.Expression.NodeType != SqlNodeType.ColumnRef) { return false; } } return true; } [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification="Unknown reason.")] private bool HasEmptySource(SqlSource node) { SqlAlias alias = node as SqlAlias; if (alias == null) return false; SqlSelect sel = alias.Node as SqlSelect; if (sel == null) return false; return sel.Row.Columns.Count == 0 && sel.From == null && sel.Where == null && sel.GroupBy.Count == 0 && sel.Having == null && sel.OrderBy.Count == 0; } } // remove duplicate columns from order by and group by lists class SqlDuplicateColumnDeflator : SqlVisitor { SqlColumnEqualizer equalizer = new SqlColumnEqualizer(); internal override SqlSelect VisitSelect(SqlSelect select) { select.From = this.VisitSource(select.From); select.Where = this.VisitExpression(select.Where); for (int i = 0, n = select.GroupBy.Count; i < n; i++) { select.GroupBy[i] = this.VisitExpression(select.GroupBy[i]); } // remove duplicate group expressions for (int i = select.GroupBy.Count - 1; i >= 0; i--) { for (int j = i - 1; j >= 0; j--) { if (SqlComparer.AreEqual(select.GroupBy[i], select.GroupBy[j])) { select.GroupBy.RemoveAt(i); break; } } } select.Having = this.VisitExpression(select.Having); for (int i = 0, n = select.OrderBy.Count; i < n; i++) { select.OrderBy[i].Expression = this.VisitExpression(select.OrderBy[i].Expression); } // remove duplicate order expressions if (select.OrderBy.Count > 0) { this.equalizer.BuildEqivalenceMap(select.From); for (int i = select.OrderBy.Count - 1; i >= 0; i--) { for (int j = i - 1; j >= 0; j--) { if (this.equalizer.AreEquivalent(select.OrderBy[i].Expression, select.OrderBy[j].Expression)) { select.OrderBy.RemoveAt(i); break; } } } } select.Top = this.VisitExpression(select.Top); select.Row = (SqlRow)this.Visit(select.Row); select.Selection = this.VisitExpression(select.Selection); return select; } } // if the top level select is simply a reprojection of the subquery, then remove it, // pushing any distinct names down class SqlTopSelectDeflator : SqlVisitor { internal override SqlSelect VisitSelect(SqlSelect select) { if (IsTrivialSelect(select)) { SqlSelect aselect = (SqlSelect)((SqlAlias)select.From).Node; // build up a column map, so we can rewrite the top-level selection expression Dictionary<SqlColumn, SqlColumnRef> map = new Dictionary<SqlColumn, SqlColumnRef>(); foreach (SqlColumn c in select.Row.Columns) { SqlColumnRef cref = (SqlColumnRef)c.Expression; map.Add(c, cref); // push the interesting column names down (non null) if (!string.IsNullOrEmpty(c.Name)) { cref.Column.Name = c.Name; } } aselect.Selection = new ColumnMapper(map).VisitExpression(select.Selection); return aselect; } return select; } private bool IsTrivialSelect(SqlSelect select) { if (select.OrderBy.Count != 0 || select.GroupBy.Count != 0 || select.Having != null || select.Top != null || select.IsDistinct || select.Where != null) return false; return this.HasTrivialSource(select.From) && this.HasTrivialProjection(select); } [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification="Unknown reason.")] private bool HasTrivialSource(SqlSource node) { SqlAlias alias = node as SqlAlias; if (alias == null) return false; return alias.Node is SqlSelect; } [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification="Unknown reason.")] private bool HasTrivialProjection(SqlSelect select) { foreach (SqlColumn c in select.Row.Columns) { if (c.Expression != null && c.Expression.NodeType != SqlNodeType.ColumnRef) { return false; } } return true; } class ColumnMapper : SqlVisitor { Dictionary<SqlColumn, SqlColumnRef> map; internal ColumnMapper(Dictionary<SqlColumn, SqlColumnRef> map) { this.map = map; } internal override SqlExpression VisitColumnRef(SqlColumnRef cref) { SqlColumnRef mapped; if (this.map.TryGetValue(cref.Column, out mapped)) { return mapped; } return cref; } } } } }
using MySql.Data.MySqlClient; 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 Stok_Takip_Otomasyonu { public partial class frmÜrünListele : Form { public frmÜrünListele() { InitializeComponent(); } MySqlConnection baglanti = new MySqlConnection("Server=localhost;Database=Stok_Takip;Uid=root;Pwd=98765Ab1."); DataSet daset = new DataSet(); private void kategorigetir() { baglanti.Open(); MySqlCommand komut = new MySqlCommand("select *from categoryinformation", baglanti); MySqlDataReader read = komut.ExecuteReader(); while (read.Read()) { comboKategori.Items.Add(read["category"].ToString()); } baglanti.Close(); } private void frmÜrünListele_Load(object sender, EventArgs e) { ÜrünListele(); kategorigetir(); } private void ÜrünListele() { baglanti.Open(); MySqlDataAdapter adtr = new MySqlDataAdapter("select *from product", baglanti); adtr.Fill(daset, "product"); dataGridView1.DataSource = daset.Tables["product"]; baglanti.Close(); } private void label1_Click(object sender, EventArgs e) { } private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e) { BarkodNotxt.Text = dataGridView1.CurrentRow.Cells["barcodeno"].Value.ToString(); Kategoritxt.Text = dataGridView1.CurrentRow.Cells["category"].Value.ToString(); Markatxt.Text = dataGridView1.CurrentRow.Cells["brand"].Value.ToString(); ÜrünAdıtxt.Text = dataGridView1.CurrentRow.Cells["productname"].Value.ToString(); Miktarıtxt.Text = dataGridView1.CurrentRow.Cells["amount"].Value.ToString(); AlışFiyatıtxt.Text = dataGridView1.CurrentRow.Cells["purchaseprice"].Value.ToString(); SatışFiyatıtxt.Text = dataGridView1.CurrentRow.Cells["saleprice"].Value.ToString(); } private void btnGüncelle_Click(object sender, EventArgs e) { baglanti.Open(); MySqlCommand komut = new MySqlCommand("update product set productname=@productname,amount=@amount,purchaseprice=@purchaseprice,saleprice=@saleprice where barcodeno=@barcodeno",baglanti); komut.Parameters.AddWithValue("@barcodeno", BarkodNotxt.Text); komut.Parameters.AddWithValue("@productname", ÜrünAdıtxt.Text); komut.Parameters.AddWithValue("@amount", int.Parse(Miktarıtxt.Text)); komut.Parameters.AddWithValue("@purchaseprice", double.Parse(AlışFiyatıtxt.Text)); komut.Parameters.AddWithValue("@saleprice",double.Parse(SatışFiyatıtxt.Text)); komut.ExecuteNonQuery(); baglanti.Close(); daset.Tables["product"].Clear(); ÜrünListele(); MessageBox.Show("Was updated."); foreach(Control item in this.Controls) { if(item is TextBox) { item.Text = ""; } } } private void btnMarkaGuncelle_Click(object sender, EventArgs e) { if (BarkodNotxt.Text != "") { baglanti.Open(); MySqlCommand komut = new MySqlCommand("update product set category=@category,brand=@brand where barcodeno=@barcodeno", baglanti); komut.Parameters.AddWithValue("@barcodeno", BarkodNotxt.Text); komut.Parameters.AddWithValue("@category", comboKategori.Text); komut.Parameters.AddWithValue("@brand", comboMarka.Text); komut.ExecuteNonQuery(); baglanti.Close(); MessageBox.Show("Was updated."); daset.Tables["product"].Clear(); ÜrünListele(); } else { MessageBox.Show("BarcodeNo not written."); } foreach (Control item in this.Controls) { if (item is ComboBox) { item.Text = ""; } } } private void comboKategori_SelectedIndexChanged(object sender, EventArgs e) { comboMarka.Items.Clear(); comboMarka.Text = ""; baglanti.Open(); MySqlCommand komut = new MySqlCommand("select *from brandinformation where category='" + comboKategori.SelectedItem + "'", baglanti); MySqlDataReader read = komut.ExecuteReader(); while (read.Read()) { comboMarka.Items.Add(read["brand"].ToString()); } baglanti.Close(); } private void btnSil_Click(object sender, EventArgs e) { baglanti.Open(); MySqlCommand komut = new MySqlCommand("delete from product where barcodeno='" + dataGridView1.CurrentRow.Cells["barcodeno"].Value.ToString() + "'", baglanti); komut.ExecuteNonQuery(); baglanti.Close(); daset.Tables["product"].Clear(); ÜrünListele(); MessageBox.Show("Registration deleted."); } private void txtBarkodNoAra_TextChanged(object sender, EventArgs e) { DataTable tablo = new DataTable(); baglanti.Open(); MySqlDataAdapter adtr = new MySqlDataAdapter("select *from product where barcodeno like '%" + txtBarkodNoAra.Text + "%'", baglanti); adtr.Fill(tablo); dataGridView1.DataSource = tablo; baglanti.Close(); } private void pictureBox1_Click(object sender, EventArgs e) { pictureBox1.Image = Properties.Resources.satıış_listele; } } }
using Aries.Core.Auth; using Aries.Core.Extend; using Aries.Core.Helper; using CYQ.Data; using CYQ.Data.Cache; using CYQ.Data.Tool; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Web; namespace Aries.Core { /// <summary> /// 权限检测模块 /// </summary> public class UrlRewrite : IHttpModule { public void Dispose() { } static bool isFirstLoad = false; public void Init(HttpApplication context) { if (!isFirstLoad) { isFirstLoad = true; CrossDb.PreLoadAllDBSchemeToCache(); } context.BeginRequest += new EventHandler(context_BeginRequest); context.PostMapRequestHandler += context_PostMapRequestHandler; context.AcquireRequestState += context_AcquireRequestState; context.Error += context_Error; } void context_PostMapRequestHandler(object sender, EventArgs e) { if (WebHelper.IsAriesSuffix()) { string localPath = context.Request.Url.LocalPath; string uriPath = Path.GetFileNameWithoutExtension(localPath).ToLower(); if (uriPath == "ajax") { context.Handler = SessionHandler.Instance;//注册Session } } } HttpContext context; void context_BeginRequest(object sender, EventArgs e) { HttpApplication app = (HttpApplication)sender; context = app.Context; if (context.Request.Url.LocalPath == "/")//设置默认首页 { string defaultUrl = WebHelper.GetDefaultUrl(); if (!string.IsNullOrEmpty(defaultUrl)) { context.RewritePath(defaultUrl, false); } } } void context_Error(object sender, EventArgs e) { if (WebHelper.IsAriesSuffix()) { Log.WriteLogToTxt(HttpContext.Current.Error); } } void context_AcquireRequestState(object sender, EventArgs e) { if (WebHelper.IsAriesSuffix()) { string localPath = context.Request.Url.LocalPath; string uriPath = Path.GetFileNameWithoutExtension(localPath).ToLower(); switch (uriPath) { case "logout": UserAuth.Logout(); break; case "login": LoginView(); break; case "ajax": InvokeClass(); break; default://普通页面 AuthCheck(uriPath == "index"); ReplaceOutput(); break; } } } #region LoginView 页处理 private void LoginView() { SetSafeKey(); if (WebHelper.IsUseUISite) { HttpCookie cookie = context.Request.Cookies["sys_ui"]; if (cookie == null) { cookie = new HttpCookie("sys_ui", "/" + AppConfig.GetApp("UI").Trim('/')); cookie.Domain = AppConfig.XHtml.Domain; context.Response.Cookies.Add(cookie); } } //context.Response.Write(" ");//避免服务器不输出Cookie。,会引发:ERR_CONTENT_DECODING_FAILED异常。 //cannot decode raw data” (NSURLErrorDomain:-1015) } #endregion #region AuthCheck 授权检测 /// <summary> /// 默认仅对Web目录和首页index.html进行登陆权限检测。 /// </summary> private void AuthCheck(bool isIndex) { SetNoCacheAndSafeKey();//.html不缓存,才能实时检测权限问题。(否则客户端缓存了,后台修改权限,客户端很为难) if (WebHelper.IsCheckToken()) { UserAuth.IsExistsToken(true);//检测登陆状态。 UserAuth.RefleshToken(); //刷新时间 if (!isIndex) { new Permission(UserAuth.UserName, true);//是否有访问该页面的权限。(100-500ms)【第一次500ms左右】,【第二次数据已缓存,100ms左右】(再优化就是缓存用户与菜单,可以减少到接近0,但无法保证实时性) } } } private void SetNoCacheAndSafeKey() { context.Response.Expires = 0; context.Response.Buffer = true; context.Response.ExpiresAbsolute = DateTime.Now.AddYears(-1); context.Response.CacheControl = "no-cache"; SetSafeKey(); } private void SetSafeKey() { HttpCookie cookie = context.Request.Cookies["aries_safekey"]; if (cookie == null) { cookie = new HttpCookie("aries_safekey"); } cookie.HttpOnly = true; cookie.Domain = AppConfig.XHtml.Domain; cookie.Value = EncrpytHelper.Encrypt("aries:" + DateTime.Now.ToString("HHmmss")); cookie.Expires = DateTime.Now.AddHours(23); context.Response.Cookies.Add(cookie); } private bool IsExistsSafeKey() { HttpCookie cookie = context.Request.Cookies["aries_safekey"]; if (cookie != null) { string value = EncrpytHelper.Decrypt(cookie.Value); if (value.StartsWith("aries:")) { return true; } } return false; } #endregion #region ReplaceOutput 替换输出,仅对子目录部署时有效 void ReplaceOutput() { if (WebHelper.IsUseUISite) { //如果项目需要部署成子应用程序,则开启,否则不需要开启(可注释掉下面一行代码) context.Response.Filter = new HttpResponseFilter(context.Response.Filter); } } #endregion #region InvokeClass 逻辑反射调用Controlls的方法 private void InvokeClass() { Type t = null; #region 处理Ajax请求 //从Url来源页找 if (context.Request.UrlReferrer == null) { WriteError("Illegal request!"); } else if (!IsExistsSafeKey() && WebHelper.IsCheckToken())// 仅检测需要登陆的页面 { string path = context.Request.UrlReferrer.PathAndQuery; if (path == "/") { path = "/index.html"; } WriteError(path);//"Page timeout,please reflesh page!" } //AjaxController是由页面的后两个路径决定了。 string[] items = context.Request.UrlReferrer.LocalPath.TrimStart('/').Split('/'); string className = Path.GetFileNameWithoutExtension(items[items.Length - 1].ToLower()); //从来源页获取className 可能是/aaa/bbb.shtml 先找aaa.bbb看看有木有,如果没有再找bbb if (items.Length > 1) { t = InvokeLogic.GetType(items[items.Length - 2].ToLower() + "." + className); } if (t == null) { t = InvokeLogic.GetDefaultType(); if (t == null) { WriteError("You need to create a controller for coding !"); } } #endregion try { object o = Activator.CreateInstance(t);//实例化 t.GetMethod("ProcessRequest").Invoke(o, new object[] { context }); } catch (ThreadAbortException e) { //ASP.NET 的机制就是通过异常退出线程(不要觉的奇怪) } catch (Exception err) { WriteError(err.Message); } } private void WriteError(string tip) { context.Response.Write(JsonHelper.OutResult(false, tip)); context.Response.End(); } #endregion } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using DotNetNuke.Entities.Content.Workflow.Entities; using System.Collections.Generic; namespace DotNetNuke.Entities.Content.Workflow { /// <summary> /// This class is responsible to manage the workflows of the portal. /// It provides CRUD operation methods and methods to know the usage of the workflow /// </summary> public interface IWorkflowManager { /// <summary> /// This method returns the paginated list of Items that are associated with a workflow /// </summary> /// <param name="workflowId">Workflow Id</param> /// <param name="pageIndex">Page index (where 1 is the index of the first page)</param> /// <param name="pageSize">Page size</param> /// <returns>List of Usage Items</returns> IEnumerable<WorkflowUsageItem> GetWorkflowUsage(int workflowId, int pageIndex, int pageSize); /// <summary> /// This method returns the total number of Content Items that are associated with any State of a workflow (even the Published state) /// </summary> /// <param name="workflowId">Workflow Id</param> /// <returns>Total count of Content Items that are using the specified workflow</returns> int GetWorkflowUsageCount(int workflowId); /// <summary> /// This method return the list of the Workflows defined for the portal /// </summary> /// <param name="portalId">Portal Id</param> /// <returns>List of the Workflows for the portal</returns> IEnumerable<Entities.Workflow> GetWorkflows(int portalId); /// <summary> /// This method adds a new workflow. It automatically add two system states: "Draft" and "Published" /// </summary> /// <param name="workflow">Workflow Entity</param> /// <exception cref="DotNetNuke.Entities.Content.Workflow.Exceptions.WorkflowNameAlreadyExistsException">Thrown when a workflow with the same name already exist for the portal</exception> void AddWorkflow(Entities.Workflow workflow); /// <summary> /// this method update a existing workflow. /// </summary> /// <param name="workflow">Workflow Entity</param> /// <exception cref="DotNetNuke.Entities.Content.Workflow.Exceptions.WorkflowNameAlreadyExistsException">Thrown when a workflow with the same name already exist for the portal</exception> void UpdateWorkflow(Entities.Workflow workflow); /// <summary> /// This method hard deletes a workflow /// </summary> /// <param name="workflow">Workflow Entity</param> /// <exception cref="DotNetNuke.Entities.Content.Workflow.Exceptions.WorkflowInvalidOperationException">Thrown when a workflow is in use or is a system workflow</exception> void DeleteWorkflow(Entities.Workflow workflow); /// <summary> /// This method returns a workflow entity by Id /// </summary> /// <param name="workflowId">Workflow Id</param> /// <returns>Workflow Entity</returns> Entities.Workflow GetWorkflow(int workflowId); /// <summary> /// This method returns a workflow entity by Content Item Id. It returns null if the Content Item is not under workflow. /// </summary> /// <param name="contentItem">Content Item</param> /// <returns>Workflow Entity</returns> Entities.Workflow GetWorkflow(ContentItem contentItem); } }
// Copyright 2020 Google Inc. 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 NtApiDotNet.Utilities.ASN1; using System.IO; using System.Text; namespace NtApiDotNet.Win32.Security.Authentication.Kerberos { /// <summary> /// Class to represent a Kerberos Checksum. /// </summary> public class KerberosChecksum { /// <summary> /// Type of kerberos checksum. /// </summary> public KerberosChecksumType ChecksumType { get;} /// <summary> /// The checksum value. /// </summary> public byte[] Checksum { get; } internal virtual void Format(StringBuilder builder) { builder.AppendLine($"Checksum : {ChecksumType} - {NtObjectUtils.ToHexString(Checksum)}"); } private protected KerberosChecksum(KerberosChecksumType type, byte[] data) { ChecksumType = type; Checksum = data; } internal static KerberosChecksum Parse(DERValue value) { if (!value.CheckSequence()) throw new InvalidDataException(); KerberosChecksumType type = 0; byte[] data = null; foreach (var next in value.Children) { if (next.Type != DERTagType.ContextSpecific) throw new InvalidDataException(); switch (next.Tag) { case 0: type = (KerberosChecksumType)next.ReadChildInteger(); break; case 1: data = next.ReadChildOctetString(); break; default: throw new InvalidDataException(); } } if (type == 0 || data == null) throw new InvalidDataException(); if (type == KerberosChecksumType.GSSAPI && KerberosChecksumGSSApi.Parse(data, out KerberosChecksum chksum)) { return chksum; } return new KerberosChecksum(type, data); } } }
using System; using System.Collections.Generic; using System.Text; namespace Converter.Units { class Byte : DataUnit { protected override double UnitDevidedByByte => 1; public override string ToString() { return nameof(Byte); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; class Program { static void Main() { var validSingers = GetInput(); var validSongs = GetInput(); var singers = new List<Singer>(); while (true) { var input = GetInput(); if (input.First() == "dawn") { break; } var name = input[0]; var song = input[1]; var award = input[2]; if (!(validSingers.Contains(name) && validSongs.Contains(song))) { continue; } var currSinger = new Singer { Name = name, Songs = new List<string> { song }, Awards = new HashSet<string> { award }, }; if (!singers.Any(singer => singer.Name == currSinger.Name)) { singers.Add(currSinger); } else { currSinger = singers.First(singer => singer.Name == name); currSinger.Songs.Add(song); currSinger.Awards.Add(award); } } if (!singers.Any()) { Console.WriteLine("No awards"); return; } foreach (var currSinger in singers .OrderByDescending(singer => singer.AwardsCount) .ThenBy(singer => singer.Name)) { currSinger.PrintStats(); currSinger.PrintAwards(); } } public static string[] GetInput() { return Regex.Split(Console.ReadLine(), @"\,\s") .ToArray(); } } internal class Singer { public string Name { get; set; } public List<string> Songs { get; set; } public HashSet<string> Awards { get; set; } public int AwardsCount => this.Awards.Count(); public void PrintStats() { Console.WriteLine($"{this.Name}: {this.AwardsCount} awards"); } public void PrintAwards() { foreach (var currAward in Awards .OrderBy(award => award)) { Console.WriteLine($"--{currAward}"); } } }
using CourseProject.Model; using CourseProject_WPF_.Repositories; using System; using System.ComponentModel; using System.Text.RegularExpressions; namespace CourseProject.ViewModel { public class RegistrationViewModel : INotifyPropertyChanged { EfUserRepository userRepository = new EfUserRepository(); string firstName; string secondName; string mail; string password1; string password2; string info; public string FirstName { get { return firstName; } set { firstName = value; OnPropertyChanged("FirstName"); } } public string SecondName { get { return secondName; } set { secondName = value; OnPropertyChanged("SecondName"); } } public string Mail { get { return mail; } set { mail = value; OnPropertyChanged("Mail"); } } public string Password1 { get { return password1; } set { password1 = value; OnPropertyChanged("Password1"); } } public string Password2 { get { return password2; } set { password2 = value; OnPropertyChanged("Password2"); } } public string Info { get { return info; } set { info = value; OnPropertyChanged("Info"); } } public bool Registration(string password1, string password2) { Password1 = password1; Password2 = password2; string firstNameRegex = @"^[А-Я]{1}[а-яё]{1,28}$|^[A-Z]{1}[a-z]{1,28}$"; string secondNameRegex = @"^[А-Я]{1}[а-яё]{1,28}$|^[A-Z]{1}[a-z]{1,28}$"; string mailRegex = @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$"; if (!String.IsNullOrEmpty(FirstName) && !String.IsNullOrEmpty(SecondName) && !String.IsNullOrEmpty(Mail) && !String.IsNullOrEmpty(Password1) && !String.IsNullOrEmpty(Password2)) { if (FirstName.Length > 1 && Regex.IsMatch(FirstName, firstNameRegex)) { if (SecondName.Length > 2 && Regex.IsMatch(SecondName, secondNameRegex)) { if (Regex.IsMatch(Mail, mailRegex, RegexOptions.IgnoreCase)) { if (Password1.Length > 0 && Password2.Length > 0) { if (Password1.Equals(Password2)) { var tmp = userRepository.GetByMail(Mail); if (tmp == null) { userRepository.Add(new User { FirstName = FirstName, SecondName = SecondName, Mail = Mail, Password = Password1, Privilege = "user" }); Info = "Зареган!"; return true; } Info = "Пользователь с таким Mail уже есть"; return false; } Info = "Пароли должны совпадать"; return false; } } Info = "Email введен некорректно"; return false; } Info = "Фамилия введена некорректно"; return false; } Info = "Имя введено некорректно"; return false; } Info = "Вы не заполнили все поля!"; return false; } public event PropertyChangedEventHandler PropertyChanged; void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } }
using System; using System.Collections.Generic; using System.Text; namespace Tarea.Models { public class Producto { public int idProducto { set; get; } public string nombreProducto { set; get; } public string tipoProducto { set; get; } public double precioUnidad { set; get; } public double precioUnidadsinIva { set; get; } public double totalProducto { set; get; } } }
namespace E03_PrintNumbers { using System; public class PrintNumbers { public static void Main(string[] args) { // Write a program to print the numbers 1, 101 and 1001, each at a separate line. // Name the program correctly. Console.WriteLine(1 + "\n" + 101 + "\n" + 1001); } } }
using SQLiteNetExtensions.Attributes; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; using ForeignKeyAttribute = SQLiteNetExtensions.Attributes.ForeignKeyAttribute; namespace ISKlinike.Model { [Table ("TerminPregleda")] public class TerminPregleda { public int Id { get; set; } public DateTime DatumVrijemePregleda { get; set; } public Korisnik Doktor { get; set; } public string RazlogPosjete { get; set; } public Pacijenti Pacijent { get; set; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.Serialization; using System.Xml; using UnityEditor; using UnityEngine; using UnityEngine.SceneManagement; using Object = UnityEngine.Object; using GenericObjectClipboard = InspectPlusNamespace.SerializablePropertyExtensions.GenericObjectClipboard; using ArrayClipboard = InspectPlusNamespace.SerializablePropertyExtensions.ArrayClipboard; using VectorClipboard = InspectPlusNamespace.SerializablePropertyExtensions.VectorClipboard; using ManagedObjectClipboard = InspectPlusNamespace.SerializablePropertyExtensions.ManagedObjectClipboard; namespace InspectPlusNamespace { public class SerializedClipboard { #region Serialized Types public abstract class IPObject { public string Name; protected SerializedClipboard root; protected IPObject( SerializedClipboard root ) { this.root = root; } protected IPObject( SerializedClipboard root, string name ) : this( root ) { Name = name; } public abstract object GetClipboardObject( Object context ); public virtual void WriteToXmlElement( XmlElement element ) { AppendXmlAttribute( element, "Name", Name ); } public virtual void ReadFromXmlElement( XmlElement element ) { Name = ReadXmlAttributeAsString( element, "Name" ); } protected void AppendXmlAttribute( XmlElement element, string name, string value ) { if( value == null ) return; XmlAttribute result = element.OwnerDocument.CreateAttribute( name ); result.Value = value; element.Attributes.Append( result ); } protected void AppendXmlAttribute( XmlElement element, string name, int value ) { XmlAttribute result = element.OwnerDocument.CreateAttribute( name ); result.Value = value.ToString( CultureInfo.InvariantCulture ); element.Attributes.Append( result ); } protected void AppendXmlAttribute( XmlElement element, string name, long value ) { XmlAttribute result = element.OwnerDocument.CreateAttribute( name ); result.Value = value.ToString( CultureInfo.InvariantCulture ); element.Attributes.Append( result ); } protected void AppendXmlAttribute( XmlElement element, string name, float value ) { XmlAttribute result = element.OwnerDocument.CreateAttribute( name ); result.Value = value.ToString( CultureInfo.InvariantCulture ); element.Attributes.Append( result ); } protected void AppendXmlAttribute( XmlElement element, string name, double value ) { XmlAttribute result = element.OwnerDocument.CreateAttribute( name ); result.Value = value.ToString( CultureInfo.InvariantCulture ); element.Attributes.Append( result ); } protected string ReadXmlAttributeAsString( XmlElement element, string name ) { XmlAttribute attribute = element.Attributes[name]; return attribute != null ? attribute.Value : null; } protected int ReadXmlAttributeAsInteger( XmlElement element, string name ) { XmlAttribute attribute = element.Attributes[name]; return attribute != null ? int.Parse( attribute.Value, CultureInfo.InvariantCulture ) : 0; } protected long ReadXmlAttributeAsLong( XmlElement element, string name ) { XmlAttribute attribute = element.Attributes[name]; return attribute != null ? long.Parse( attribute.Value, CultureInfo.InvariantCulture ) : 0L; } protected float ReadXmlAttributeAsFloat( XmlElement element, string name ) { XmlAttribute attribute = element.Attributes[name]; return attribute != null ? float.Parse( attribute.Value, CultureInfo.InvariantCulture ) : 0f; } protected double ReadXmlAttributeAsDouble( XmlElement element, string name ) { XmlAttribute attribute = element.Attributes[name]; return attribute != null ? double.Parse( attribute.Value, CultureInfo.InvariantCulture ) : 0.0; } } public class IPNull : IPObject { public override object GetClipboardObject( Object context ) { return null; } public IPNull( SerializedClipboard root ) : base( root ) { } public IPNull( SerializedClipboard root, string name ) : base( root, name ) { } } public class IPType : IPObject { public string AssemblyQualifiedName; private bool typeRecreated; private Type m_type; public Type Type { get { return (Type) GetClipboardObject( null ); } } // Useful shorthand property public IPType( SerializedClipboard root ) : base( root ) { } public IPType( SerializedClipboard root, Type type ) : base( root, type.Name ) { AssemblyQualifiedName = type.AssemblyQualifiedName; } public override object GetClipboardObject( Object context ) { // We want to call Type.GetType only once but it can return null. Thus, we aren't using "if( type == null )" if( !typeRecreated ) { typeRecreated = true; m_type = Type.GetType( AssemblyQualifiedName ); } return m_type; } public override void WriteToXmlElement( XmlElement element ) { base.WriteToXmlElement( element ); AppendXmlAttribute( element, "FullName", AssemblyQualifiedName ); } public override void ReadFromXmlElement( XmlElement element ) { base.ReadFromXmlElement( element ); AssemblyQualifiedName = ReadXmlAttributeAsString( element, "FullName" ); } } public abstract class IPObjectWithChild : IPObject { public IPObject[] Children; protected IPObjectWithChild( SerializedClipboard root ) : base( root ) { } protected IPObjectWithChild( SerializedClipboard root, string name ) : base( root, name ) { } public override void WriteToXmlElement( XmlElement element ) { base.WriteToXmlElement( element ); root.CreateObjectArrayInXmlElement( element, Children ); } public override void ReadFromXmlElement( XmlElement element ) { base.ReadFromXmlElement( element ); Children = root.ReadObjectArrayFromXmlElement<IPObject>( element ); } } public abstract class IPObjectWithType : IPObject { public int TypeIndex; protected IPType serializedType; protected IPObjectWithType( SerializedClipboard root ) : base( root ) { } protected IPObjectWithType( SerializedClipboard root, string name, Type type ) : base( root, name ) { TypeIndex = root.GetIndexOfTypeToSerialize( type, true ); } public override object GetClipboardObject( Object context ) { serializedType = root.Types[TypeIndex]; return null; } public override void WriteToXmlElement( XmlElement element ) { base.WriteToXmlElement( element ); AppendXmlAttribute( element, "TypeIndex", TypeIndex ); } public override void ReadFromXmlElement( XmlElement element ) { base.ReadFromXmlElement( element ); TypeIndex = ReadXmlAttributeAsInteger( element, "TypeIndex" ); } } public class IPArray : IPObjectWithChild { public string ElementType; public IPArray( SerializedClipboard root ) : base( root ) { } public IPArray( SerializedClipboard root, string name, ArrayClipboard value, Object source ) : base( root, name ) { ElementType = value.elementType; Children = new IPObject[value.elements.Length]; for( int i = 0; i < value.elements.Length; i++ ) Children[i] = root.GetSerializableDataFromClipboardData( value.elements[i], null, source ); } public override object GetClipboardObject( Object context ) { object[] elements = new object[Children != null ? Children.Length : 0]; for( int i = 0; i < elements.Length; i++ ) elements[i] = Children[i].GetClipboardObject( context ); return new ArrayClipboard( ElementType, elements ); } public override void WriteToXmlElement( XmlElement element ) { base.WriteToXmlElement( element ); AppendXmlAttribute( element, "ElementType", ElementType ); } public override void ReadFromXmlElement( XmlElement element ) { base.ReadFromXmlElement( element ); ElementType = ReadXmlAttributeAsString( element, "ElementType" ); } } public class IPGenericObject : IPObjectWithChild { public string Type; public IPGenericObject( SerializedClipboard root ) : base( root ) { } public IPGenericObject( SerializedClipboard root, string name, GenericObjectClipboard value, Object source ) : base( root, name ) { Type = value.type; Children = new IPObject[value.values.Length]; for( int i = 0; i < value.values.Length; i++ ) Children[i] = root.GetSerializableDataFromClipboardData( value.values[i], null, source ); } public override object GetClipboardObject( Object context ) { object[] values = new object[Children != null ? Children.Length : 0]; for( int i = 0; i < values.Length; i++ ) values[i] = Children[i].GetClipboardObject( context ); return new GenericObjectClipboard( Type, values ); } public override void WriteToXmlElement( XmlElement element ) { base.WriteToXmlElement( element ); AppendXmlAttribute( element, "Type", Type ); } public override void ReadFromXmlElement( XmlElement element ) { base.ReadFromXmlElement( element ); Type = ReadXmlAttributeAsString( element, "Type" ); } } // A [SerializeReference] object public class IPManagedObject : IPObjectWithType { public class NestedReference { public string RelativePath; public int ReferenceIndex; } public string Value; public NestedReference[] NestedManagedObjects; public NestedReference[] NestedSceneObjects; public NestedReference[] NestedAssets; // Each different UnityEngine.Object context will receive a different copy of this managed object. If the same object was used, // altering the managed object's nested assets/scene objects due to RelativePath would affect the previous contexts that this // managed object was assigned to, as well private readonly Dictionary<Object, ManagedObjectClipboard> valuesPerContext = new Dictionary<Object, ManagedObjectClipboard>( 2 ); public IPManagedObject( SerializedClipboard root ) : base( root ) { } public IPManagedObject( SerializedClipboard root, ManagedObjectClipboard clipboard, Object source ) : base( root, null, clipboard.value.GetType() ) { Value = EditorJsonUtility.ToJson( clipboard.value ); if( source ) valuesPerContext[source] = clipboard; ManagedObjectClipboard.NestedManagedObject[] nestedManagedObjects = clipboard.nestedManagedObjects; if( nestedManagedObjects != null && nestedManagedObjects.Length > 0 ) { NestedManagedObjects = new NestedReference[nestedManagedObjects.Length]; int validNestedManagedObjectCount = 0; for( int i = 0; i < nestedManagedObjects.Length; i++ ) { object nestedReference = nestedManagedObjects[i].reference; if( nestedReference == null || nestedReference.Equals( null ) ) continue; int referenceIndex = root.GetIndexOfManagedObjectToSerialize( nestedReference, false ); if( referenceIndex >= 0 ) { NestedManagedObjects[validNestedManagedObjectCount++] = new NestedReference() { ReferenceIndex = referenceIndex, RelativePath = nestedManagedObjects[i].relativePath }; } } if( validNestedManagedObjectCount == 0 ) NestedManagedObjects = null; else if( validNestedManagedObjectCount != NestedManagedObjects.Length ) Array.Resize( ref NestedManagedObjects, validNestedManagedObjectCount ); } ManagedObjectClipboard.NestedUnityObject[] nestedUnityObjects = clipboard.nestedUnityObjects; if( nestedUnityObjects != null && nestedUnityObjects.Length > 0 ) { NestedSceneObjects = new NestedReference[nestedUnityObjects.Length]; NestedAssets = new NestedReference[nestedUnityObjects.Length]; int validNestedSceneObjectCount = 0; int validNestedAssetCount = 0; for( int i = 0; i < nestedUnityObjects.Length; i++ ) { Object nestedReference = nestedUnityObjects[i].reference; if( !nestedReference ) continue; if( AssetDatabase.Contains( nestedReference ) ) { int referenceIndex = root.GetIndexOfAssetToSerialize( nestedReference, true ); if( referenceIndex >= 0 ) { NestedAssets[validNestedAssetCount++] = new NestedReference() { ReferenceIndex = referenceIndex, RelativePath = nestedUnityObjects[i].relativePath }; } } else { int referenceIndex = root.GetIndexOfSceneObjectToSerialize( nestedReference, true ); if( referenceIndex >= 0 ) { NestedSceneObjects[validNestedSceneObjectCount++] = new NestedReference() { ReferenceIndex = referenceIndex, RelativePath = nestedUnityObjects[i].relativePath }; } } } if( validNestedSceneObjectCount == 0 ) NestedSceneObjects = null; else if( validNestedSceneObjectCount != NestedSceneObjects.Length ) Array.Resize( ref NestedSceneObjects, validNestedSceneObjectCount ); if( validNestedAssetCount == 0 ) NestedAssets = null; else if( validNestedAssetCount != NestedAssets.Length ) Array.Resize( ref NestedAssets, validNestedAssetCount ); } } public override object GetClipboardObject( Object context ) { // Initialize serializedType base.GetClipboardObject( context ); if( !context ) { Debug.LogError( "Empty context encountered while deserializing managed object, please report it to Inspect+'s author." ); return null; } ManagedObjectClipboard cachedResult; if( valuesPerContext.TryGetValue( context, out cachedResult ) ) return cachedResult; if( serializedType.Type != null ) { object value; if( serializedType.Type.GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null ) != null ) value = Activator.CreateInstance( serializedType.Type, true ); else value = FormatterServices.GetUninitializedObject( serializedType.Type ); EditorJsonUtility.FromJsonOverwrite( Value, value ); // No need to fill the nestedManagedObjects and nestedUnityObjects arrays, they aren't used by SerializablePropertyExtensions cachedResult = new ManagedObjectClipboard( serializedType.Name, value, null, null ); // Avoiding StackOverflowException if cyclic nested references exist valuesPerContext[context] = cachedResult; // We've assigned cachedResult its value before filling in the nested managed objects because a nested managed object can also reference // this managed object (cyclic reference) and in which case, we want our cachedResult value to be ready ApplyNestedReferencesToValue( value, NestedManagedObjects, root.ManagedObjects, context ); ApplyNestedReferencesToValue( value, NestedSceneObjects, root.SceneObjects, context ); ApplyNestedReferencesToValue( value, NestedAssets, root.Assets, context ); } valuesPerContext[context] = cachedResult; return cachedResult; } public override void WriteToXmlElement( XmlElement element ) { base.WriteToXmlElement( element ); AppendXmlAttribute( element, "Value", Value ); WriteNestedReferencesToChildXmlElement( element, NestedManagedObjects, "NestedManagedObjects" ); WriteNestedReferencesToChildXmlElement( element, NestedSceneObjects, "NestedSceneObjects" ); WriteNestedReferencesToChildXmlElement( element, NestedAssets, "NestedAssets" ); } public override void ReadFromXmlElement( XmlElement element ) { base.ReadFromXmlElement( element ); Value = ReadXmlAttributeAsString( element, "Value" ); XmlNodeList childNodes = element.ChildNodes; if( childNodes != null ) { for( int i = 0; i < childNodes.Count; i++ ) { XmlElement childNode = (XmlElement) childNodes[i]; if( childNode.Name == "NestedManagedObjects" ) NestedManagedObjects = ReadNestedReferencesFromXmlElement( childNode ); else if( childNode.Name == "NestedSceneObjects" ) NestedSceneObjects = ReadNestedReferencesFromXmlElement( childNode ); else if( childNode.Name == "NestedAssets" ) NestedAssets = ReadNestedReferencesFromXmlElement( childNode ); } } } private void WriteNestedReferencesToChildXmlElement( XmlElement element, NestedReference[] references, string childElementName ) { if( references != null && references.Length > 0 ) { XmlElement arrayRoot = element.OwnerDocument.CreateElement( childElementName ); element.AppendChild( arrayRoot ); for( int i = 0; i < references.Length; i++ ) { XmlElement childElement = arrayRoot.OwnerDocument.CreateElement( "Reference" ); AppendXmlAttribute( childElement, "RelativePath", references[i].RelativePath ); AppendXmlAttribute( childElement, "ManagedRefIndex", references[i].ReferenceIndex ); arrayRoot.AppendChild( childElement ); } } } private NestedReference[] ReadNestedReferencesFromXmlElement( XmlElement element ) { XmlNodeList childNodes = element.ChildNodes; if( childNodes == null || childNodes.Count == 0 ) return null; NestedReference[] result = new NestedReference[childNodes.Count]; for( int i = 0; i < childNodes.Count; i++ ) { XmlElement childNode = (XmlElement) childNodes[i]; result[i] = new NestedReference() { RelativePath = ReadXmlAttributeAsString( childNode, "RelativePath" ), ReferenceIndex = ReadXmlAttributeAsInteger( childNode, "ManagedRefIndex" ) }; } return result; } private void ApplyNestedReferencesToValue( object value, NestedReference[] nestedReferences, IPObject[] referenceContainer, Object context ) { if( nestedReferences != null ) { for( int i = 0; i < nestedReferences.Length; i++ ) { object nestedReference = referenceContainer[nestedReferences[i].ReferenceIndex].GetClipboardObject( context ); if( nestedReference is ManagedObjectClipboard ) nestedReference = ( (ManagedObjectClipboard) nestedReference ).value; if( nestedReference != null && !nestedReference.Equals( null ) ) SerializablePropertyExtensions.TraversePathAndSetFieldValue( value, nestedReferences[i].RelativePath, nestedReference ); } } } } public class IPManagedReference : IPObject { public int ManagedRefIndex; public IPManagedReference( SerializedClipboard root ) : base( root ) { } public IPManagedReference( SerializedClipboard root, string name, ManagedObjectClipboard value ) : base( root, name ) { ManagedRefIndex = root.GetIndexOfManagedObjectToSerialize( value, true ); } public override object GetClipboardObject( Object context ) { return root.ManagedObjects[ManagedRefIndex].GetClipboardObject( context ); } public override void WriteToXmlElement( XmlElement element ) { base.WriteToXmlElement( element ); AppendXmlAttribute( element, "ManagedRefIndex", ManagedRefIndex ); } public override void ReadFromXmlElement( XmlElement element ) { base.ReadFromXmlElement( element ); ManagedRefIndex = ReadXmlAttributeAsInteger( element, "ManagedRefIndex" ); } } public abstract class IPUnityObject : IPObjectWithType { public string ObjectName; public string Path; public string RelativePath; protected IPUnityObject( SerializedClipboard root ) : base( root ) { } protected IPUnityObject( SerializedClipboard root, string name, Type type ) : base( root, name, type ) { } public override object GetClipboardObject( Object context ) { base.GetClipboardObject( context ); // Try finding the object with RelativePath first return ResolveRelativePath( context, RelativePath, serializedType ); } public override void WriteToXmlElement( XmlElement element ) { base.WriteToXmlElement( element ); AppendXmlAttribute( element, "ObjectName", ObjectName ); AppendXmlAttribute( element, "Path", Path ); AppendXmlAttribute( element, "RelativePath", RelativePath ); } public override void ReadFromXmlElement( XmlElement element ) { base.ReadFromXmlElement( element ); ObjectName = ReadXmlAttributeAsString( element, "ObjectName" ); Path = ReadXmlAttributeAsString( element, "Path" ); RelativePath = ReadXmlAttributeAsString( element, "RelativePath" ); } protected string CalculateRelativePath( Object source, Object context, string targetPath = null ) { if( !InspectPlusSettings.Instance.UseRelativePathsInXML ) return null; if( !source || !context || ( !( source is Component ) && !( source is GameObject ) ) || ( !( context is Component ) && !( context is GameObject ) ) ) return null; Transform sourceTransform = source is Component ? ( (Component) source ).transform : ( (GameObject) source ).transform; Transform targetTransform = context is Component ? ( (Component) context ).transform : ( (GameObject) context ).transform; if( sourceTransform == targetTransform ) return "./"; if( sourceTransform.root != targetTransform.root ) return null; if( targetTransform.IsChildOf( sourceTransform ) ) { string _result = targetTransform.name; while( targetTransform.parent != sourceTransform ) { targetTransform = targetTransform.parent; _result = string.Concat( targetTransform.name, "/", _result ); } return _result; } if( sourceTransform.IsChildOf( targetTransform ) ) { string _result = "../"; while( sourceTransform.parent != targetTransform ) { sourceTransform = sourceTransform.parent; _result += "../"; } return _result; } // Credit: https://stackoverflow.com/a/9042938/2373034 string sourcePath = CalculatePath( sourceTransform ); if( string.IsNullOrEmpty( targetPath ) ) targetPath = CalculatePath( targetTransform ); int commonPrefixEndIndex = 0; for( int i = 0; i < targetPath.Length && i < sourcePath.Length && targetPath[i] == sourcePath[i]; i++ ) { if( targetPath[i] == '/' ) commonPrefixEndIndex = i; } string result = "../"; for( int i = commonPrefixEndIndex + 1; i < sourcePath.Length; i++ ) { if( sourcePath[i] == '/' ) result += "../"; } return result + targetPath.Substring( commonPrefixEndIndex + 1 ); } protected Object ResolveRelativePath( Object source, string relativePath, IPType targetType ) { if( !InspectPlusSettings.Instance.UseRelativePathsInXML ) return null; if( string.IsNullOrEmpty( relativePath ) || !source || ( !( source is Component ) && !( source is GameObject ) ) ) return null; Transform result = source is Component ? ( (Component) source ).transform : ( (GameObject) source ).transform; if( relativePath != "./" ) // "./" means RelativePath points to the target object itself { int index = 0; while( index < relativePath.Length && relativePath.StartsWith( "../" ) ) { result = result.parent; if( !result ) return null; index += 3; } while( index < relativePath.Length ) { int separatorIndex = relativePath.IndexOf( '/', index ); if( separatorIndex < 0 ) separatorIndex = relativePath.Length; result = result.Find( relativePath.Substring( index, separatorIndex - index ) ); if( !result ) return null; index = separatorIndex + 1; } } return GetObjectOfTypeFromTransform( result, targetType ); } protected Object GetObjectOfTypeFromTransform( Transform source, IPType type ) { if( type.Name == "GameObject" ) return source.gameObject; else { Component[] components = source.GetComponents<Component>(); for( int i = 0; i < components.Length; i++ ) { if( components[i].GetType().Name == type.Name ) { if( type.Type == null || type.Type == components[i].GetType() ) return components[i]; } } } return null; } protected string CalculatePath( Transform transform ) { string result = transform.name; #if UNITY_2018_3_OR_NEWER UnityEditor.Experimental.SceneManagement.PrefabStage openPrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage(); if( openPrefabStage != null && openPrefabStage.IsPartOfPrefabContents( transform.gameObject ) ) { Transform prefabStageRoot = openPrefabStage.prefabContentsRoot.transform; while( transform.parent && transform != prefabStageRoot ) { transform = transform.parent; result = string.Concat( transform.name, "/", result ); } } else #endif { while( transform.parent ) { transform = transform.parent; result = string.Concat( transform.name, "/", result ); } } return result; } } public class IPSceneObject : IPUnityObject { public string SceneName; private bool objectRecreated; private Object m_object; public IPSceneObject( SerializedClipboard root ) : base( root ) { } public IPSceneObject( SerializedClipboard root, Object value, Object source ) : base( root, null, value.GetType() ) { ObjectName = value.name; if( value is Component || value is GameObject ) { Transform transform = value is Component ? ( (Component) value ).transform : ( (GameObject) value ).transform; #if UNITY_2018_3_OR_NEWER UnityEditor.Experimental.SceneManagement.PrefabStage openPrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage(); if( openPrefabStage == null || !openPrefabStage.IsPartOfPrefabContents( transform.gameObject ) ) #endif SceneName = transform.gameObject.scene.name; Path = CalculatePath( transform ); RelativePath = CalculateRelativePath( source, value, Path ); } } public override object GetClipboardObject( Object context ) { // First, try to resolve the RelativePath. We can't cache it as it depends on the target object baseResult = base.GetClipboardObject( context ); if( baseResult != null && !baseResult.Equals( null ) ) return baseResult; if( objectRecreated ) return m_object; objectRecreated = true; if( !string.IsNullOrEmpty( Path ) ) { // Search all open scenes to find the object reference // Don't use GameObject.Find because it can't find inactive objects string[] pathComponents = Path.Split( '/' ); #if UNITY_2018_3_OR_NEWER // Search the currently open prefab stage (if any) UnityEditor.Experimental.SceneManagement.PrefabStage openPrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage(); if( openPrefabStage != null ) { Object result = FindObjectInScene( new GameObject[1] { openPrefabStage.prefabContentsRoot }, pathComponents ); if( result ) { m_object = result; return result; } } #endif int originalSceneIndex = -1; Scene[] scenes = new Scene[SceneManager.sceneCount]; for( int i = 0; i < scenes.Length; i++ ) { scenes[i] = SceneManager.GetSceneAt( i ); if( scenes[i].name == SceneName ) originalSceneIndex = i; } // Try finding the object in the scene with matching name first if( originalSceneIndex >= 0 ) { Object result = FindObjectInScene( scenes[originalSceneIndex].GetRootGameObjects(), pathComponents ); if( result ) { m_object = result; return result; } } // If object isn't found, search other scenes for( int i = 0; i < scenes.Length; i++ ) { if( i != originalSceneIndex ) { Object result = FindObjectInScene( scenes[i].GetRootGameObjects(), pathComponents ); if( result ) { m_object = result; return result; } } } } else { // Search all objects of specified type if( serializedType.Type != null ) { Object[] objects = Object.FindObjectsOfType( serializedType.Type ); for( int i = 0; i < objects.Length; i++ ) { if( objects[i].name == ObjectName ) { m_object = objects[i]; return objects[i]; } } } } return null; } public override void WriteToXmlElement( XmlElement element ) { base.WriteToXmlElement( element ); AppendXmlAttribute( element, "SceneName", SceneName ); } public override void ReadFromXmlElement( XmlElement element ) { base.ReadFromXmlElement( element ); SceneName = ReadXmlAttributeAsString( element, "SceneName" ); } private Object FindObjectInScene( GameObject[] sceneRoot, string[] pathComponents ) { for( int i = 0; i < sceneRoot.Length; i++ ) { Object result = TraverseHierarchyRecursively( sceneRoot[i].transform, pathComponents, 0 ); if( result ) return result; } return null; } private Object TraverseHierarchyRecursively( Transform obj, string[] path, int pathIndex ) { if( obj.name != path[pathIndex] ) return null; if( pathIndex == path.Length - 1 ) return GetObjectOfTypeFromTransform( obj, serializedType ); for( int i = obj.childCount - 1; i >= 0; i-- ) { Object result = TraverseHierarchyRecursively( obj.GetChild( i ), path, pathIndex + 1 ); if( result ) return result; } return null; } } public class IPAsset : IPUnityObject { [Serializable] private class AssetWrapper { public Object value; } public string Value; private bool assetRecreated; private Object m_asset; public IPAsset( SerializedClipboard root ) : base( root ) { } public IPAsset( SerializedClipboard root, Object value, Object source ) : base( root, null, value.GetType() ) { ObjectName = value.name; Path = AssetDatabase.GetAssetPath( value ); RelativePath = CalculateRelativePath( source, value ); Value = EditorJsonUtility.ToJson( new AssetWrapper() { value = value } ); } public override object GetClipboardObject( Object context ) { // First, try to resolve the RelativePath. We can't cache it as it depends on the target object baseResult = base.GetClipboardObject( context ); if( baseResult != null && !baseResult.Equals( null ) ) return baseResult; if( assetRecreated ) return m_asset; assetRecreated = true; AssetWrapper wrapper = new AssetWrapper(); EditorJsonUtility.FromJsonOverwrite( Value, wrapper ); if( wrapper.value ) { m_asset = wrapper.value; return wrapper.value; } if( !string.IsNullOrEmpty( Path ) ) { Object result = FindAssetAtPath( Path ); if( result ) { m_asset = result; return result; } } string[] guids = AssetDatabase.FindAssets( ObjectName + " t:" + serializedType.Name ); if( guids != null ) { for( int i = 0; i < guids.Length; i++ ) { Object result = FindAssetAtPath( AssetDatabase.GUIDToAssetPath( guids[i] ) ); if( result ) { m_asset = result; return result; } } } return null; } public override void WriteToXmlElement( XmlElement element ) { base.WriteToXmlElement( element ); AppendXmlAttribute( element, "Value", Value ); } public override void ReadFromXmlElement( XmlElement element ) { base.ReadFromXmlElement( element ); Value = ReadXmlAttributeAsString( element, "Value" ); } private Object FindAssetAtPath( string path ) { if( !string.IsNullOrEmpty( path ) ) { Object[] assets = AssetDatabase.LoadAllAssetsAtPath( path ); if( assets != null ) { for( int i = 0; i < assets.Length; i++ ) { Object asset = assets[i]; if( asset.name == ObjectName && asset.GetType().Name == serializedType.Name ) { if( serializedType.Type == null || serializedType.Type == asset.GetType() ) return asset; } } } } return null; } } public class IPSceneObjectReference : IPObject { public int SceneObjectIndex; public IPSceneObjectReference( SerializedClipboard root ) : base( root ) { } public IPSceneObjectReference( SerializedClipboard root, string name, Object value ) : base( root, name ) { SceneObjectIndex = root.GetIndexOfSceneObjectToSerialize( value, true ); } public override object GetClipboardObject( Object context ) { return root.SceneObjects[SceneObjectIndex].GetClipboardObject( context ); } public override void WriteToXmlElement( XmlElement element ) { base.WriteToXmlElement( element ); AppendXmlAttribute( element, "SceneObjectIndex", SceneObjectIndex ); } public override void ReadFromXmlElement( XmlElement element ) { base.ReadFromXmlElement( element ); SceneObjectIndex = ReadXmlAttributeAsInteger( element, "SceneObjectIndex" ); } } public class IPAssetReference : IPObject { public int AssetIndex; public IPAssetReference( SerializedClipboard root ) : base( root ) { } public IPAssetReference( SerializedClipboard root, string name, Object value ) : base( root, name ) { AssetIndex = root.GetIndexOfAssetToSerialize( value, true ); } public override object GetClipboardObject( Object context ) { return root.Assets[AssetIndex].GetClipboardObject( context ); } public override void WriteToXmlElement( XmlElement element ) { base.WriteToXmlElement( element ); AppendXmlAttribute( element, "AssetIndex", AssetIndex ); } public override void ReadFromXmlElement( XmlElement element ) { base.ReadFromXmlElement( element ); AssetIndex = ReadXmlAttributeAsInteger( element, "AssetIndex" ); } } public class IPVector : IPObject { public float C1; public float C2; public float C3; public float C4; public float C5; public float C6; public IPVector( SerializedClipboard root ) : base( root ) { } public IPVector( SerializedClipboard root, string name, VectorClipboard value ) : base( root, name ) { C1 = value.c1; C2 = value.c2; C3 = value.c3; C4 = value.c4; C5 = value.c5; C6 = value.c6; } public override object GetClipboardObject( Object context ) { return new VectorClipboard( C1, C2, C3, C4, C5, C6 ); } public override void WriteToXmlElement( XmlElement element ) { base.WriteToXmlElement( element ); AppendXmlAttribute( element, "C1", C1 ); AppendXmlAttribute( element, "C2", C2 ); AppendXmlAttribute( element, "C3", C3 ); if( C6 != 0f ) { AppendXmlAttribute( element, "C4", C4 ); AppendXmlAttribute( element, "C5", C5 ); AppendXmlAttribute( element, "C6", C6 ); } else if( C5 != 0f ) { AppendXmlAttribute( element, "C4", C4 ); AppendXmlAttribute( element, "C5", C5 ); } else if( C4 != 0f ) AppendXmlAttribute( element, "C4", C4 ); } public override void ReadFromXmlElement( XmlElement element ) { base.ReadFromXmlElement( element ); C1 = ReadXmlAttributeAsFloat( element, "C1" ); C2 = ReadXmlAttributeAsFloat( element, "C2" ); C3 = ReadXmlAttributeAsFloat( element, "C3" ); C4 = ReadXmlAttributeAsFloat( element, "C4" ); C5 = ReadXmlAttributeAsFloat( element, "C5" ); C6 = ReadXmlAttributeAsFloat( element, "C6" ); } } public class IPLong : IPObject { public long Value; public IPLong( SerializedClipboard root ) : base( root ) { } public IPLong( SerializedClipboard root, string name, long value ) : base( root, name ) { Value = value; } public override object GetClipboardObject( Object context ) { return Value; } public override void WriteToXmlElement( XmlElement element ) { base.WriteToXmlElement( element ); AppendXmlAttribute( element, "Value", Value ); } public override void ReadFromXmlElement( XmlElement element ) { base.ReadFromXmlElement( element ); Value = ReadXmlAttributeAsLong( element, "Value" ); } } public class IPDouble : IPObject { public double Value; public IPDouble( SerializedClipboard root ) : base( root ) { } public IPDouble( SerializedClipboard root, string name, double value ) : base( root, name ) { Value = value; } public override object GetClipboardObject( Object context ) { return Value; } public override void WriteToXmlElement( XmlElement element ) { base.WriteToXmlElement( element ); AppendXmlAttribute( element, "Value", Value ); } public override void ReadFromXmlElement( XmlElement element ) { base.ReadFromXmlElement( element ); Value = ReadXmlAttributeAsDouble( element, "Value" ); } } public class IPString : IPObject { public string Value; public IPString( SerializedClipboard root ) : base( root ) { } public IPString( SerializedClipboard root, string name, string value ) : base( root, name ) { Value = value; } public override object GetClipboardObject( Object context ) { return Value; } public override void WriteToXmlElement( XmlElement element ) { base.WriteToXmlElement( element ); AppendXmlAttribute( element, "Value", Value ); } public override void ReadFromXmlElement( XmlElement element ) { base.ReadFromXmlElement( element ); Value = ReadXmlAttributeAsString( element, "Value" ); } } public class IPAnimationCurve : IPObject { [Serializable] private class AnimationCurveWrapper { public AnimationCurve value; } public string Value; public IPAnimationCurve( SerializedClipboard root ) : base( root ) { } public IPAnimationCurve( SerializedClipboard root, string name, AnimationCurve value ) : base( root, name ) { Value = EditorJsonUtility.ToJson( new AnimationCurveWrapper() { value = value } ); } public override object GetClipboardObject( Object context ) { AnimationCurveWrapper wrapper = new AnimationCurveWrapper(); EditorJsonUtility.FromJsonOverwrite( Value, wrapper ); return wrapper.value; } public override void WriteToXmlElement( XmlElement element ) { base.WriteToXmlElement( element ); AppendXmlAttribute( element, "Value", Value ); } public override void ReadFromXmlElement( XmlElement element ) { base.ReadFromXmlElement( element ); Value = ReadXmlAttributeAsString( element, "Value" ); } } public class IPGradient : IPObject { [Serializable] private class GradientWrapper { public Gradient value; } public string Value; public IPGradient( SerializedClipboard root ) : base( root ) { } public IPGradient( SerializedClipboard root, string name, Gradient value ) : base( root, name ) { Value = EditorJsonUtility.ToJson( new GradientWrapper() { value = value } ); } public override object GetClipboardObject( Object context ) { GradientWrapper wrapper = new GradientWrapper(); EditorJsonUtility.FromJsonOverwrite( Value, wrapper ); return wrapper.value; } public override void WriteToXmlElement( XmlElement element ) { base.WriteToXmlElement( element ); AppendXmlAttribute( element, "Value", Value ); } public override void ReadFromXmlElement( XmlElement element ) { base.ReadFromXmlElement( element ); Value = ReadXmlAttributeAsString( element, "Value" ); } } #endregion public IPType[] Types; public IPSceneObject[] SceneObjects; public IPAsset[] Assets; public IPManagedObject[] ManagedObjects; public IPObject[] Values; private List<Type> typesToSerialize; private List<Object> sceneObjectsToSerialize; private List<Object> assetsToSerialize; private List<ManagedObjectClipboard> managedObjectsToSerialize; #region Serialization Functions public string SerializeProperty( SerializedProperty property, bool prettyPrint ) { return SerializeClipboardData( property.CopyValue(), prettyPrint, property.serializedObject.targetObject ); } public string SerializeClipboardData( object clipboardData, bool prettyPrint, Object source ) { // For Component, ScriptableObject and materials, serialize the fields as well (for name-based paste operations) if( clipboardData is Component || clipboardData is ScriptableObject || clipboardData is Material ) return SerializeUnityObject( (Object) clipboardData, prettyPrint, source ); Values = new IPObject[1] { GetSerializableDataFromClipboardData( clipboardData, null, source ) }; return SerializeToXml( prettyPrint, source ); } private string SerializeUnityObject( Object value, bool prettyPrint, Object source ) { SerializedObject serializedObject = new SerializedObject( value ); int valueCount = 0; foreach( SerializedProperty property in serializedObject.EnumerateDirectChildren() ) { if( property.name != "m_Script" ) valueCount++; } IPObject[] serializedValues = new IPObject[valueCount + 1]; serializedValues[0] = GetSerializableDataFromClipboardData( value, null, source ); if( valueCount > 0 ) { int valueIndex = 1; foreach( SerializedProperty property in serializedObject.EnumerateDirectChildren() ) { if( property.name != "m_Script" ) serializedValues[valueIndex++] = GetSerializableDataFromClipboardData( property.CopyValue(), property.name, value ); } } Values = serializedValues; return SerializeToXml( prettyPrint, source ); } private string SerializeToXml( bool prettyPrint, Object source ) { // Managed objects must be serialized first since these objects may fill the scene objects list and assets list as they are serialized if( managedObjectsToSerialize != null && managedObjectsToSerialize.Count > 0 ) { ManagedObjects = new IPManagedObject[managedObjectsToSerialize.Count]; for( int i = 0; i < managedObjectsToSerialize.Count; i++ ) ManagedObjects[i] = new IPManagedObject( this, managedObjectsToSerialize[i], source ); managedObjectsToSerialize = null; } if( sceneObjectsToSerialize != null && sceneObjectsToSerialize.Count > 0 ) { SceneObjects = new IPSceneObject[sceneObjectsToSerialize.Count]; for( int i = 0; i < sceneObjectsToSerialize.Count; i++ ) SceneObjects[i] = new IPSceneObject( this, sceneObjectsToSerialize[i], source ); sceneObjectsToSerialize = null; } if( assetsToSerialize != null && assetsToSerialize.Count > 0 ) { Assets = new IPAsset[assetsToSerialize.Count]; for( int i = 0; i < assetsToSerialize.Count; i++ ) Assets[i] = new IPAsset( this, assetsToSerialize[i], source ); assetsToSerialize = null; } // Types must be serialized last since other lists may fill the Types list as they are serialized if( typesToSerialize != null && typesToSerialize.Count > 0 ) { Types = new IPType[typesToSerialize.Count]; for( int i = 0; i < typesToSerialize.Count; i++ ) Types[i] = new IPType( this, typesToSerialize[i] ); typesToSerialize = null; } XmlDocument xmlDocument = new XmlDocument(); XmlElement rootElement = xmlDocument.CreateElement( "InspectPlus" ); xmlDocument.AppendChild( rootElement ); CreateObjectArrayInChildXmlElement( rootElement, Types, "Types" ); CreateObjectArrayInChildXmlElement( rootElement, SceneObjects, "SceneObjects" ); CreateObjectArrayInChildXmlElement( rootElement, Assets, "Assets" ); CreateObjectArrayInChildXmlElement( rootElement, ManagedObjects, "ManagedObjects" ); CreateObjectArrayInChildXmlElement( rootElement, Values, "Values" ); XmlWriterSettings settings = new XmlWriterSettings { Indent = prettyPrint, OmitXmlDeclaration = true }; using( StringWriter textWriter = new StringWriter() ) using( XmlWriter xmlWriter = XmlWriter.Create( textWriter, settings ) ) { xmlDocument.Save( xmlWriter ); return textWriter.ToString(); } } public void Deserialize( string xmlContents ) { Types = null; ManagedObjects = null; Values = null; XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml( xmlContents ); XmlNodeList childNodes = xmlDocument.DocumentElement.ChildNodes; for( int i = 0; i < childNodes.Count; i++ ) { XmlElement childNode = (XmlElement) childNodes[i]; if( childNode.Name == "Types" ) Types = ReadObjectArrayFromXmlElement<IPType>( childNode ); else if( childNode.Name == "SceneObjects" ) SceneObjects = ReadObjectArrayFromXmlElement<IPSceneObject>( childNode ); else if( childNode.Name == "Assets" ) Assets = ReadObjectArrayFromXmlElement<IPAsset>( childNode ); else if( childNode.Name == "ManagedObjects" ) ManagedObjects = ReadObjectArrayFromXmlElement<IPManagedObject>( childNode ); else if( childNode.Name == "Values" ) Values = ReadObjectArrayFromXmlElement<IPObject>( childNode ); } } private IPObject GetSerializableDataFromClipboardData( object obj, string name, Object source ) { if( obj == null || obj.Equals( null ) ) return new IPNull( this, name ); if( obj is Object ) { Object value = (Object) obj; if( !value ) return new IPNull( this, name ); else if( AssetDatabase.Contains( value ) ) return new IPAssetReference( this, name, value ); else return new IPSceneObjectReference( this, name, value ); } if( obj is ArrayClipboard ) return new IPArray( this, name, (ArrayClipboard) obj, source ); if( obj is GenericObjectClipboard ) return new IPGenericObject( this, name, (GenericObjectClipboard) obj, source ); if( obj is VectorClipboard ) return new IPVector( this, name, (VectorClipboard) obj ); if( obj is ManagedObjectClipboard ) { object value = ( (ManagedObjectClipboard) obj ).value; if( value == null || value.Equals( null ) ) return new IPNull( this, name ); else return new IPManagedReference( this, name, (ManagedObjectClipboard) obj ); } if( obj is long ) return new IPLong( this, name, (long) obj ); if( obj is double ) return new IPDouble( this, name, (double) obj ); if( obj is string ) return new IPString( this, name, (string) obj ); if( obj is AnimationCurve ) return new IPAnimationCurve( this, name, (AnimationCurve) obj ); if( obj is Gradient ) return new IPGradient( this, name, (Gradient) obj ); return new IPNull( this, name ); } private XmlElement ConvertObjectToXmlElement( IPObject entry, XmlElement parent ) { string elementName; if( entry is IPNull ) elementName = "Null"; else if( entry is IPAsset ) elementName = "Asset"; else if( entry is IPSceneObject ) elementName = "SceneObject"; else if( entry is IPAssetReference ) elementName = "AssetRef"; else if( entry is IPSceneObjectReference ) elementName = "SceneObjectRef"; else if( entry is IPArray ) elementName = "Array"; else if( entry is IPGenericObject ) elementName = "Generic"; else if( entry is IPVector ) elementName = "Vector"; else if( entry is IPManagedReference ) elementName = "ManagedRef"; else if( entry is IPLong ) elementName = "Long"; else if( entry is IPDouble ) elementName = "Double"; else if( entry is IPString ) elementName = "String"; else if( entry is IPAnimationCurve ) elementName = "Curve"; else if( entry is IPGradient ) elementName = "Gradient"; else if( entry is IPType ) elementName = "Type"; else if( entry is IPManagedObject ) elementName = "ManagedObject"; else elementName = "Unknown"; XmlElement result = parent.OwnerDocument.CreateElement( elementName ); entry.WriteToXmlElement( result ); return result; } private IPObject ConvertXmlElementToObject( XmlElement element ) { IPObject result; string elementName = element.Name; if( elementName == "Null" ) result = new IPNull( this ); else if( elementName == "Asset" ) result = new IPAsset( this ); else if( elementName == "SceneObject" ) result = new IPSceneObject( this ); else if( elementName == "AssetRef" ) result = new IPAssetReference( this ); else if( elementName == "SceneObjectRef" ) result = new IPSceneObjectReference( this ); else if( elementName == "Array" ) result = new IPArray( this ); else if( elementName == "Generic" ) result = new IPGenericObject( this ); else if( elementName == "Vector" ) result = new IPVector( this ); else if( elementName == "ManagedRef" ) result = new IPManagedReference( this ); else if( elementName == "Long" ) result = new IPLong( this ); else if( elementName == "Double" ) result = new IPDouble( this ); else if( elementName == "String" ) result = new IPString( this ); else if( elementName == "Curve" ) result = new IPAnimationCurve( this ); else if( elementName == "Gradient" ) result = new IPGradient( this ); else if( elementName == "Type" ) result = new IPType( this ); else if( elementName == "ManagedObject" ) result = new IPManagedObject( this ); else result = new IPNull( this ); result.ReadFromXmlElement( element ); return result; } #endregion #region Helper Functions private int GetIndexOfTypeToSerialize( Type type, bool addEntryIfNotExists ) { return GetIndexOfObjectInList( type, ref typesToSerialize, addEntryIfNotExists ); } private int GetIndexOfSceneObjectToSerialize( Object sceneObject, bool addEntryIfNotExists ) { return GetIndexOfObjectInList( sceneObject, ref sceneObjectsToSerialize, addEntryIfNotExists ); } private int GetIndexOfAssetToSerialize( Object asset, bool addEntryIfNotExists ) { return GetIndexOfObjectInList( asset, ref assetsToSerialize, addEntryIfNotExists ); } private int GetIndexOfManagedObjectToSerialize( ManagedObjectClipboard obj, bool addEntryIfNotExists ) { if( managedObjectsToSerialize == null ) managedObjectsToSerialize = new List<ManagedObjectClipboard>( 4 ); for( int i = managedObjectsToSerialize.Count - 1; i >= 0; i-- ) { if( managedObjectsToSerialize[i].value == obj.value ) return i; } if( !addEntryIfNotExists ) return -1; managedObjectsToSerialize.Add( obj ); return managedObjectsToSerialize.Count - 1; } private int GetIndexOfManagedObjectToSerialize( object obj, bool addEntryIfNotExists ) { if( managedObjectsToSerialize == null ) managedObjectsToSerialize = new List<ManagedObjectClipboard>( 4 ); for( int i = managedObjectsToSerialize.Count - 1; i >= 0; i-- ) { if( managedObjectsToSerialize[i].value == obj ) return i; } if( !addEntryIfNotExists ) return -1; managedObjectsToSerialize.Add( new ManagedObjectClipboard( obj.GetType().Name, obj, null, null ) ); return managedObjectsToSerialize.Count - 1; } private int GetIndexOfObjectInList<T>( T obj, ref List<T> list, bool addEntryIfNotExists ) where T : class { if( list == null ) list = new List<T>( 4 ); for( int i = list.Count - 1; i >= 0; i-- ) { if( list[i] == obj ) return i; } if( !addEntryIfNotExists ) return -1; list.Add( obj ); return list.Count - 1; } private void CreateObjectArrayInChildXmlElement( XmlElement element, IPObject[] array, string childElementName ) { if( array != null && array.Length > 0 ) { XmlElement arrayRoot = element.OwnerDocument.CreateElement( childElementName ); element.AppendChild( arrayRoot ); CreateObjectArrayInXmlElement( arrayRoot, array ); } } private void CreateObjectArrayInXmlElement( XmlElement element, IPObject[] array ) { if( array != null && array.Length > 0 ) { for( int i = 0; i < array.Length; i++ ) element.AppendChild( ConvertObjectToXmlElement( array[i], element ) ); } } private T[] ReadObjectArrayFromXmlElement<T>( XmlElement element ) where T : IPObject { XmlNodeList childNodes = element.ChildNodes; if( childNodes == null || childNodes.Count == 0 ) return null; T[] result = new T[childNodes.Count]; for( int i = 0; i < childNodes.Count; i++ ) result[i] = (T) ConvertXmlElementToObject( (XmlElement) childNodes[i] ); return result; } #endregion } }
using Webservice.helper; using PersianDate; using System; using System.Collections.Generic; using System.Linq; using System.Web; using Webservice.Models; namespace Webservice.Repo { public class OtherRepo { protected Service_DBEntities DBContext; public OtherRepo() { DBContext = new Service_DBEntities(); } public object getCompany() { try { var data = DBContext.tbl_company.Where(e => e.isConfirmed == true).ToList(); List<companyCls> companyClsLst = new List<companyCls>(); { foreach (var a in data) { companyClsLst.Add(new companyCls { company_id = a.company_id, company_name = a.company_name }); } } if (companyClsLst.Count == 0) { return new ErrorMessage { error = "No data found" }; } else { return companyClsLst; } } catch (Exception ex) { HandleAndLogException.LogErrorToText(ex); return new ErrorMessage { error = "Something went wrong" }; } } public class companyCls { public int company_id { get; set; } public string company_name { get; set; } } public object getGeneraldata() { try { int ID = 1; var generalData = DBContext.tbl_general.SingleOrDefault(e=>e.ID == ID); var commissionFeeData = DBContext.tbl_commissionFee.FirstOrDefault(); if (generalData == null || commissionFeeData == null) { return new ErrorMessage { error = "No data found" }; } else { generalData = new tbl_general { aboutPath = generalData.aboutPath, hostAddress = generalData.hostAddress, ID = generalData.ID, passengerDetect = commissionFeeData.persianPassengerFee, percentDetect = commissionFeeData.driversFee, fastTrackAmount = commissionFeeData.minFastInBalance, perKM = generalData.perKM, privacyPolicyPath = generalData.privacyPolicyPath, termConditionPath = generalData.termConditionPath }; return generalData; } } catch (Exception ex) { HandleAndLogException.LogErrorToText(ex); return new ErrorMessage { error = "Something went wrong" }; } } public object userRating(tbl_userRating data) { try { var a = DBContext.tbl_book.Where(e => e.book_id == data.offerRide_ID).SingleOrDefault(); if (data.user_id != 0 && data.ratingCount != 0 && data.rate_user_id != 0 && data.offerRide_ID != 0) { data.offerRide_ID = a.offerRide_ID; DBContext.tbl_userRating.Add(data); DBContext.SaveChanges(); return new SuccessMessage { success = "Submitted" }; } else { return new ErrorMessage { error = "user not exist." }; } } catch (Exception ex) { HandleAndLogException.LogErrorToText(ex); return new ErrorMessage { error = "Something went wrong" }; } } /* public object userChat(tbl_chat data) { try { var offerData = DBContext.tbl_offerRide.SingleOrDefault(e => e.offerRide_ID == data.offerRide_ID); if (offerData != null) { var chatData = DBContext.tbl_chat.SingleOrDefault(e=>e.offerRide_ID == data.offerRide_ID); } else { return new ErrorMessage { error = "Ride not exist." }; } } catch (Exception ex) { HandleAndLogException.LogErrorToText(ex); return new ErrorMessage { error = "Something went wrong" }; } }*/ public object getUsersRating(int user_id) { try { //this is return list of your rate to users var yourRatingLst = DBContext.tbl_userRating.Where(e => e.user_id == user_id).OrderByDescending(e => e.rateDatetime).ToList(); //this is return list of users rate for you var usersRatingLst = DBContext.tbl_userRating.Where(e => e.rate_user_id == user_id).OrderByDescending(e => e.rateDatetime).ToList(); if (yourRatingLst.Count == 0 && usersRatingLst.Count == 0) { return new ErrorMessage { error = "No data found" }; } else { List<usersRating> RatingList = new List<usersRating>(); foreach (var item in yourRatingLst) { var user = DBContext.tbl_profile.SingleOrDefault(e => e.user_id == item.rate_user_id); RatingList.Add(new usersRating { full_name = user.full_name,//language.Trim().Equals("Persian") ? TranslateCls.Translate(user.full_name, "English", "Persian") : user.full_name, user_id = user.user_id, profile_pic = user.profile_pic, rateDatetime = String.Format("{0:f}", item.rateDatetime), ratingCount = item.ratingCount.ToString(), rateType = "your rate to user" }); } foreach (var item in usersRatingLst) { var user = DBContext.tbl_profile.SingleOrDefault(e => e.user_id == item.user_id); RatingList.Add(new usersRating { full_name = user.full_name, user_id = user.user_id, profile_pic = user.profile_pic, rateDatetime = String.Format("{0:f}", item.rateDatetime), ratingCount = item.ratingCount.ToString(), rateType = "user rate to you" }); } return RatingList; } } catch (Exception ex) { HandleAndLogException.LogErrorToText(ex); return new ErrorMessage { error = "Something went wrong" }; } } public object getUserRating(int user_id, int rate_user_id, int offerRide_ID) { try { var result = DBContext.tbl_userRating.SingleOrDefault(e => e.offerRide_ID == offerRide_ID && e.user_id == user_id && e.rate_user_id == rate_user_id); if (result == null) { return new SuccessMessage { success = "No data found" }; } else { return result; } } catch (Exception ex) { HandleAndLogException.LogErrorToText(ex); return new ErrorMessage { error = "Something went wrong" }; } } public object getPassengerAcceptInfo(int book_id) { try { tbl_book bookData = DBContext.tbl_book.AsEnumerable().Where(e => e.book_id == book_id).SingleOrDefault(); if (bookData == null) { return new ErrorMessage { error = "No data found" }; } else { return new PassengerAcceptInfo { full_name = bookData.tbl_profile.full_name, user_id = bookData.tbl_profile.user_id, profile_pic = bookData.tbl_profile.profile_pic, from = bookData.tbl_offerRide.from_place, to = bookData.tbl_offerRide.to_place, book_id = book_id.ToString(), currentLatLong = bookData.tbl_profile.latLong }; } } catch (Exception ex) { HandleAndLogException.LogErrorToText(ex); return new ErrorMessage { error = "Something went wrong" }; } } public object getDriverAcceptInfo(int book_id) { try { tbl_book bookData = DBContext.tbl_book.AsEnumerable().Where(e => e.book_id == book_id).SingleOrDefault(); if (bookData == null) { return new ErrorMessage { error = "No data found" }; } else { return new DriverAcceptInfo { full_name = bookData.tbl_offerRide.tbl_profile.full_name, user_id = bookData.tbl_offerRide.tbl_profile.user_id, profile_pic = bookData.tbl_offerRide.tbl_profile.profile_pic, from = bookData.tbl_offerRide.from_place, to = bookData.tbl_offerRide.to_place, book_id = book_id.ToString(), currentLatLong = bookData.tbl_offerRide.tbl_profile.latLong, datetime = String.Format("{0:f}", bookData.tbl_offerRide.datetime), perSeatCash = (double.Parse(bookData.tbl_offerRide.price) / bookData.tbl_offerRide.no_seats).ToString(), brand = bookData.tbl_offerRide.tbl_vehicle.brand, carPhoto = bookData.tbl_offerRide.tbl_vehicle.carPhoto, color = bookData.tbl_offerRide.tbl_vehicle.color, model = bookData.tbl_offerRide.tbl_vehicle.model, type = bookData.tbl_offerRide.tbl_vehicle.type, plateNumber = bookData.tbl_offerRide.tbl_vehicle.plateNumber }; } } catch (Exception ex) { HandleAndLogException.LogErrorToText(ex); return new ErrorMessage { error = "Something went wrong" }; } } public object getUsersNotification(int user_id) { try { //this is return list of users notification for you var usersNotificationLst = DBContext.tbl_Notification.Where(e => e.user_id == user_id).OrderByDescending(e => e.notificationDatetime).ToList(); if (usersNotificationLst.Count == 0) { return new ErrorMessage { error = "No data found" }; } else { List<usersNotification> NotificationList = new List<usersNotification>(); notificationCls Notification = new notificationCls(); //int i = 1; foreach (var item in usersNotificationLst) { //var user = DBContext.tbl_profile.SingleOrDefault(e => e.user_id == item.user_id); string[] messageObj = item.message.Split('|'); string book_id = messageObj[1].Split('=')[1]; tbl_book bookData = DBContext.tbl_book.AsEnumerable().Where(e => e.book_id == int.Parse(book_id)).SingleOrDefault(); NotificationList.Add(new usersNotification { seat = "1", full_name = bookData.tbl_profile.full_name, user_id = bookData.tbl_profile.user_id, profile_pic = bookData.tbl_profile.profile_pic, notificationDatetime = Notification.myTime(DateTime.Parse(item.notificationDatetime.ToString())), message = messageObj[0], ID = item.ID, from = bookData.tbl_offerRide.from_place, to = bookData.tbl_offerRide.to_place, rating = "4.9", status = bookData.status, book_id = book_id, currentLatLong = bookData.tbl_profile.latLong }); /* i++; if (i == 11) { break; }*/ } return NotificationList; } } catch (Exception ex) { HandleAndLogException.LogErrorToText(ex); return new ErrorMessage { error = "Something went wrong" }; } } public object sendTestPush(int user_id, string msg) { try { var user = DBContext.tbl_profile.SingleOrDefault(e => e.user_id == user_id && e.deviceToken != ""); if (user != null) { notificationCls Notification = new notificationCls(); /*if (language.Trim().Equals("Persian")) { return Notification.sendTestPush(user.deviceToken, TranslateCls.Translate(msg,"English","Persian")); } else*/ { return Notification.sendTestPush(user.deviceToken, msg); } } else { return new ErrorMessage { error = "No data found" }; } } catch (Exception ex) { HandleAndLogException.LogErrorToText(ex); return new ErrorMessage { error = "Something went wrong" }; } } public object complaint(tbl_complaint data) { try { if (data.user_id != 0 && data.offerRide_ID != 0) { DBContext.tbl_complaint.Add(data); var result = DBContext.tbl_offerRide.SingleOrDefault(e => e.offerRide_ID == data.offerRide_ID); result.complaint = true; DBContext.SaveChanges(); return new SuccessMessage { success = "Submitted" }; } else { return new ErrorMessage { error = "user not exist." }; } } catch (Exception ex) { HandleAndLogException.LogErrorToText(ex); return new ErrorMessage { error = "Something went wrong" }; } } public string getAmount(int user_id) { var passengerData = DBContext.tbl_WalletTransaction.Where(e => e.user_id == user_id).ToList(); if (passengerData.Count != 0) { return passengerData.LastOrDefault().Balance; } else { return "0"; } } public object deleteNotfication(int ID) { try { tbl_Notification notficationData = DBContext.tbl_Notification.SingleOrDefault(e => e.ID == ID && e.isDeleted == null); if (notficationData != null) { notficationData.isDeleted = true; DBContext.SaveChanges(); return new SuccessMessage { success = "Notification successfully deleted" }; } else { return new ErrorMessage { error = "item not exist." }; } } catch (Exception ex) { HandleAndLogException.LogErrorToText(ex); return new ErrorMessage { error = "Something went wrong" }; } } public string getUserOwnRating(int rate_user_id) { var userRatingData = DBContext.tbl_userRating.Where(e => e.rate_user_id == rate_user_id).ToList(); if (userRatingData.Count != 0) { int usersRateCount = userRatingData.Count(); int RateCount = userRatingData.Sum(e => e.ratingCount); return (RateCount / usersRateCount).ToString(); } else { return "0"; } } public class SuccessMessage { public string success { get; set; } } public class ConvertMessage { public string text { get; set; } } public class ErrorMessage { public string error { get; set; } } public class usersRating { public int user_id { get; set; } public string profile_pic { get; set; } public string full_name { get; set; } public string ratingCount { get; set; } public string rateDatetime { get; set; } public string rateType { get; set; } } public class usersNotification { public int ID { get; set; } public int user_id { get; set; } public string profile_pic { get; set; } public string full_name { get; set; } public string notificationDatetime { get; set; } public string message { get; set; } public string from { get; set; } public string to { get; set; } public string seat { get; set; } public string rating { get; set; } public string status { get; set; } public string book_id { get; set; } public string currentLatLong { get; set; } } public class PassengerAcceptInfo { public int user_id { get; set; } public string profile_pic { get; set; } public string full_name { get; set; } public string from { get; set; } public string to { get; set; } public string book_id { get; set; } public string currentLatLong { get; set; } } public class DriverAcceptInfo { public int user_id { get; set; } public string profile_pic { get; set; } public string full_name { get; set; } public string from { get; set; } public string to { get; set; } public string book_id { get; set; } public string currentLatLong { get; set; } public string datetime { get; set; } public string perSeatCash { get; set; } public string brand { get; set; } public string model { get; set; } public string color { get; set; } public string plateNumber { get; set; } public string carPhoto { get; set; } public string type { get; set; } } } }
namespace Contoso.KendoGrid.Api { public class ConfigurationOptions { #region Constants public const string DEFAULTBASEBSLURL = "http://localhost:53345/api"; #endregion Constants #region Properties public string BaseBslUrl { get; set; } = DEFAULTBASEBSLURL; #endregion Properties } }
using System; namespace Person { public class Male { public void MaleInfo() { Console.WriteLine("Male info"); } } }
using System.Collections.Generic; using System.Text; using System; namespace LinnworksAPI { public class OrderRefundLinesPaged { public Int32 Page; public Int32 TotalReferences; public Int32 ReferencesPerPage; public Int32 ActualItemsPerPage; public List<OrderRefundLine> OrderRefundLines; } }
 using MongoDB.Bson; using RecipeLibrary.Recipes; using MongoDB.Bson.Serialization.Attributes; namespace RecipeLibrary.MongoDB.Recipes { public class IMongoRecipe : IRecipe { [BsonId] public ObjectId ObjectId { get; set; } [BsonElement("recipeId")] public int RecipeId { get; set; } [BsonElement("title")] public string Title { get; set; } [BsonElement("ingredients")] public string Ingredients { get; set; } [BsonElement("directions")] public string Directions { get; set; } [BsonElement("link")] public string Link { get; set; } [BsonElement("source")] public string Source { get; set; } [BsonElement("NER")] public string NER { get; set; } } }
/* * Copyright 2021 Adobe * All Rights Reserved. * * NOTICE: Adobe permits you to use, modify, and distribute this file in * accordance with the terms of the Adobe license agreement accompanying * it. If you have received this file from a source other than Adobe, * then your use, modification, or distribution of it requires the prior * written permission of Adobe. */ using System.IO; using System; using log4net.Repository; using log4net.Config; using log4net; using System.Reflection; using Adobe.PDFServicesSDK; using Adobe.PDFServicesSDK.auth; using Adobe.PDFServicesSDK.options.documentmerge; using Adobe.PDFServicesSDK.pdfops; using Adobe.PDFServicesSDK.io; using Adobe.PDFServicesSDK.exception; using Newtonsoft.Json.Linq; /// <summary> /// This sample illustrates how to merge the Word based document template with the input JSON data to generate the output document in the DOCX format. /// <para> /// To know more about document generation and document templates, please see the <a href="http://www.adobe.com/go/dcdocgen_overview_doc">documentation</a> /// And to know more about fragments use-case in document generation and document templates, please see the <a href="http://www.adobe.com/go/dcdocgen_fragments_support_doc">documentation</a> /// </para> /// Refer to README.md for instructions on how to run the samples. /// </summary> /// namespace MergeDocumentToDocxFragments { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServicePrincipalCredentialsBuilder() .WithClientId(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID")) .WithClientSecret(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET")) .Build(); // Create an ExecutionContext using credentials. ExecutionContext executionContext = ExecutionContext.Create(credentials); // Setup input data for the document merge process var content = File.ReadAllText(@"orderDetail.json"); JObject jsonDataForMerge = JObject.Parse(content); // Fragment one JObject obj1 = JObject.Parse("{\"orderDetails\": \"<b>Quantity</b>:{{quantity}}, <b>Description</b>:{{description}}, <b>Amount</b>:{{amount}}\"}"); // Fragment two JObject obj2 = JObject.Parse("{\"customerDetails\": \"{{customerName}}, Visits: {{customerVisits}}\"}"); // Fragment Object Fragments fragments = new Fragments(); // Adding Fragments to the Fragment object fragments.AddFragment(obj1); fragments.AddFragment(obj2); // Create a new DocumentMerge Options instance with fragment DocumentMergeOptions documentMergeOptions = new DocumentMergeOptions(jsonDataForMerge, OutputFormat.DOCX, fragments); // Create a new DocumentMerge Operation instance with the DocumentMerge Options instance DocumentMergeOperation documentMergeOperation = DocumentMergeOperation.CreateNew(documentMergeOptions); // Set the operation input document template from a source file. documentMergeOperation.SetInput(FileRef.CreateFromLocalFile(@"orderDetailTemplate.docx")); // Execute the operation. FileRef result = documentMergeOperation.Execute(executionContext); //Generating a file name String outputFilePath = CreateOutputFilePath(); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + outputFilePath); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } catch (ServiceApiException ex) { log.Error("Exception encountered while executing operation", ex); } catch (SDKException ex) { log.Error("Exception encountered while executing operation", ex); } catch (IOException ex) { log.Error("Exception encountered while executing operation", ex); } catch (Exception ex) { log.Error("Exception encountered while executing operation", ex); } } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } //Generates a string containing a directory structure and file name for the output file. public static string CreateOutputFilePath() { String timeStamp = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH'-'mm'-'ss"); return ("/output/merge" + timeStamp + ".docx"); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using AutoMapper; using Dentist.Enums; using Dentist.Models; using Kendo.Mvc.UI; using Microsoft.Owin.Security.Google; namespace Dentist.ViewModels { public class SchedulerPracticeViewModel { public int Id { get; set; } public string Name { get; set; } public string Color { get; set; } } public class SchedulerDoctorViewModel { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Color { get; set; } //public List<SchedulerPracticeViewModel> Practices { get; set; } } public class SchedulerAppointmentViewModel : ISchedulerEvent { public int Id { get; set; } [Display(Name = "Doctor")] public int DoctorId { get; set; } [Display(Name = "Search")] public int? PatientId { get; set; } [Display(Name = "First Name")] [Required] public string FirstName { get; set; } [Display(Name = "Last Name")] [Required] public string LastName { get; set; } [DataType(DataType.PhoneNumber)] public string Phone { get; set; } [Display(Name = "Status")] public AppointmentStatus AppointmentStatus { get; set; } [Display(Name = "Practice")] public int PracticeId { get; set; } public string PracticeColor { get; set; } //Inherited public DateTime Start { get; set; } //Inherited public DateTime End { get; set; } //Inherited [DataType(DataType.MultilineText)] public string Description { get; set; } //Inherited private string _title; public string Title { get { return FirstName + " " + LastName; } set { _title = value; } } //Inherited [Display(Name = "Recurrence")] public string RecurrenceRule { get; set; } //Inherited public string RecurrenceException { get; set; } [Display(Name = "Is Break")] public bool IsBreak { get; set; } //Inherited Exclude public bool IsAllDay { get; set; } //Inherited Exclude public string StartTimezone { get; set; } //Inherited Exclude public string EndTimezone { get; set; } } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; using Tadu.NetCore.Api.Extensions; using Tadu.NetCore.Data.CustomModel; using Tadu.NetCore.Data.Model; using Tadu.NetCore.Data.Services; namespace Tadu.NetCore.Api.Controllers { [ApiController] [AuthorizeExtention] [Route("[controller]")] public class UserController : BaseApiController { private readonly ILogger<UserController> _logger; private readonly IUserService _userService; public UserController(ILogger<UserController> logger, IUserService userService) { _logger = logger; _userService = userService; } [HttpPost("RegisterUser")] [AllowAnonymous] public async Task<IActionResult> RegisterUser(RegisterUserModel model) { try { var result = await _userService.RegisterUserAsync(model); if (result.Succeeded) { return Ok(result); } var mess = "Error :"; foreach (var item in result.Errors) { mess += item.Description; } return BadRequest(new { message = mess }); } catch (Exception ex) { this.log.Error(string.Format(Conts.Conts.ApiErrorMessageLog, ControllerContext.ActionDescriptor.ControllerName, ControllerContext.ActionDescriptor.ActionName), ex); return BadRequest(new { message = Conts.Conts.ApiErrorMessageResponse }); } } [HttpPost("Login")] [AllowAnonymous] public async Task<IActionResult> Login(LoginModel model) { try { var result = await _userService.Login(model); if (result!=null) { return Ok(result); } var mess = "Error : Invalid Login Attempt"; return BadRequest(new { message = mess }); } catch (Exception ex) { this.log.Error(string.Format(Conts.Conts.ApiErrorMessageLog, ControllerContext.ActionDescriptor.ControllerName, ControllerContext.ActionDescriptor.ActionName), ex); return BadRequest(new { message = Conts.Conts.ApiErrorMessageResponse }); } } [HttpPost("authenticate")] [AllowAnonymous] public async Task<IActionResult> Authenticate(AuthenticateRequest model) { var response = await _userService.Authenticate(model); if (response==null) return BadRequest(new { message = "Username or password is incorrect" }); return Ok(response); } [HttpPost("Logout")] public async Task Logout() { await _userService.Logout(); } } }
using System; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Claims; using System.Threading; using System.Web; using System.Web.Http; using CloneDeploy_App.Controllers.Authorization; using CloneDeploy_Entities.DTOs; using CloneDeploy_Services.Workflows; namespace CloneDeploy_App.Controllers { public class WorkflowController : ApiController { [CustomAuth(Permission = "Administrator")] [HttpGet] public ApiBoolResponseDTO CancelAllImagingTasks() { return new ApiBoolResponseDTO {Value = new CancelAllImagingTasks().Execute()}; } [CustomAuth(Permission = "AdminUpdate")] [HttpGet] public ApiBoolResponseDTO CopyPxeBinaries() { return new ApiBoolResponseDTO {Value = new CopyPxeBinaries().Execute()}; } [CustomAuth(Permission = "AdminUpdate")] [HttpGet] public ApiBoolResponseDTO CreateClobberBootMenu(int profileId, bool promptComputerName) { new ClobberBootMenu(profileId, promptComputerName).Execute(); return new ApiBoolResponseDTO {Value = true}; } [CustomAuth(Permission = "AdminUpdate")] [HttpPost] public ApiBoolResponseDTO CreateDefaultBootMenu(BootMenuGenOptionsDTO defaultMenuOptions) { new DefaultBootMenu(defaultMenuOptions).Execute(); return new ApiBoolResponseDTO {Value = true}; } [CustomAuth(Permission = "AdminUpdate")] [HttpGet] public ActionResultDTO UpdateDatabase() { return new DbUpdater().Update(); } [CustomAuth(Permission = "AdminUpdate")] [HttpPost] public HttpResponseMessage GenerateLinuxIsoConfig(IsoGenOptionsDTO isoOptions) { new IsoGen(isoOptions).Generate(); var basePath = HttpContext.Current.Server.MapPath("~") + Path.DirectorySeparatorChar + "private" + Path.DirectorySeparatorChar + "client_iso" + Path.DirectorySeparatorChar; if (isoOptions.buildType == "ISO") basePath += "clientboot.iso"; else basePath += "clientboot.zip"; var result = new HttpResponseMessage(HttpStatusCode.OK); var stream = new FileStream(basePath, FileMode.Open); result.Content = new StreamContent(stream); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(basePath); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentLength = stream.Length; return result; } [CustomAuth(Permission = "AllowOnd")] [HttpGet] public ApiStringResponseDTO StartOnDemandMulticast(int profileId,string clientCount,string sessionName, int clusterId) { var identity = (ClaimsPrincipal) Thread.CurrentPrincipal; var userId = identity.Claims.Where(c => c.Type == "user_id") .Select(c => c.Value).SingleOrDefault(); return new ApiStringResponseDTO { Value = new Multicast(profileId, clientCount,sessionName, Convert.ToInt32(userId), Request.GetClientIpAddress(),clusterId).Create() }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using JIoffe.PizzaBot.Model; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.AI.Luis; using Microsoft.Bot.Builder.Dialogs; using Newtonsoft.Json; using PizzaBot.Accessors; using PizzaBot.Responses; namespace PizzaBot.Dialogs { public class MainMenuDialogFactory : IDialogFactory { private readonly PizzaOrderAccessors _accessors; private readonly LuisRecognizer _luisRecognizer; /// <summary> /// Predictions with lower scores than this threshold should be ignored /// </summary> private const double CONFIDENCE_THRESHOLD = 0.6D; public MainMenuDialogFactory(PizzaOrderAccessors accessors, LuisRecognizer luisRecognizer) { _accessors = accessors; _luisRecognizer = luisRecognizer; } public Dialog Build() { //The WaterfallDialog is a type of dialog that can //have one or many steps that flow into eachother linearly. //The result of one Waterfall step will carry to the start //of the next one. //At any point, you are able to push or pop from the dialog stack. //Observe how the steps are applied here so that you can create //the steps necessary for placing an order. var steps = new WaterfallStep[] { MainMenuAsync }; var dialog = new WaterfallDialog(DialogNames.MAIN_MENU, steps); return dialog; } private async Task<DialogTurnResult> MainMenuAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { var turnContext = stepContext.Context; //Step 9) Pass the ITurnContext into the LuisRecognizer to get the top scoring intent for this turn. var recognizerResult = await _luisRecognizer.RecognizeAsync(turnContext, cancellationToken); (string intent, double score) = recognizerResult.GetTopScoringIntent(); //Step 10) If the score is below a confidence threshold, show confusion response and end dialog if(score < CONFIDENCE_THRESHOLD) { await turnContext.SendActivityAsync(MainMenu.Confusion, cancellationToken: cancellationToken); return await stepContext.EndDialogAsync(); } //Step 11) Create a switch statement against the intent. For "Greeting", send a welcome message. //For "Help", send a help message. Default to confusion. These should match whatever you named //your intent(s) in Luis.ai. //We will return to this method in the future to support the "OrderPizza" intent for ordering pizza. //Use the ApplyEntitiesToOrderState helper method to flesh out an order state using Luis.ai entities. switch (intent) { case "Greeting": await turnContext.SendActivityAsync(MainMenu.WelcomeReturningUser, cancellationToken: cancellationToken); break; case "Help": await turnContext.SendActivityAsync(MainMenu.Help, cancellationToken: cancellationToken); break; case "OrderPizza": //Clear the previous state and apply any relevant LUIS await ApplyEntitiesToOrderState(turnContext, recognizerResult); return await stepContext.BeginDialogAsync(DialogNames.PIZZA_ORDER, null, cancellationToken); default: await turnContext.SendActivityAsync(MainMenu.Confusion, cancellationToken: cancellationToken); break; } //After all is over, we will end this dialog. //If it is the last dialog in the stack, we will recreate it //in OnTurnAsync. Alternatively, we could simply replace this instance //of a MainMenu dialog with a new one. return await stepContext.EndDialogAsync(); } private async Task ApplyEntitiesToOrderState(ITurnContext turnContext, RecognizerResult recognizerResult) { var state = await _accessors.PizzaOrderState.GetAsync(turnContext, () => new States.PizzaOrderState()); state.CurrentOrder = new PizzaOrder(); //This direct enum parse will not capture pluralizations or alternate spellings! //But it is a straightforward example of how to apply the entities into the state var sizeEntities = recognizerResult.Entities.SelectToken("Size"); var toppingEntities = recognizerResult.Entities.SelectToken("Topping"); if(sizeEntities != null) { var label = JsonConvert.DeserializeObject<IEnumerable<string>>(JsonConvert.SerializeObject(sizeEntities)).FirstOrDefault(); PizzaSize size; if(Enum.TryParse(label, true, out size)) { state.CurrentOrder.Size = size; } } if(toppingEntities != null) { var labels = JsonConvert.DeserializeObject<IEnumerable<string>>(JsonConvert.SerializeObject(toppingEntities)); state.CurrentOrder.Toppings = labels.Select(label => { PizzaTopping topping = 0; Enum.TryParse(label, true, out topping); return topping; }) .Where(t => t != 0) .ToHashSet(); } await _accessors.ConversationState.SaveChangesAsync(turnContext); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Item : MonoBehaviour { private GameObject mPlayer; private void DistanceUpdate() { float _x = transform.position.x; float _y = transform.position.y; //float _z = transform.position.z; if (transform.position.y <= mPlayer.transform.position.y) { transform.position = new Vector3(_x, _y, transform.parent.position.z-1); } else { transform.position = new Vector3(_x, _y, transform.parent.position.z+1); } } void Awake() { } // Use this for initialization void Start () { mPlayer = GameManager.GetInstance().GetGamePlayer(); } // Update is called once per frame void Update () { DistanceUpdate(); } }
using System; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Windows.Forms; using Top_Down_shooter.Properties; using Top_Down_shooter.Scripts.Components; using Top_Down_shooter.Scripts.Controllers; using Top_Down_shooter.Scripts.GameObjects; using Top_Down_shooter.Scripts.Source; using unvell.D2DLib; namespace Top_Down_shooter { public class Form1 : Form { private readonly int IntervalUpdateGameLoop = 30; private D2DGraphicsDevice device; private D2DMatrix3x2 defaultTransform; private D2DBitmap bulletIcon; private D2DBitmap gameOverImage; private D2DBitmap victoryImage; private readonly Point positionLableCountBullets = new Point(980, 670); private readonly Point positionBulletIcon = new Point(910, 660); private readonly Random randGenerator = new Random(); public Form1() { Cursor = new Cursor("Cursor.cur"); DoubleBuffered = false; Size = new Size(GameSettings.ScreenWidth, GameSettings.ScreenHeight); FormBorderStyle = FormBorderStyle.FixedToolWindow; CenterToScreen(); GameModel.Initialize(); GameRender.Initialize(); RunTimeInvoker(IntervalUpdateGameLoop, UpdateGameLoop); RunTimeInvoker(GameSettings.DelaySpawnNewMonster, GameModel.SpawnTank); RunTimeInvoker(GameSettings.BossCooldown, GameModel.SpawnFire); RunFunctionAsync(Controller.UpdateKeyboardHandler); RunFunctionAsync(Controller.UpdateMouseHandler); RunFunctionAsync(NavMesh.Update); RunFunctionAsync(Physics.Update); RunFunctionAsync(GameRender.PlayAnimations); } protected override void OnLoad(EventArgs e) { device = new D2DGraphicsDevice(this); defaultTransform = device.Graphics.GetTransform(); bulletIcon = device.CreateBitmap(Resources.BulletIcon); gameOverImage = device.CreateBitmap(Resources.GameOver); victoryImage = device.CreateBitmap(Resources.Victory); } protected override void OnKeyDown(KeyEventArgs e) { if (e.KeyCode == Keys.F && GameModel.IsEnd) Application.Restart(); } protected override void OnPaintBackground(PaintEventArgs e) { } protected override void OnPaint(PaintEventArgs e) { device.BeginRender(); device.Graphics.SetTransform(defaultTransform); device.Graphics.TranslateTransform(-GameRender.Camera.X, -GameRender.Camera.Y); GameRender.DrawScene(device); device.Graphics.DrawText( GameModel.Player.Gun.CountBullets.ToString(), D2DColor.Black, "Intro", 35, GameRender.Camera.X + positionLableCountBullets.X, GameRender.Camera.Y + positionLableCountBullets.Y); device.Graphics.DrawBitmap(bulletIcon, new D2DRect( GameRender.Camera.X + positionBulletIcon.X, GameRender.Camera.Y + positionBulletIcon.Y, bulletIcon.Size.width, bulletIcon.Size.height)); if (GameModel.IsEnd) { if (GameModel.Player.Health < 1) { device.Graphics.DrawBitmap(gameOverImage, new D2DRect( GameRender.Camera.X + GameSettings.ScreenWidth / 2 - gameOverImage.Width / 2, GameRender.Camera.Y + GameSettings.ScreenHeight / 2 - gameOverImage.Height / 2, gameOverImage.Width, gameOverImage.Height)); } else { device.Graphics.DrawBitmap(victoryImage, new D2DRect( GameRender.Camera.X + GameSettings.ScreenWidth / 2 - victoryImage.Width / 2, GameRender.Camera.Y + GameSettings.ScreenHeight / 2 - victoryImage.Height / 2, victoryImage.Width, victoryImage.Height)); } } device.EndRender(); } private void UpdateGameLoop() { if (!GameModel.IsEnd) { UpdatePlayer(); UpdateEnemies(); UpdateBullets(); UpdateFires(); if (GameModel.Player.Health < 0 || GameModel.Boss.Health < 0) GameModel.IsEnd = true; } Invalidate(); } private void UpdatePlayer() { var mousePosition = PointToClient(MousePosition); GameRender.Camera.Move(GameModel.Player); GameModel.Player.Gun.Angle = (float)Math.Atan2( mousePosition.Y + GameRender.Camera.Y - GameModel.Player.Gun.Y, mousePosition.X + GameRender.Camera.X - GameModel.Player.Gun.X); var prevPos = GameModel.Player.Transform; GameModel.Player.MoveX(); if (Physics.IsCollided(GameModel.Player.Collider, typeof(Box), typeof(Block), typeof(Boss))) GameModel.Player.SetX(prevPos.X); GameModel.Player.MoveY(); if (Physics.IsCollided(GameModel.Player.Collider, typeof(Box), typeof(Block), typeof(Boss))) GameModel.Player.SetY(prevPos.Y); if (Physics.IsHit(GameModel.Player.HitBox, out var collisions)) { foreach (var other in collisions.Select(collider => collider.GameObject)) { if (other is Fire fire && fire.CanKick) { fire.CanKick = false; GameModel.Player.Health -= GameSettings.FireDamage; continue; } if (other is Powerup powerup) { if (powerup is HP) { if (GameModel.Player.Health < GameSettings.PlayerHealth) { GameModel.Player.Health += powerup.Boost; GameModel.RespawnStaticPowerup(powerup); } } else { GameModel.Player.Gun.CountBullets += powerup.Boost; if (powerup is BigLoot) { GameModel.Powerups.Remove(powerup); Physics.RemoveFromTrackingHitBoxes(powerup.Collider); GameRender.RemoveRender(powerup); } else GameModel.RespawnStaticPowerup(powerup); } } } } } private void UpdateEnemies() { lock (GameModel.LockerEnemies) { GameModel.Boss.LookAt(GameModel.Player.Transform); while (GameModel.NewEnemies.Count > 0) { var enemy = GameModel.NewEnemies.Dequeue(); if (enemy is null) continue; GameModel.Enemies.Add(enemy); Physics.AddToTrackingColliders(enemy.Collider); Physics.AddToTrackingHitBoxes(enemy.HitBox); GameRender.AddRenderFor(enemy); } foreach (var enemy in GameModel.Enemies) { if (enemy.Health < 1) { GameModel.RemovedEnemies.Enqueue(enemy); } if (enemy is Fireman fireman) GameModel.UpdateTargetFireman(fireman); enemy.Move(); if (enemy is Tank tank && Physics.IsHit(enemy.HitBox, out var collisions)) { foreach (var other in collisions.Select(hitBox => hitBox.GameObject)) { if (other is Fire fire && fire.CanKick) { fire.CanKick = false; enemy.Health -= GameSettings.FireDamage; } if (other is Player && tank.CanKick) { GameModel.Player.Health -= GameSettings.TankDamage; tank.CanKick = false; } } } } while (GameModel.RemovedEnemies.Count > 0) { var enemy = GameModel.RemovedEnemies.Dequeue(); GameModel.Enemies.Remove(enemy); GameRender.RemoveRender(enemy); NavMesh.RemoveAgent(enemy.Agent); Physics.RemoveFromTrackingColliders(enemy.Collider); Physics.RemoveFromTrackingHitBoxes(enemy.HitBox); enemy.Cooldown.Dispose(); GameModel.SpawnBigLoot(enemy); } } } private void UpdateBullets() { lock (GameModel.LockerBullets) { while (GameModel.NewBullets.Count > 0) { var bullet = GameModel.NewBullets.Dequeue(); if (bullet is null) continue; if (bullet.Parent is Player) GameModel.Player.Gun.CountBullets--; GameModel.Bullets.Add(bullet); GameRender.AddRenderFor(bullet); } foreach (var bullet in GameModel.Bullets) { bullet.Move(); if (Physics.IsHit(bullet.Collider, out var collisions)) { var willBeDestroyed = false; foreach (var other in collisions.Select(hitBox => hitBox.GameObject)) { if (other is Block) willBeDestroyed = true; if (other is Box box) { box.Health -= bullet.Damage; if (box.Health < 1) { GameModel.ChangeBoxToGrass(box); Physics.RemoveFromTrackingColliders(box.Collider); Physics.RemoveFromTrackingHitBoxes(box.Collider); GameRender.RemoveRender(box); } willBeDestroyed = true; } if (other is Player && !(bullet.Parent is Player)) { GameModel.Player.Health -= bullet.Damage; willBeDestroyed = true; } if (other is Enemy enemy) { if ((enemy is Fireman || enemy is Boss) && bullet.Parent is Fireman) continue; enemy.Health -= bullet.Damage; willBeDestroyed = true; } } if (willBeDestroyed) { GameModel.DeletedBullets.Enqueue(bullet); GameRender.RemoveRender(bullet); Physics.RemoveFromTrackingHitBoxes(bullet.Collider); } } } while (GameModel.DeletedBullets.Count > 0) { var removedBullet = GameModel.DeletedBullets.Dequeue(); GameModel.Bullets.Remove(removedBullet); GameRender.RemoveRender(removedBullet); } } } private void UpdateFires() { lock (GameModel.LockerFires) { while (GameModel.NewFires.Count > 0) { var fire = GameModel.NewFires.Dequeue(); GameModel.Fires.Add(fire); GameModel.MovingFires.AddLast(fire); } for (var fire = GameModel.MovingFires.First; !(fire is null); fire = fire.Next) { fire.Value.Move(); if (fire.Value.IsCompleteMoving) { GameModel.MovingFires.Remove(fire); } } } } private void RunTimeInvoker(int interval, Action func) { var timer = new System.Windows.Forms.Timer(); timer.Interval = interval; timer.Tick += (sender, args) => func(); timer.Start(); } private void RunFunctionAsync(Action func) { var worker = new BackgroundWorker(); worker.DoWork += (sender, args) => func(); worker.RunWorkerAsync(); } } }
using Hayalpc.Fatura.Data; using Hayalpc.Fatura.Data.Models; using Hayalpc.Fatura.Panel.Internal.Services.Interfaces; using Hayalpc.Library.Log; using Hayalpc.Library.Repository.Interfaces; using Microsoft.Extensions.Caching.Memory; namespace Hayalpc.Fatura.Panel.Internal.Services { public class TableDefinitionService : BaseService<TableDefinition>, ITableDefinitionService { public TableDefinitionService(IRepository<TableDefinition> repository, IHpLogger logger, IHpUnitOfWork<HpDbContext> unitOfWork, IMemoryCache memoryCache) : base(repository, logger, unitOfWork, memoryCache) { } public override TableDefinition BeforeAdd(TableDefinition model) { model.Namespace = model.GetType().Namespace; model.Assembly = model.GetType().Assembly.ToString(); return base.BeforeAdd(model); } public override TableDefinition BeforeUpdate(TableDefinition model) { model.Namespace = model.GetType().Namespace; model.Assembly = model.GetType().Assembly.ToString(); return base.BeforeAdd(model); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Game.Network { public class ClientPool<T> { private Stack<T> m_pool; public ClientPool(int capacity) { m_pool = new Stack<T>(capacity); } public void Push(T item) { if (item == null) { throw new ArgumentException("Items added to a AsyncSocketUserToken cannot be null"); } lock (m_pool) { m_pool.Push(item); } } public T Pop() { lock (m_pool) { return m_pool.Pop(); } } public int Count { get { return m_pool.Count; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DataObject; namespace Service.Interface { public interface IDichVu { int ThemDichVu(DichVu dv); int CapNhatDichVu(DichVu dv); int XoaDichVu(int maDV); } }
using System; using System.Collections.Generic; using UnityEngine; namespace YoukiaUnity.View { public class CallbackEventInfo { public GameObject target; public bool isPlayEnd; public string currentAnimName; public CallbackEventInfo(GameObject target, string AnimName, bool isPlayEnd) { this.target = target; this.currentAnimName = AnimName; this.isPlayEnd = isPlayEnd; } } }
using System; using System.Collections.Generic; using UnityEngine; namespace RO { [CustomLuaClass] public class BusManager : SingleTonGO<BusManager> { private Dictionary<long, Bus> buses_ = new Dictionary<long, Bus>(); public static BusManager Instance { get { return SingleTonGO<BusManager>.Me; } } public GameObject monoGameObject { get { return base.get_gameObject(); } } public bool Add(Bus bus) { if (this.buses_.ContainsKey(bus.ID)) { return false; } this.buses_.Add(bus.ID, bus); return true; } public void Remove(Bus bus) { if (!this.buses_.ContainsKey(bus.ID)) { return; } this.buses_.Remove(bus.ID); } public Bus GetBus(long ID) { Bus result; if (this.buses_.TryGetValue(ID, ref result)) { return result; } return null; } public Dictionary<long, Bus> GetBuses() { return this.buses_; } public Bus CloneBus(long id) { Bus bus = this.GetBus(id); if (null != bus) { return bus.Copy(); } return null; } } }
//Created by: Manuel Muncaster //Date: February 14, 2017 //Purpose: This is a replica of the electronic game "Simon Says" 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 Simon_Says { public partial class Form1 : Form { public Form1() { InitializeComponent(); MainScreen ms = new MainScreen(); this.Controls.Add(ms); } //Setting up lists public static List<int> pattern = new List<int>(); public static List<int> sound = new List<int>(); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace solution1 { public partial class FormBonsDeTransfert : Form { string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["connectString1"].ConnectionString; string requete = null; DataSet dS = null; string dateDebut = null; string dateFin = null; string idinventaire; public FormBonsDeTransfert(string uidInventaire) { this.idinventaire = uidInventaire; InitializeComponent(); } private void FormBonsDeTransfert_Load(object sender, EventArgs e) { chargerBonsDeTransfert(); this.WindowState = FormWindowState.Maximized; } private void chargerBonsDeTransfert() { if (rBTous.Checked) { requete = "create view maVue as select idBonTransfert, dateTransfert, motifTransfert, IdSiteSource, idSiteDestination, NomSite as NomSiteSource, etatBonTransfert from BonTransfert, Site where BonTransfert.idSiteSource = Site.idSite and etatBonTransfert = 'Non supprimé'"; } else { if (rBNumBonTransfert.Checked) { requete = "create view maVue as select idBonTransfert, dateTransfert, motifTransfert, IdSiteSource, idSiteDestination, NomSite as NomSiteSource, etatBonTransfert from BonTransfert, Site where BonTransfert.idSiteSource = Site.idSite and etatBonTransfert = 'Non supprimé' and idBonTransfert = " + tBIdBonTransfert.Text; } else { if (rBDate.Checked) { dateDebut = this.dTPDebut.Value.ToString("dd/MM/yyyy"); dateFin = this.dTPFin.Value.ToString("dd/MM/yyyy"); requete = "create view maVue as select idBonTransfert, dateTransfert, motifTransfert, IdSiteSource, idSiteDestination, NomSite as NomSiteSource, etatBonTransfert from BonTransfert, Site where BonTransfert.idSiteSource = Site.idSite and etatBonTransfert = 'Non supprimé' and dateTransfert > '" + dateDebut + "' and dateTransfert < '" + dateFin + "'"; } } } dGVBonDeTransfert.Rows.Clear(); MaConnexion.ExecuteUpdate(connectionString, requete); try { requete = "select maVue.idBonTransfert, maVue.dateTransfert, maVue.motifTransfert, maVue.NomSiteSource, NomSite as NomSiteDestination from maVue, site where maVue.idSiteDestination = Site.idSite;"; dS = MaConnexion.ExecuteSelect(connectionString, requete); foreach (DataRow row in dS.Tables[0].Rows) { int jour = Int32.Parse(row[1].ToString().Substring(0, 2)); int mois = Int32.Parse(row[1].ToString().Substring(3, 2)); int année = Int32.Parse(row[1].ToString().Substring(6, 4)); DateTime date = new DateTime(année, mois, jour); object[] lignePVCession = new object[] { row[0].ToString(), date, row[2].ToString(), row[3].ToString(), row[4].ToString(), null, null, null }; dGVBonDeTransfert.Rows.Add(lignePVCession); } } catch (Exception) { } finally { requete = "drop view maVue "; dS = MaConnexion.ExecuteSelect(connectionString, requete); //suppression de la vue intermédiaire } } //************************ recherche avancée private void tBIdBonTransfert_TextChanged(object sender, EventArgs e) { rBNumBonTransfert.Checked = true; chargerBonsDeTransfert(); } private void dTPDebut_ValueChanged(object sender, EventArgs e) { rBDate.Checked = true; chargerBonsDeTransfert(); } private void dTPFin_ValueChanged(object sender, EventArgs e) { rBDate.Checked = true; chargerBonsDeTransfert(); } private void rBNumBonTransfert_CheckedChanged(object sender, EventArgs e) { if (rBNumBonTransfert.Checked) chargerBonsDeTransfert(); } private void rBTous_CheckedChanged(object sender, EventArgs e) { if (rBTous.Checked) chargerBonsDeTransfert(); } private void rBDate_CheckedChanged(object sender, EventArgs e) { if (rBDate.Checked) chargerBonsDeTransfert(); } // ************************** bonton datagrid private void dGVBonDeTransfert_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.ColumnIndex == -1 || e.RowIndex == -1) return; if (dGVBonDeTransfert.Columns[e.ColumnIndex].Name == "ColumnImprimer") { if (e.RowIndex != dGVBonDeTransfert.RowCount - 1) { e.Paint(e.CellBounds, DataGridViewPaintParts.All); int intTop = (e.CellBounds.Height - 16) / 2 + e.CellBounds.Top; int intLeft = (e.CellBounds.Width - 16) / 2 + e.CellBounds.Left; try { e.Graphics.DrawImage(System.Drawing.Image.FromFile("imprimer.jpeg"), intLeft, intTop); } catch (Exception) { } e.Handled = true; } } else if (dGVBonDeTransfert.Columns[e.ColumnIndex].Name == "ColumnSupprimer") { if (e.RowIndex != dGVBonDeTransfert.RowCount - 1) { e.Paint(e.CellBounds, DataGridViewPaintParts.All); int intTop = (e.CellBounds.Height - 16) / 2 + e.CellBounds.Top; int intLeft = (e.CellBounds.Width - 16) / 2 + e.CellBounds.Left; try { e.Graphics.DrawImage(System.Drawing.Image.FromFile("delete.gif"), intLeft, intTop); } catch (Exception) { } e.Handled = true; } } else if (dGVBonDeTransfert.Columns[e.ColumnIndex].Name == "ColumnModifier") { if (e.RowIndex != dGVBonDeTransfert.RowCount - 1) { e.Paint(e.CellBounds, DataGridViewPaintParts.All); int intTop = (e.CellBounds.Height - 16) / 2 + e.CellBounds.Top; int intLeft = (e.CellBounds.Width - 10) / 2 + e.CellBounds.Left; try { e.Graphics.DrawImage(System.Drawing.Image.FromFile("modifier.gif"), intLeft, intTop); } catch (Exception) { } e.Handled = true; } else { e.Paint(e.CellBounds, DataGridViewPaintParts.All); int intTop = (e.CellBounds.Height - 16) / 2 + e.CellBounds.Top; int intLeft = (e.CellBounds.Width - 16) / 2 + e.CellBounds.Left; try { e.Graphics.DrawImage(System.Drawing.Image.FromFile("images.jpeg"), intLeft, intTop); } catch (Exception) { } e.Handled = true; } } } private void dGVBonDeTransfert_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex < 0 || e.ColumnIndex < 0) return; //click sur le bouton de suppression if (dGVBonDeTransfert.Columns[e.ColumnIndex].Name == "ColumnImprimer") { if (e.RowIndex != dGVBonDeTransfert.RowCount - 1) //bouton de suppression { try { // (new FormCRBonTransfert(dGVBonDeTransfert.Rows[e.RowIndex].Cells["ColumnIdBonTransfert"].Value.ToString())).ShowDialog(); } catch (Exception) { } } } else if (dGVBonDeTransfert.Columns[e.ColumnIndex].Name == "ColumnModifier") //click sur le bouton de modification ou d'ajout { if (e.RowIndex != dGVBonDeTransfert.RowCount - 1) //click sur le bouton de modification { (new ModifierBonTransfert(dGVBonDeTransfert.Rows[e.RowIndex].Cells["ColumnIdBonTransfert"].Value.ToString(),idinventaire)).ShowDialog(); } else //click sur le bouton d'ajout { (new AjouterBonDeTransfert(idinventaire)).ShowDialog(); } //Ce que j'ai fait ici, c'est du bricolage : à réctifier this.Visible = false; (new FormBonsDeTransfert(idinventaire)).Show(); } else if (dGVBonDeTransfert.Columns[e.ColumnIndex].Name == "ColumnSupprimer") //click sur le bouton de suppression { if (MessageBox.Show("Voulez vous vraiment supprimer ce bon de transfert ?", "Supprimer un bon de transfert", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) { requete = "update BonTransfert set etatBonTransfert = 'Supprimé' where idBonTransfert = " + dGVBonDeTransfert.Rows[e.RowIndex].Cells["ColumnIdBonTransfert"].Value.ToString(); if (MaConnexion.ExecuteUpdate(connectionString, requete) != 1) { MessageBox.Show("Echec de suppression du bon de transfert", "Erreur de suppression", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { //dGVBonDeTransfert.Rows.RemoveAt(e.RowIndex); dGVBonDeTransfert.Rows.Remove(dGVBonDeTransfert.Rows[e.RowIndex]); } } //chargerBonsDeTransfert(); } } private void dGVBonDeTransfert_SelectionChanged(object sender, EventArgs e) { chargerBiensTransférés(); } private void chargerBiensTransférés() { dGVBiens.Rows.Clear(); try { /* requete = "create view vueBonDeTransfert as select Bien.idBien, Bien.ancienCode, Bien.DesigBien, CategorieBien.DesigCategorieBien, Bien.DateAcquisitionBien, Etat.DesigEtat, Bien.Prix, Bien.Particularite,Transferer.idEmplaSource, Transferer.idEmplaDest, Emplacement.DesigEmpla as DesigEmplaSource, Transferer.reçu from bien, Transferer, CategorieBien, Emplacement, SeTrouveB, Etat where Emplacement.idEmplaComplet = Transferer.idEmplaSource and Bien.IdBien = Transferer.idBien and CategorieBien.IdCategorieBien = Bien.IdCategorieBien and seTrouveB.IdBien = Bien.idBien and seTrouveB.IdEtat = Etat.idEtat and SeTrouveB.uidInventaire = '" + idinventaire + "' and Transferer.idBonTransfert = " + dGVBonDeTransfert.Rows[dGVBonDeTransfert.CurrentCell.RowIndex].Cells["ColumnIdBonTransfert"].Value; Console.WriteLine(requete); MaConnexion.ExecuteUpdate(connectionString, requete); requete = "select vueBonDeTransfert.idBien, vueBonDeTransfert.ancienCode, vueBonDeTransfert.DesigBien, vueBonDeTransfert.DesigCategorieBien, vueBonDeTransfert.DateAcquisitionBien, vueBonDeTransfert.DesigEtat,vueBonDeTransfert.Prix, vueBonDeTransfert.Particularite, vueBonDeTransfert.DesigEmplaSource,Emplacement.DesigEmpla as DesigEmplaDestination, vueBonDeTransfert.reçu from vueBonDeTransfert, Emplacement where vueBonDeTransfert.idEmplaDest = Emplacement.idEmplaComplet"; Console.WriteLine(requete); */ string requete3 = "select Bien.idbien,Transferer.idEmplaSource,Transferer.idEmplaDest,Bien.ancienCode, Bien.DesigBien, CategorieBien.DesigCategorieBien, Bien.DateAcquisitionBien, Etat.DesigEtat, Bien.Prix ,Bien.Particularite from bien, Transferer, CategorieBien, Emplacement, SeTrouveB, Etat where Emplacement.idEmplaComplet = Transferer.idEmplaSource and Bien.IdBien = Transferer.idBien and CategorieBien.IdCategorieBien = Bien.IdCategorieBien and seTrouveB.IdBien = Bien.idBien and seTrouveB.IdEtat = Etat.idEtat and SeTrouveB.uidInventaire = '" + idinventaire + "' and Transferer.idBonTransfert = " + dGVBonDeTransfert.Rows[dGVBonDeTransfert.CurrentCell.RowIndex].Cells["ColumnIdBonTransfert"].Value; dS = MaConnexion.ExecuteSelect(connectionString, requete3); foreach (DataRow row in dS.Tables[0].Rows) { object[] ligneBienTransféré = new object[] { row[0].ToString(), row[1].ToString(), row[2].ToString(), row[3].ToString(), row[4].ToString().Substring(0, 8), row[5].ToString(), row[6].ToString(), row[7].ToString(), row[8].ToString(), row[9].ToString() }; dGVBiens.Rows.Add(ligneBienTransféré); if (row[10].ToString().Equals("True")) dGVBiens.Rows[dGVBiens.Rows.Count - 2].DefaultCellStyle.BackColor = Color.Green; else dGVBiens.Rows[dGVBiens.Rows.Count - 2].DefaultCellStyle.BackColor = Color.Red; } requete = "drop view vueBonDeTransfert"; MaConnexion.ExecuteUpdate(connectionString, requete); } catch (Exception) { } } private void buttonQuitter_Click(object sender, EventArgs e) { this.Close(); } } }
using System; using System.Collections; using System.Collections.Generic; using Unity.Collections; using UnityEngine; using UnityEngine.Events; using UnityEngine.Jobs; public class BulletJobSystemFacadeMono : MonoBehaviour, IBulletJobSystemFacade { public uint m_numberOfBullets; public BulletsPoolMovingComputeJobWrapper m_jobPositioning; public NABulletsDataRef m_bulletsInfoInMemoryRef; public NABulletsTransformRef m_transformInMemoryRef; public JobCompute_MovingBulletsWrapper m_bulletsJobManager; public JobCompute_TransformBulletsWrapper m_transformJobManager; public NextBulletAvailableSeeker m_bulletSeeker; JobComputeExe_MovingBullets m_bulletMovingExe; JobComputeExe_DefaultBulletsToTransform m_bulletTransformExe; public TriggeredBulletData m_bulletInit; public BulletDataResult m_bulletResult; public Transform m_linkedTransform; public BulletsRayCastingMono m_raycastManager; public BulletsToMeshColliderJobSystem m_bulletsToMesh; public JobBulletsFilteringMono m_jobBulletsFilter; public UnityEvent m_beforeComputingStart; public UnityEvent m_afterPositionComputing; public UnityEvent m_afterTransformComputing; private bool m_isInit; private void Awake() { m_bulletsInfoInMemoryRef = new NABulletsDataRef(m_numberOfBullets); m_transformInMemoryRef = new NABulletsTransformRef(m_numberOfBullets); m_bulletsInfoInMemoryRef.GetNativeArrayBulletData(out NativeArray<TriggeredBulletData> bullets); m_bulletsInfoInMemoryRef.GetNativeArrayBulletData(out NativeArray<BulletDataResult> bulletsResult); m_bulletMovingExe = new JobComputeExe_MovingBullets(); m_bulletTransformExe = new JobComputeExe_DefaultBulletsToTransform(); m_bulletsToMesh.SetBulletsMemory(bulletsResult); m_bulletMovingExe.SetSharedMemory(bullets, bulletsResult); m_bulletTransformExe.SetSharedMemory(bulletsResult); m_jobBulletsFilter.SetBulletsNativeArray(bulletsResult); m_bulletsJobManager = new JobCompute_MovingBulletsWrapper(m_bulletMovingExe); m_transformJobManager = new JobCompute_TransformBulletsWrapper(m_bulletTransformExe); m_bulletSeeker = new NextBulletAvailableSeeker(); m_bulletSeeker.SetMemoryArrayUsed(bullets); m_bulletsJobManager.SetSharedMemory(bullets); m_bulletsJobManager.SetSharedMemory(bulletsResult); m_transformInMemoryRef.GetTransformAccesArray(out TransformAccessArray transformsMemory); m_transformJobManager.SetSharedMemory(transformsMemory); if(m_raycastManager) m_raycastManager.SetMemorySharing(bulletsResult); m_isInit = true; } public void GetInfoAboutBullet(IBulletIdTicket id, out TriggeredBulletData initValue, out BulletDataResult result, out Transform linkedTransform) { if (id != null && m_isInit) { id.GetId(out int idValue); m_bulletsInfoInMemoryRef.GetBullet(idValue, out initValue); m_bulletsInfoInMemoryRef.GetBulletResult(idValue, out result); //m_transformInMemoryRef.GetTransfromAt(idValue, out linkedTransform); linkedTransform = null; } else { initValue = new TriggeredBulletData(); result = new BulletDataResult(); linkedTransform = null; } } public void SpawnBullet(Vector3 position, Vector3 directionSpeed, Transform proposedView, out IBulletIdTicket ticket) { float gameTime = Time.time; m_bulletSeeker.GetNextAvailableBulletId(out ticket); ticket.GetId(out int id); m_bulletsInfoInMemoryRef.SetBullet(id, new TriggeredBulletData() { m_isActive = true, m_gameTimeWhenTriggerInSeconds = gameTime, m_bulletInfo = new BulletDataInitValue() { m_startPoint = position, m_directionSpeed= directionSpeed } } ); m_transformInMemoryRef.SetTransform(id, proposedView); } internal void ForceSetBullet(int id, Vector3 position, Vector3 directionSpeed, Transform proposedView) { float gameTime = Time.time; m_bulletsInfoInMemoryRef.SetBullet(id, new TriggeredBulletData() { m_isActive = true, m_gameTimeWhenTriggerInSeconds = gameTime, m_bulletInfo = new BulletDataInitValue() { m_startPoint = position, m_directionSpeed = directionSpeed } } ); m_transformInMemoryRef.SetTransform(id, proposedView); } public void Update() { m_beforeComputingStart.Invoke(); m_bulletsJobManager.ComputeBulletNewPositions(Time.time); m_afterPositionComputing.Invoke(); m_transformJobManager.StartComputingTransformPosition(); } public void LateUpdate() { m_transformJobManager.ApplyTransformPosition(); m_afterTransformComputing.Invoke(); m_bulletsInfoInMemoryRef.GetBullet(0, out m_bulletInit); m_bulletsInfoInMemoryRef.GetBulletResult(0, out m_bulletResult); m_transformInMemoryRef.GetTransfromAt(0, out m_linkedTransform); } } public interface IBulletJobSystemFacade { void SpawnBullet(Vector3 position, Vector3 directionSpeed, Transform proposedView, out IBulletIdTicket ticket); } public class NextBulletAvailableSeeker { public int m_cyclingIndex; public uint m_bulletsCount; public NativeArray<TriggeredBulletData> m_bullets; public void SetMemoryArrayUsed(NativeArray<TriggeredBulletData> array) { m_bullets = array; m_bulletsCount = (uint) array.Length; } public void GetNextAvailableBulletId(out IBulletIdTicket bulletId) { bulletId = null; int antiLoop = 0; while (antiLoop < m_bulletsCount) { if (!m_bullets[m_cyclingIndex].m_isActive) { bulletId = new BulletTicketId(m_cyclingIndex); m_cyclingIndex++; return; } else { m_cyclingIndex++; } antiLoop++; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; namespace Tivo.Hmo { internal class UnknownTivoItem : TivoItem { internal UnknownTivoItem(XElement element) : base(element) { } } }
namespace ETLBox.Connection { /// <summary> /// The generic defintion of a connection string /// </summary> public interface IDbConnectionString { /// <summary> /// The connection string value, e.g. "Server=localhost;Database=etlbox;" /// </summary> string Value { get; set; } /// <summary> /// Returns the connection string <see cref="Value"/> /// </summary> /// <returns>The new connection string</returns> string ToString(); /// <summary> /// Creates a copy of the current connection /// </summary> /// <returns></returns> IDbConnectionString Clone(); /// <summary> /// The database name /// </summary> string DbName { get; set; } /// <summary> /// The name of the master database (if applicable) /// </summary> string MasterDbName { get; } /// <summary> /// Clone the current connection string with a new database name /// </summary> /// <param name="value">The new database name</param> /// <returns>The new connection string</returns> IDbConnectionString CloneWithNewDbName(string value = null); /// <summary> /// Clone the current connection string with the master database /// </summary> /// <returns>The new connection string</returns> IDbConnectionString CloneWithMasterDbName(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class BuildingSetter : MonoBehaviour { MeshRenderer meshRenderer; Material[] materials; Material material; public static BuildingSetter instance; public float health, maxHealth, faction, type, production, resources; public bool isDead = false; public bool isBuilding = true; public Image healthBar; TargetController Target; // Start is called before the first frame update void Start() { //materials = meshRenderer.materials; //material = this.meshRenderer.material; meshRenderer = this.GetComponent<MeshRenderer>(); faction = Random.Range(0, 2); type = Random.Range(0, 2); SetTeam(); SetType(); } void SetType() //Sets the units to a random unit type { if (type == 0) { this.ChangeMesh(gameObject, PrimitiveHelper.GetPrimitiveMesh(PrimitiveType.Cube)); this.name = "Factory"; this.production = 50; this.maxHealth = 200; this.health = 200; MaterialSet(); } else if (type == 1) { this.name = "Resouce Building"; this.resources = 1000; this.maxHealth = 100; this.health = 100; MaterialSet(); } else { this.ChangeMesh(gameObject, PrimitiveHelper.GetPrimitiveMesh(PrimitiveType.Cube)); this.name = "Factory"; this.production = 50; this.maxHealth = 200; this.health = 200; MaterialSet(); } } void SetTeam()//then sets the unit to a team, however in the previous method, if their name is Wizard they get set to the team wizards automatically { if (faction == 0) { this.tag = "Team 1"; meshRenderer.material.SetColor("_Color", Color.green); } else if (faction == 1) { this.tag = "Team 2"; //materials[1].color = Color.red; meshRenderer.material.SetColor("_Color", Color.red); } } void Death() { if (resources == 0) { Destroy(this.gameObject); } if (isDead == true) { Destroy(this.gameObject); } } private void Awake() { if (instance == null) { instance = this; } } // Update is called once per frame void Update() { HealthBarCheck(); Death(); } IEnumerator MaterialSet() { Material[] materials = meshRenderer.materials; materials[1] = material; //materials[1].color = Color.white; meshRenderer.materials = materials; Debug.Log("Name: " + meshRenderer.materials[1].name); yield return new WaitForSeconds(0.1f); meshRenderer.materials = materials; } private void ChangeMesh(GameObject pObject, Mesh pMesh) { if (pMesh == null) return; Mesh meshInstance = Instantiate(pMesh) as Mesh; pObject.GetComponent<MeshFilter>().mesh = meshInstance; } private void HealthBarCheck() { healthBar.fillAmount = health / maxHealth; //Debug.Log(this.ToString() + " \nHealthScale:" + health / maxHealth); Debugging the health checks } }
using Hybrid.Data; using Hybrid.Extensions; using Hybrid.Swagger.Helpers; using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; using System; using System.IO; namespace Hybrid.Swagger { /// <summary> /// Swagger 自定义功能 /// </summary> [ApiExplorerSettings(IgnoreApi = true), Route("api/[controller]/[action]"), ApiController] //[Route("api/[controller]/[action]"), ApiController] public class SwaggerController : ControllerBase { //private readonly IHostingEnvironment _hostingEnvironment; private readonly SpireDocHelper _spireDocHelper; private readonly SwaggerGenerator _swaggerGenerator; // private readonly SwaggerCustomOptions _swaggerCustomOptions; // /// <summary> /// /// </summary> /// <param name="hostingEnvironment"></param> /// <param name="spireDocHelper"></param> /// <param name="swaggerGenerator"></param> public SwaggerController(SpireDocHelper spireDocHelper, //IHostingEnvironment hostingEnvironment, SwaggerGenerator swaggerGenerator, SwaggerCustomOptions swaggerCustomOptions) { //_hostingEnvironment = hostingEnvironment; _spireDocHelper = spireDocHelper; _swaggerGenerator = swaggerGenerator; //从ioc容器中获取swagger生成文档的对象 _swaggerCustomOptions = swaggerCustomOptions; } //private readonly IServiceProvider _serviceProvider; ///// <inheritdoc /> //public SwaggerController(IServiceProvider serviceProvider) //{ // _serviceProvider = serviceProvider; //} ///// <summary> ///// ///// </summary> //protected IHostingEnvironment HostingEnvironment => _serviceProvider.GetService<IHostingEnvironment>(); ///// <summary> ///// ///// </summary> //protected SpireDocHelper SpireDocHelper => _serviceProvider.GetService<SpireDocHelper>(); ///// <summary> ///// ///// </summary> //protected SwaggerGenerator SwaggerGenerator => _serviceProvider.GetService<SwaggerGenerator>(); ///// <summary> ///// ///// </summary> //protected SwaggerCustomOptions swaggerCustomOptions => _serviceProvider.GetService<SwaggerCustomOptions>(); /// <summary> /// Swagger 文档导出 /// </summary> /// <param name="docType">1-.docx 2-.pdf 3-.html 4-.xml 5-.svg 6-.md</param> /// <param name="version">导出版本</param> /// <returns></returns> [HttpGet] public FileResult ExportApiWord(DocTypes docType = DocTypes.Html, string version = "v1") { if (!_swaggerCustomOptions.UseExportDoc) { throw new Exception("This function has not been turned on yet!"); } //获取swagger json 之前通过swagger的接口获取,废弃了。原因:他返回的数据看着像json数据,实则不是,不能用newtonsoft反序列化成对象。 //var url = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}/swagger/v2/swagger.json"; //var data = RestSharpHelper.HttpGet(url); //var model = JsonHelper.StrToModel<OpenApiDocument>(data); //1.获取api文档json,version是版本,根据指定版本获取指定版本的json对象。 SwaggerDocument model = _swaggerGenerator.GetSwagger(version); if (model == null) { throw new Exception("Swagger Json cannot be equal to null!"); } //2.这里使用了微软的mvc模板引擎技术来生成html,做过mvc项目的同学应该都知道是啥东西,这里不细说了。自己看代码吧,用起来很方便。 //string html = T4Helper.GenerateSwaggerHtml($"{_hostingEnvironment.WebRootPath}\\SwaggerDoc.cshtml", model); string html = T4Helper.GenerateSwaggerHtml(model); string suffix = docType.ToDescription(); //3.将html转换成需要导出的文件类型。 OperationResult<Stream> op = _spireDocHelper.SwaggerHtmlConvert(html, suffix, out string contentType); if (!op.Successed) { throw new Exception(op.Message); } return File(op.Data, contentType, $"{model.Info.Description}-{version}-{suffix}"); //返回文件流,type是文件格式 } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyBullet : MonoBehaviour { [HideInInspector] public Vector3 direction; [HideInInspector] public float speed; private void Update() { transform.position += (direction.normalized * speed * Time.deltaTime); } private void OnTriggerEnter2D(Collider2D other) { DestroySelf(); } private void OnCollisionEnter2D(Collision2D other) { DestroySelf(); } public void DestroySelf() { if(GetComponent<IsPooledObject>() != null) { gameObject.SetActive(false); } else { Destroy(gameObject); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Utilities.CustomException { /// <summary> /// Clase Excepcion para /// generar un error controlado /// cuando el formato del archivo no es soportado /// </summary> [Serializable] public class ExtencionNotSupportedException : Exception { public ExtencionNotSupportedException() { } public ExtencionNotSupportedException(string message) : base(message) { } public ExtencionNotSupportedException(string message, Exception innerException) : base(message, innerException) { } protected ExtencionNotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
using System; namespace Checkout.Payment.Identity.Domain.Models { public class MerchantApiKey { public string SubjectId { get; set; } public string Email { get; set; } public string UserName { get; set; } public string ApiKey { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Offline.Payment.Business.Models; using Offline.Payment.Business.Services; namespace Offline.Payment.API.Controllers { [Route("api/[controller]")] [ApiController] public class OrderController : ControllerBase { IUserTransactionService _userTransactionService; public OrderController(IUserTransactionService userTransactionService) { _userTransactionService = userTransactionService; } [HttpGet] public async Task<IEnumerable<UserTransaction>> Get(int userId) { return await _userTransactionService.GetAll(userId); } [HttpPost] [ProducesResponseType(200, Type = typeof(UserTransaction))] [ProducesResponseType(400)] public async Task<UserTransaction> Create([FromBody]UserTransaction userTransaction) { return await _userTransactionService.Create(userTransaction); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Data.Core; namespace LearningEnglishWeb.Areas.Training.Services.Helpers { public static class Api { public static class Training { //public static string GetRequiringStudyWords(string baseUrl, TrainingTypeEnum trainingType, bool isReverseTraining) //{ // return $"{baseUrl}/RequiringStudyWords?trainingType={trainingType}&isReverseTraining={isReverseTraining}"; //} internal static string GetAvailableTrainingWordsCount(string baseUrl) { return $"{baseUrl}/AvailableTrainingWordsCount"; } //internal static string GetTrainingWords(string baseUrl, IEnumerable<int> userSelectedWords) //{ // var parameters = userSelectedWords.Select(uw => $"userSelectedWords={uw}"); // return $"{baseUrl}/TrainingWords?" + String.Join('&', parameters); //} internal static string GetTrainingWordsRatio(string baseUrl, ICollection<int> userWordIs) { var urlBuilder = new StringBuilder($"{baseUrl}/TrainingWordsRatio"); if (userWordIs.Any()) { var parameters = string.Join('&', userWordIs.Select(uw => $"userWordIds={uw}")); urlBuilder.Append('?'); urlBuilder.Append(parameters); } return urlBuilder.ToString(); } internal static string SaveTrainingResult(string baseUrl) { return baseUrl; } public static string GetTrainingQuestions(string baseUrl, TrainingTypeEnum trainingType, bool isReverseTraining, IEnumerable<int> selectedUserWords) { var url = $"{baseUrl}/TrainingQuestion?trainingType={trainingType}&isReverseTraining={isReverseTraining}"; if (selectedUserWords != null && selectedUserWords.Any()) { var parameters = selectedUserWords.Select(uw => $"userSelectedWords={uw}"); url += $"&{string.Join('&', parameters)}"; } return url; } } } }
using System.Data.Entity.ModelConfiguration; using DDDStore.Domain.Entities; namespace DDDStore.Infra.Data.EntityConfig { public class CustomerConfiguration : EntityTypeConfiguration<Customer> { public CustomerConfiguration() { HasKey(c => c.CustomerId); Property(c => c.Title) .IsRequired(); Property(c => c.FirstName) .IsRequired(); Property(c => c.LastName) .IsRequired(); Property(c => c.Email) .IsRequired(); } } }
namespace ns11 { using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] internal struct Struct14 { private readonly Struct12[] struct12_0; private readonly int int_0; public Struct14(int numBitLevels) { this.int_0 = numBitLevels; this.struct12_0 = new Struct12[((int) 1) << numBitLevels]; } public void method_0() { for (uint i = 1; i < (((int) 1) << this.int_0); i++) { this.struct12_0[i].method_1(); } } public uint method_1(Class62 class62_0) { uint index = 1; for (int i = this.int_0; i > 0; i--) { index = (index << 1) + this.struct12_0[index].method_2(class62_0); } return (index - (((uint) 1) << this.int_0)); } public uint method_2(Class62 class62_0) { uint index = 1; uint num2 = 0; for (int i = 0; i < this.int_0; i++) { uint num4 = this.struct12_0[index].method_2(class62_0); index = index << 1; index += num4; num2 |= num4 << i; } return num2; } public static uint smethod_0(Struct12[] struct12_1, uint uint_0, Class62 class62_0, int int_1) { uint num = 1; uint num2 = 0; for (int i = 0; i < int_1; i++) { uint num4 = struct12_1[uint_0 + num].method_2(class62_0); num = num << 1; num += num4; num2 |= num4 << i; } return num2; } } }
using System.Collections; using System.Collections.Generic; using UnityAssets.Standard_Assets.CrossPlatformInput.Scripts; using UnityEngine; namespace Game.Player.Controller { public class Spacecontrol : MonoBehaviour { public float MoveForce = 5, brakeforcemlp = -5; Rigidbody2D myBody; void Start() { myBody = this.GetComponent<Rigidbody2D>(); } void FixedUpdate() { Vector3 moveVec = new Vector3((CrossPlatformInputManager.GetAxis("Horizontal") * MoveForce * 10), (CrossPlatformInputManager.GetAxis("Vertical")) * MoveForce * 10); myBody.AddForce(moveVec); } } }
using BattleUtil; [System.Serializable] public class EntityStat { public string name; public int curHP; public int baseHP; public int curSP; public int baseSP; public BattleEffect.StatusEffect statStatus; public EntityStat() { name = "Error"; curHP = 0; baseHP = 0; curSP = 0; baseSP = 0; statStatus = BattleEffect.StatusEffect.None; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using WebApp1.Pages; using Microsoft.EntityFrameworkCore; using System.ComponentModel.DataAnnotations; using WebApp1.Model; namespace WebApp1.Model { public class Subastas { [Key] public int IdSubastas { get; set;} [Required (ErrorMessage = "El Campo para el Nombre es obligatorio")][MaxLength(100)] [Display( Name= "Nombre del Usuario")] public string NombreUsuario { get; set;} [Required (ErrorMessage = "El Campo para el apellido es obligatorio")][MaxLength(100)] [Display( Name= "Apellido del Usuario")] public string ApellidoUsuario { get; set;} [Required (ErrorMessage = "Campo obligatorio")][MaxLength(40)] [Display( Name= "Nombre del articulo a subastar")] public string NombreArticulo { get; set;} [Required (ErrorMessage = "Campo obligatorio")][MaxLength(250)] [Display( Name= "Descripción del articulo a subastar")] public string DescripcionArticulo { get; set;} [RegularExpression (@"^La categoria del articulo es oblogatoria")] [Required (ErrorMessage = "La categoria del articulo es oblogatoria")] [Display( Name= "Categoria del articulo")] public string Categoria { get; set;} [RegularExpression (@"^El precio del articulo es oblogatorio")] [Required(ErrorMessage = "El precio del articulo es oblogatorio")] [Display( Name= "Precio Incial del articulo")] [Range(1, 1000000000)] public int Precio { get; set;} [Required (ErrorMessage = "Campo obligatorio")] [Display( Name= "Fecha de inicio de la subasta")] [DataType(DataType.Date)] public DateTime FechaSubasta {get;set;} [Required (ErrorMessage = "Campo obligatorio")] [Display( Name= "Fecha de finalizacion de la subasta")] [DataType(DataType.Date)] public DateTime FechaFinSubasta {get;set;} [Display( Name= "Oferta")] public int Oferta {get;set;} } }
using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace IdentityServerAspNetIdentity { public class OnlineUserAuthorizationFilter : Attribute, IAsyncAuthorizationFilter { public Task OnAuthorizationAsync(AuthorizationFilterContext context) { var HttpContext = context.HttpContext; return Task.CompletedTask; } } }
using System.ComponentModel.DataAnnotations.Schema; using PagedList; namespace LeaveRequestApp.Models { [NotMapped] public class PagedModel<TModel> where TModel : class { public PagedListMetaData MetaData { get; set; } public IPagedList<TModel> Data { get; set; } public int Total { get; set; } } }
using JKMServices.DTO; using System.Collections.Generic; namespace JKMServices.DAL.CRM.common { public interface ICRMUtilities { Dictionary<string, string> ExecuteDeleteRequest(string entityName, string jsonFormattedData); Dictionary<string, string> ExecuteGetRequest(string entityName, string retriveFieldList, string filterString, string orderBy = "", string orderingType = "", string expandValue = ""); Dictionary<string, string> ExecutePostRequest(string entityName, string jsonFormattedData); Dictionary<string, string> ExecutePutRequest(string entityName, string strGuID, string jsonFormattedData); bool IsValidResponse(Dictionary<string, string> response); bool ContainsNullValue(Dictionary<string, string> response); ServiceResponse<T> GetFormattedResponseToDTO<T>(Dictionary<string, string> crmResponse); string GetSpecificAttributeFromResponse(Dictionary<string, string> crmResponse, string requiredField); } }
namespace Frontend.Core.Converting.Operations { public enum AggregateOperationsResult { NotStarted, InProgress, Canceled, CompletedSuccessfully, CompletedWithWarnings, Failed } }
using OpenQA.Selenium; using System; namespace SeleniumSample.Helpers { sealed class SeleniumHelpers { /// <summary> /// An expectation for checking that an element is present on the DOM of a /// page. This does not necessarily mean that the element is visible. /// </summary> /// <param name="locator">The locator used to find the element.</param> /// <returns>The <see cref="IWebElement"/> once it is located.</returns> public static Func<IWebDriver, IWebElement> ElementExists(By locator) { return (driver) => { try { return driver.FindElement(locator); } catch (NoSuchElementException) { return null; } }; } } }
namespace SiscomSoft.Migrations { using System; using System.Data.Entity.Migrations; public partial class INICIAL : DbMigration { public override void Up() { CreateTable( "dbo.Almacenes", c => new { idAlmacen = c.Int(nullable: false, identity: true), sFolio = c.String(unicode: false), cliente_id = c.Int(nullable: false), sNumFactura = c.String(unicode: false), sMoneda = c.String(unicode: false), sDescripcion = c.String(unicode: false), dTipoCambio = c.Decimal(nullable: false, precision: 18, scale: 2), sTipoCompra = c.String(unicode: false), dtFechaCompra = c.DateTime(nullable: false, precision: 0), dtFechaMovimiento = c.DateTime(nullable: false, precision: 0), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idAlmacen); CreateTable( "dbo.Capas", c => new { idCapa = c.Int(nullable: false, identity: true), almacen_id = c.Int(nullable: false), producto_id = c.Int(nullable: false), dtFecha = c.DateTime(nullable: false, precision: 0), dTipoCambio = c.Decimal(nullable: false, precision: 18, scale: 2), iNumeroLote = c.Int(nullable: false), dCantidad = c.Decimal(nullable: false, precision: 18, scale: 2), dCosto = c.Decimal(nullable: false, precision: 18, scale: 2), dtFechaCaducidad = c.DateTime(nullable: false, precision: 0), dtFechaFabricacion = c.DateTime(nullable: false, precision: 0), }) .PrimaryKey(t => t.idCapa); CreateTable( "dbo.Catalogos", c => new { idCatalogo = c.Int(nullable: false, identity: true), sUDM = c.String(unicode: false), sAbreviacion = c.String(unicode: false), iValor = c.Int(nullable: false), sClaveUnidad = c.String(unicode: false), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idCatalogo); CreateTable( "dbo.Categorias", c => new { idCategoria = c.Int(nullable: false, identity: true), sNomCat = c.String(unicode: false), sNomSubCat = c.String(unicode: false), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idCategoria); CreateTable( "dbo.Certificados", c => new { idCertificado = c.Int(nullable: false, identity: true), sArchCer = c.String(unicode: false), sArchkey = c.String(unicode: false), sContrasena = c.String(unicode: false), sNoCertifi = c.String(unicode: false), sValidoDe = c.String(unicode: false), sValidoHasta = c.String(unicode: false), sRutaArch = c.String(unicode: false), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idCertificado); CreateTable( "dbo.Clientes", c => new { idCliente = c.Int(nullable: false, identity: true), sRfc = c.String(unicode: false), sRazonSocial = c.String(unicode: false), iPersona = c.Int(nullable: false), sCurp = c.String(unicode: false), sNombre = c.String(unicode: false), sPais = c.String(unicode: false), iCodPostal = c.Int(nullable: false), sEstado = c.String(unicode: false), sMunicipio = c.String(unicode: false), sLocalidad = c.String(unicode: false), sColonia = c.String(unicode: false), sCalle = c.String(unicode: false), iNumExterior = c.Int(nullable: false), iNumInterior = c.Int(nullable: false), sTelFijo = c.String(unicode: false), sTelMovil = c.String(unicode: false), sCorreo = c.String(unicode: false), sReferencia = c.String(unicode: false), sTipoPago = c.String(unicode: false), sNumCuenta = c.String(unicode: false), sConPago = c.String(unicode: false), iTipoCliente = c.Int(nullable: false), iStatus = c.Int(nullable: false), sLogo = c.String(unicode: false), }) .PrimaryKey(t => t.idCliente); CreateTable( "dbo.Descuentos", c => new { idDescuento = c.Int(nullable: false, identity: true), dTasaDesc = c.Decimal(nullable: false, precision: 18, scale: 2), dTasaDescEx = c.Decimal(nullable: false, precision: 18, scale: 2), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idDescuento); CreateTable( "dbo.DescuentosProducto", c => new { idDescuentoProducto = c.Int(nullable: false, identity: true), descuento_id = c.Int(nullable: false), producto_id = c.Int(nullable: false), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idDescuentoProducto); CreateTable( "dbo.DetalleAlmacenes", c => new { idDetalle = c.Int(nullable: false, identity: true), sDescripcion = c.String(unicode: false), almacen_id = c.Int(nullable: false), producto_id = c.Int(nullable: false), iCantidad = c.Int(nullable: false), dCosto = c.Decimal(nullable: false, precision: 18, scale: 2), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idDetalle); CreateTable( "dbo.DetalleFacturas", c => new { idDetalleFactura = c.Int(nullable: false, identity: true), factura_id = c.Int(nullable: false), producto_id = c.Int(nullable: false), sClave = c.String(unicode: false), sDescripcion = c.String(unicode: false), iCantidad = c.Int(nullable: false), dPreUnitario = c.Decimal(nullable: false, precision: 18, scale: 2), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idDetalleFactura); CreateTable( "dbo.DetalleInventarios", c => new { pkDetalleInventario = c.Int(nullable: false, identity: true), inventario_id = c.Int(nullable: false), producto_id = c.Int(nullable: false), dCantidad = c.Decimal(nullable: false, precision: 18, scale: 2), dLastCosto = c.Decimal(nullable: false, precision: 18, scale: 2), dPreVenta = c.Decimal(nullable: false, precision: 18, scale: 2), }) .PrimaryKey(t => t.pkDetalleInventario); CreateTable( "dbo.DetallePeriodos", c => new { idDetallePeriodo = c.Int(nullable: false, identity: true), periodo_id = c.Int(nullable: false), venta_id = c.Int(nullable: false), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idDetallePeriodo); CreateTable( "dbo.DetalleVentas", c => new { idDetalleVenta = c.Int(nullable: false, identity: true), venta_id = c.Int(nullable: false), producto_id = c.Int(nullable: false), sDescripcion = c.String(unicode: false), dCantidad = c.Decimal(nullable: false, precision: 18, scale: 2), dPreUnitario = c.Decimal(nullable: false, precision: 18, scale: 2), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idDetalleVenta); CreateTable( "dbo.Empresas", c => new { idEmpresa = c.Int(nullable: false, identity: true), sRazonSocial = c.String(unicode: false), sNomComercial = c.String(unicode: false), sNomContacto = c.String(unicode: false), sRegFiscal = c.String(unicode: false), sTelefono = c.String(unicode: false), sCorreo = c.String(unicode: false), sPais = c.String(unicode: false), sEstado = c.String(unicode: false), sMunicipio = c.String(unicode: false), sColonia = c.String(unicode: false), sLocalidad = c.String(unicode: false), sCalle = c.String(unicode: false), iNumExterior = c.Int(nullable: false), iNumInterir = c.Int(nullable: false), iCodPostal = c.Int(nullable: false), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idEmpresa); CreateTable( "dbo.Existencias", c => new { idExistencia = c.Int(nullable: false, identity: true), almacen_id = c.Int(nullable: false), producto_id = c.Int(nullable: false), dCantidad = c.Decimal(nullable: false, precision: 18, scale: 2), dSalida = c.Decimal(nullable: false, precision: 18, scale: 2), dBaja = c.Decimal(nullable: false, precision: 18, scale: 2), dExistencia = c.Decimal(nullable: false, precision: 18, scale: 2), }) .PrimaryKey(t => t.idExistencia); CreateTable( "dbo.Facturas", c => new { idFactura = c.Int(nullable: false, identity: true), usuario_id = c.Int(nullable: false), sucursal_id = c.Int(nullable: false), cliente_id = c.Int(nullable: false), dtFecha = c.DateTime(nullable: false, precision: 0), sFolio = c.String(unicode: false), sTipoCambio = c.String(unicode: false), sMoneda = c.String(unicode: false), sUsoCfdi = c.String(unicode: false), sFormaPago = c.String(unicode: false), sMetodoPago = c.String(unicode: false), sTipoCompro = c.String(unicode: false), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idFactura); CreateTable( "dbo.Impuestos", c => new { idImpuesto = c.Int(nullable: false, identity: true), sTipoImpuesto = c.String(unicode: false), sImpuesto = c.String(unicode: false), dTasaImpuesto = c.Decimal(nullable: false, precision: 18, scale: 2), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idImpuesto); CreateTable( "dbo.ImpuestosProducto", c => new { idDetalleProducto = c.Int(nullable: false, identity: true), impuesto_id = c.Int(nullable: false), producto_id = c.Int(nullable: false), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idDetalleProducto); CreateTable( "dbo.Inventarios", c => new { idInventario = c.Int(nullable: false, identity: true), sFolio = c.String(unicode: false), dtFecha = c.DateTime(nullable: false, precision: 0), sTipoMov = c.String(unicode: false), bStatus = c.Boolean(nullable: false), usuario_id = c.Int(nullable: false), almacen_id = c.Int(nullable: false), }) .PrimaryKey(t => t.idInventario); CreateTable( "dbo.Periodos", c => new { idPeriodo = c.Int(nullable: false, identity: true), dtInicio = c.DateTime(nullable: false, precision: 0), dtFinal = c.DateTime(nullable: false, precision: 0), sFolio = c.String(unicode: false), iTurno = c.Int(nullable: false), sCaja = c.String(unicode: false), dFondo = c.Decimal(nullable: false, precision: 18, scale: 2), usuario_id = c.Int(nullable: false), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idPeriodo); CreateTable( "dbo.Permisos", c => new { idPermiso = c.Int(nullable: false, identity: true), sNombre = c.String(nullable: false, unicode: false), sComentario = c.String(nullable: false, unicode: false), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idPermiso); CreateTable( "dbo.PermisosNegadosRol", c => new { idPermisoNegadoRol = c.Int(nullable: false, identity: true), rol_id = c.Int(nullable: false), permiso_id = c.Int(nullable: false), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idPermisoNegadoRol); CreateTable( "dbo.Precios", c => new { idPrecios = c.Int(nullable: false, identity: true), sNombre = c.String(unicode: false), iPrePorcen = c.Int(nullable: false), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idPrecios); CreateTable( "dbo.Preferencias", c => new { idPreferencia = c.Int(nullable: false, identity: true), sLogotipo = c.String(unicode: false), bForImpreso = c.Boolean(nullable: false), sNumSerie = c.String(unicode: false), bEnvFactura = c.Boolean(nullable: false), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idPreferencia); CreateTable( "dbo.Productos", c => new { idProducto = c.Int(nullable: false, identity: true), sClaveProd = c.String(unicode: false), sDescripcion = c.String(unicode: false), sMarca = c.String(unicode: false), dCosto = c.Decimal(nullable: false, precision: 18, scale: 2), dPreVenta = c.Decimal(nullable: false, precision: 18, scale: 2), sFoto = c.String(unicode: false), bStatus = c.Boolean(nullable: false), categoria_id = c.Int(nullable: false), catalogo_id = c.Int(nullable: false), precio_id = c.Int(nullable: false), }) .PrimaryKey(t => t.idProducto); CreateTable( "dbo.Roles", c => new { idRol = c.Int(nullable: false, identity: true), sNombre = c.String(nullable: false, unicode: false), sComentario = c.String(nullable: false, unicode: false), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idRol); CreateTable( "dbo.Sucursales", c => new { idSucursal = c.Int(nullable: false, identity: true), sNombre = c.String(unicode: false), iStatus = c.Int(nullable: false), sNoCertifi = c.String(unicode: false), sPais = c.String(unicode: false), sEstado = c.String(unicode: false), sMunicipio = c.String(unicode: false), sColonia = c.String(unicode: false), sLocalidad = c.String(unicode: false), sCalle = c.String(unicode: false), iNumExterior = c.Int(nullable: false), iNumInterior = c.Int(nullable: false), iCodPostal = c.Int(nullable: false), sMoneda = c.String(unicode: false), sTipoCambio = c.String(unicode: false), empresa_id = c.Int(nullable: false), preferencia_id = c.Int(nullable: false), certificado_id = c.Int(nullable: false), }) .PrimaryKey(t => t.idSucursal); CreateTable( "dbo.Usuarios", c => new { idUsuario = c.Int(nullable: false, identity: true), sRfc = c.String(unicode: false), sUsuario = c.String(nullable: false, unicode: false), sNombre = c.String(nullable: false, unicode: false), sContrasena = c.String(nullable: false, unicode: false), sPin = c.String(nullable: false, unicode: false), sNumero = c.String(nullable: false, unicode: false), sCorreo = c.String(nullable: false, unicode: false), sComentario = c.String(nullable: false, unicode: false), rol_id = c.Int(nullable: false), sucursal_id = c.Int(nullable: false), bStatus = c.Boolean(nullable: false), }) .PrimaryKey(t => t.idUsuario); CreateTable( "dbo.Ventas", c => new { idVenta = c.Int(nullable: false, identity: true), dtFechaVenta = c.DateTime(nullable: false, precision: 0), dCambio = c.Decimal(nullable: false, precision: 18, scale: 2), sTipoPago = c.String(unicode: false), sMoneda = c.String(unicode: false), bStatus = c.Boolean(nullable: false), iTurno = c.Int(nullable: false), iCaja = c.Int(nullable: false), sFolio = c.String(unicode: false), cliente_id = c.Int(nullable: false), factura_id = c.Int(nullable: false), usuario_id = c.Int(nullable: false), }) .PrimaryKey(t => t.idVenta); } public override void Down() { DropTable("dbo.Ventas"); DropTable("dbo.Usuarios"); DropTable("dbo.Sucursales"); DropTable("dbo.Roles"); DropTable("dbo.Productos"); DropTable("dbo.Preferencias"); DropTable("dbo.Precios"); DropTable("dbo.PermisosNegadosRol"); DropTable("dbo.Permisos"); DropTable("dbo.Periodos"); DropTable("dbo.Inventarios"); DropTable("dbo.ImpuestosProducto"); DropTable("dbo.Impuestos"); DropTable("dbo.Facturas"); DropTable("dbo.Existencias"); DropTable("dbo.Empresas"); DropTable("dbo.DetalleVentas"); DropTable("dbo.DetallePeriodos"); DropTable("dbo.DetalleInventarios"); DropTable("dbo.DetalleFacturas"); DropTable("dbo.DetalleAlmacenes"); DropTable("dbo.DescuentosProducto"); DropTable("dbo.Descuentos"); DropTable("dbo.Clientes"); DropTable("dbo.Certificados"); DropTable("dbo.Categorias"); DropTable("dbo.Catalogos"); DropTable("dbo.Capas"); DropTable("dbo.Almacenes"); } } }
using KRF.Core.Entities.Actors; namespace KRF.Core.FunctionalContracts { public interface ILogin { /// <summary> /// Functionality is to validate the supplied username and password against the database records. /// </summary> /// <param name="username">Supplied username</param> /// <param name="password">Supplied password</param> /// <returns>True - If success, False - If failure</returns> bool AuthenticateUser(string username, string password); /// <summary> /// Get User detail /// </summary> /// <param name="username"></param> /// <returns></returns> User GetUserDetail(string username); /// <summary> /// Fucntionality is to kickstart the Forgot Password logic (Sending emails to user's email id) /// </summary> /// <param name="code">Supplied code</param> /// <returns>True - if success, False - if failure.</returns> bool ForgotPassword(string email, string code); /// <summary> /// Check if code is valid /// </summary> /// <param name="code"></param> /// <returns></returns> bool IsCodeValid(string code); /// <summary> /// Reset user's password /// </summary> /// <param name="key">User's key.</param> /// <param name="newPassword">New password</param> /// <returns>True - if success, False - if failure.</returns> bool ResetPassword(string key, string newPassword); } }
using UnityEngine; using System.Collections; public class Ball : MonoBehaviour { private Paddle paddle; private Vector3 paddleToBallVector; private bool hasStarted = false; // Use this for initialization void Start () { paddle = GameObject.FindObjectOfType<Paddle>(); paddleToBallVector = this.transform.position - paddle.transform.position; } // Update is called once per frame void Update () { if(!hasStarted){ //lock the ball relative to the paddle this.transform.position = paddle.transform.position + paddleToBallVector; //wait for a mouse press to launch if(Input.GetMouseButtonDown(0)){ print ("ball launched"); this.rigidbody2D.velocity = new Vector2(2f, 10f); hasStarted = true; } } } void OnCollisionEnter2D(Collision2D col){ //ball doesn't trigger sound when brick is destroyed if(hasStarted){ HandleVelocity(); } audio.Play(); print(rigidbody2D.velocity); } void HandleVelocity(){ Vector2 vtweak; if(rigidbody2D.velocity.x >= 0){ if(rigidbody2D.velocity.y >=0){ vtweak = new Vector2(Random.Range(0f, 0.1f), Random.Range(0f, 0.1f)); }else{ vtweak = new Vector2(Random.Range(0f, 0.1f), Random.Range(0f, 0.1f)); } }else{ if(rigidbody2D.velocity.y >=0){ vtweak = new Vector2(Random.Range(-0.1f, 0f), Random.Range(0f, 0.1f)); }else{ vtweak = new Vector2(Random.Range(-0.1f, 0f), Random.Range(0f, 0.1f)); } } Vector2 temp = rigidbody2D.velocity+vtweak; rigidbody2D.velocity = new Vector2(Mathf.Clamp(temp.x, -13f, 13f), Mathf.Clamp(temp.y, -13, 13)); } }
using System.Windows; using System.Windows.Controls; namespace FinalYearProject { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class LoginWindow : Page { public LoginWindow() { InitializeComponent(); } private void btnLogIn_Click(object sender, RoutedEventArgs e) { // Retrieve the users details UserDetails userDetails = SQLFunctions.RetrieveUserDetails(txtName.Text); // Check if patient or clinician if (userDetails.AccountType == true) // Clinician { this.NavigationService.Navigate(new ClinicianHomeWindow()); } else if (userDetails.AccountType == false) // Patient { // Pass in user details if patient this.NavigationService.Navigate(new PatientHomeWindow(userDetails)); } else { // User not found MessageBox.Show("User not found, please check your spelling and try again", "User Not Found"); } } private void btnExit_Click(object sender, RoutedEventArgs e) { // Close NavigationWindow upon exit (shutdown application) (this.Parent as NavigationWindow).Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SharePoint; using Microsoft.SharePoint.Utilities; namespace SP2010.Manage.FileTypes { public sealed class DownloadManager { private static volatile DownloadManager instance; private static object syncRoot = new Object(); List<DownloadType> downloadTypes = new List<DownloadType>(); public List<DownloadType> DownloadTypes { get { return downloadTypes; } } private DownloadManager() { GetDownloadTypes(); } public static DownloadManager Instance { get { if (instance == null) { lock (syncRoot) { if (instance == null) instance = new DownloadManager(); } } return instance; } } public void RefreshCashe() { instance = new DownloadManager(); } public DownloadType Find(string extension) { return DownloadTypes.Find(a => String.Equals(a.Extension, extension, StringComparison.OrdinalIgnoreCase) && a.Active == true); } public ExtState Add(DownloadType type) { ExtState state = ExtState.Failed; if (!downloadTypes.Contains(type, new DownloadTypeEqualComparer())) { downloadTypes.Add(type); state = Save(downloadTypes); } else state = ExtState.IsExists; return state; } public ExtState Save(List<DownloadType> types) { ExtState state = ExtState.Failed; if (types == null) return state; Helper.RunElevated(SPContext.Current.Site.ID, SPContext.Current.Site.RootWeb.ID, delegate(SPWeb elevatedWeb) { string fileTypes = string.Empty; string fileSizes = string.Empty; string actives = string.Empty; foreach (DownloadType type in types) { fileTypes += type.Extension + ";"; fileSizes += type.Size + ";"; actives += type.Active + ";"; } elevatedWeb.AllowUnsafeUpdates = true; elevatedWeb.Properties[Content.SPFileTypes] = fileTypes; elevatedWeb.Properties[Content.SPFileSizes] = fileSizes; elevatedWeb.Properties[Content.SPFileTypesActive] = actives; elevatedWeb.Properties.Update(); elevatedWeb.AllowUnsafeUpdates = false; state = ExtState.Success; }); return state; } private void GetDownloadTypes() { List<DownloadType> types = new List<DownloadType>(); Helper.RunElevated(SPContext.Current.Site.ID, SPContext.Current.Site.RootWeb.ID, delegate(SPWeb elevatedWeb) { string[] fileTypes = elevatedWeb.Properties[Content.SPFileTypes].ToLower().Split(';'); string[] fileSizes = elevatedWeb.Properties[Content.SPFileSizes].ToLower().Split(';'); string[] actives = elevatedWeb.Properties[Content.SPFileTypesActive].ToLower().Split(';'); if (fileSizes != null && fileTypes != null) if (fileTypes.Length == fileSizes.Length) for (int i = 0; i < fileTypes.Length - 1; i++) { DownloadType file = new DownloadType(fileTypes[i], Convert.ToInt32(fileSizes[i]), Convert.ToBoolean(actives[i])); if (!types.Contains(file, new DownloadTypeEqualComparer())) types.Add(file); } }); if (types.Count > 0) { downloadTypes.Clear(); downloadTypes.AddRange(types); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace TestHelper { public class ProcessQuestions { public static StringBuilder OutPut = new StringBuilder(); private static object mutrix = new object(); private static int critical = 1; // Critical resource private static Semaphore sk = new Semaphore(3, 3); private static void P() { lock (mutrix) { critical -= 1; if (critical < 0) { Waiting(); } else { // TODO: Continue. } } } private static void V() { lock (mutrix) { critical += 1; if (critical <= 0) // there is other process is waiting. { Wake(); } else { // TODO: Continue. } } } private static void Waiting() { // TODO: Thread waiting. OutPut.AppendFormat("thread id:{0} waiting..."); } private static void Wake() { // TODO: Thread wake. OutPut.AppendFormat("Thread id:{0} is wake..."); } public static void Start() { } } public class SortClass { private static void Print(int[] a) { a.ToList().ForEach(p => System.Console.Write(string.Format("{0} ", p.ToString()))); System.Console.WriteLine(); } #region 冒泡排序 public static int[] BubbleSort(int[] a) { System.Console.WriteLine("Before sort:"); Print(a); int f; int c = a.Count(); for (int i = 1; i < c; i++) // 选出第i大数放到倒数第i位 { for (int j = 0; j < c - i; j++) // 选出第i大数需要比较次数 { if (a[j] > a[j + 1]) { f = a[j]; a[j] = a[j + 1]; a[j + 1] = f; } } } System.Console.WriteLine("After sort:"); Print(a); return a; } public static int[] BubbleSort1(int[] a) { System.Console.WriteLine("Before sort:"); Print(a); int f; int c = a.Count(); for (int i = 0; i < c - 1; i++) // 选出第i大数放到倒数第i位 { for (int j = i + 1; j < c; j++) // 选出第i大数需要比较次数 { if (a[i] < a[j]) { f = a[j]; a[i] = a[j]; a[j] = f; } } } System.Console.WriteLine("After sort:"); Print(a); return a; } #endregion #region 插入排序 public static int[] InsertSort(int[] a) { System.Console.WriteLine("Before sort:"); Print(a); int f; int c = a.Count(); for (int i = 1; i < c; i++) // 把第N个数插入到有序数组中 { int j = 0; for (; j < i && a[i] > a[j]; j++) ; // 找需要移动的位置j f = a[i]; // [j,i)的数往后移动一位 for (int ss = i; ss > j; ss--) { a[ss] = a[ss - 1]; } a[j] = f; //把第N个数插入到j位置 } System.Console.WriteLine("After sort:"); Print(a); return a; } #endregion #region 选择排序 public static int[] SelectSort(int[] a) { System.Console.WriteLine("Before sort:"); Print(a); int f; int c = a.Count(); int min = -1; // 选择第i+1小的数放在第i+1位 for (int i = 0; i < c; i++) { min = -1; // 找到一趟遍历的最小数的位置 f = a[i]; // 找到最小值所在位置 for (int j = i + 1; j < c; j++) { if (a[j] < f) { f = a[j]; min = j; } } // 交换最小值和第i个的位置 if (min != -1) { a[min] = a[i]; a[i] = f; } } System.Console.WriteLine("After sort:"); Print(a); return a; } #endregion #region 堆排序 public static int[] HeapSort(int[] a) { System.Console.WriteLine("Before sort:"); Print(a); int f; int c = a.Count(); for (int i = c - 1; i >= 0; i--) { if (2 * i + 1 < c) { int minChildrenIndex = 2 * i + 1; if (2 * i + 2 < c) { if (a[2 * i + 1] > a[2 * i + 2]) minChildrenIndex = 2 * i + 2; } if (a[i] > a[minChildrenIndex]) { ExchageValue(ref a[i], ref a[minChildrenIndex]); NodeSort(ref a, minChildrenIndex); } } } System.Console.WriteLine("After sort:"); Print(a); return a; } private static void NodeSort(ref int[] dblArray, int StartIndex) { while (2 * StartIndex + 1 < dblArray.Length) { int MinChildrenIndex = 2 * StartIndex + 1; if (2 * StartIndex + 2 < dblArray.Length) { if (dblArray[2 * StartIndex + 1] > dblArray[2 * StartIndex + 2]) { MinChildrenIndex = 2 * StartIndex + 2; } } if (dblArray[StartIndex] > dblArray[MinChildrenIndex]) { ExchageValue(ref dblArray[StartIndex], ref dblArray[MinChildrenIndex]); StartIndex = MinChildrenIndex; } } } private static void ExchageValue(ref int A, ref int B) { int Temp = A; A = B; B = Temp; } #endregion } public class Others { // 判断a是不是连续的,如1,2,3,4,5或者1,4,3,2,5 public static bool ContinuousinInteger(int[] a) { bool result = false; int len = 0; if (a != null) { len = a.Count(); if (len > 0) { if (len == 1) { result = true; } else { // sort a SortClass.BubbleSort(a); bool flag = false; for (int i = 1; i < len; i++) { if (Math.Abs(a[i] - a[i - 1]) != 1) { flag = true; break; } } if (!flag) { result = true; } } } } return result; } } /* * ssysname 列为null所占比例 create database test go use test go create table Test1 ( ssysid int identity(1,1) not null, ssysname varchar(10) null, constraint pk_test1 primary key(ssysid) ) go insert into Test1(ssysname) values('ttt') insert into Test1(ssysname) values(null) insert into Test1(ssysname) values('sss') select * from Test1 select cast((select COUNT(*) from Test1 where ssysname is not null) as numeric(5,2))/ (select COUNT(*) from Test1) */ // 顺序表 public class Line { public int[] Data { get; set; } public int Length { get; set; } public string Name { get; set; } public int MaxLenght = 10; public Line(int[] data) { Data = new int[10]; Length = data.Length; if (Length > 10) { Length = 10; } for (int i = 0; i < Length; i++) { Data[i] = data[i]; } } // 1<= pos <=L.Lenght+1 private static void InsertOne(Line L, int pos, int da, bool print = true) { if (print) { System.Console.WriteLine(); System.Console.Write(string.Format("Insert position:{0}, insert data:{1}, befor insert ", pos, da)); PrintLine(L); } if (L.Length == L.MaxLenght) { System.Console.WriteLine("Line has no space to insert a new one."); } else { if (pos < 1 || pos > L.Length + 1) { System.Console.WriteLine("The position where new one should be inset must met the condition:1 <= pos <= {0}", L.Length + 1); } else { for (int i = L.Length; i >= pos; i--) { L.Data[i] = L.Data[i - 1]; } L.Data[pos - 1] = da; L.Length += 1; } } if (print) { System.Console.Write("After insert "); PrintLine(L); System.Console.WriteLine(); } } // 1<= pos <=L.Lenght private static void DeleteOne(Line L, int pos, bool print = true) { if (print) { System.Console.WriteLine(); System.Console.Write(string.Format("Delete position:{0}, befor delete ", pos)); PrintLine(L); } if (pos < 1 || pos > L.Length) { System.Console.WriteLine("The position where one should be delete must met the condition:1 <= pos <= {0}", L.Length); } else { for (int i = pos; i < L.Length; i++) { L.Data[i - 1] = L.Data[i]; } L.Length -= 1; } if (print) { System.Console.Write("After delete "); PrintLine(L); System.Console.WriteLine(); } } // return==0, not exist, otherwize exist. private static int FindOne(Line L, int da) { int position = 0; for (int i = 0; i < L.Length; i++) { if (L.Data[i] == da) { position = i + 1; break; } } return position; } private static void PrintLine(Line L) { System.Console.WriteLine(string.Format("Line {0} data:", L.Name)); if (L == null || L.Length <= 0) { System.Console.WriteLine("Null"); } else { StringBuilder sb = new StringBuilder(); for (int i = 0; i < L.Length; i++) { sb.Append(L.Data[i].ToString() + " "); } System.Console.WriteLine(sb.ToString().Trim()); } } public static void TestInsertOne() { int[] a = new int[] { 1, 5, 89, 20 }; Line line = new Line(a); int insertPosition = 0; int insertData = 0; insertPosition = 0; insertData = 10; InsertOne(line, insertPosition, insertData); insertPosition = line.Length + 2; insertData = 10; InsertOne(line, insertPosition, insertData); insertPosition = 1; insertData = 10; InsertOne(line, insertPosition, insertData); insertPosition = line.Length + 1; insertData = 30; InsertOne(line, insertPosition, insertData); } public static void TestDeleteOne() { int[] a = new int[] { 1, 5, 89, 20 }; Line line = new Line(a); int deletePosition = 0; deletePosition = 0; DeleteOne(line, deletePosition); deletePosition = line.Length + 1; DeleteOne(line, deletePosition); deletePosition = 1; DeleteOne(line, deletePosition); deletePosition = line.Length; DeleteOne(line, deletePosition); } public static void TestLineAOrLineB() { int[] a = new int[] { 1, 5, 89, 20 }; Line line1 = new Line(a) { Name = "LineA" }; int[] b = new int[] { 1, 5, 17, 27 }; Line line2 = new Line(b) { Name = "LineB" }; System.Console.WriteLine("Before combine:"); PrintLine(line1); PrintLine(line2); for (int i = 0; i < line2.Length; i++) { if (FindOne(line1, line2.Data[i]) == 0) { InsertOne(line1, line1.Length + 1, line2.Data[i], false); } } System.Console.WriteLine("After combine:"); PrintLine(line1); } public static void TestLineAAndLineB() { int[] a = new int[] { 1, 5, 89, 20 }; Line line1 = new Line(a) { Name = "LineA" }; int[] b = new int[] { 1, 5, 17, 27 }; Line line2 = new Line(b) { Name = "LineB" }; Line line3 = new Line(new int[10]) { Name = "LineC", Length = 0 }; System.Console.WriteLine("Before get same:"); PrintLine(line1); PrintLine(line2); for (int i = 0; i < line2.Length; i++) { if (FindOne(line1, line2.Data[i]) > 0) { InsertOne(line3, line3.Length + 1, line2.Data[i], false); } } System.Console.WriteLine("After get same:"); PrintLine(line3); } } // StackArrary // Empty condition:Top==-1 // Full condition:Top==MaxLenght-1; public class StackArrary { public int[] Data { get; set; } public int MaxLength { get; set; } public int Top { get; set; } public StackArrary(int maxLength) { if (maxLength <= 1) { MaxLength = 1; } else { MaxLength = maxLength; } Data = new int[MaxLength]; Top = -1; } public void Push(int da) { if (Top == MaxLength - 1) { Console.WriteLine("Stack overflow!"); } else { Top++; Data[Top] = da; } } public int Pop() { if (Top == -1) { Console.WriteLine("Stack underflow!"); return -111111; } else { int da = Data[Top]; Top--; return da; } } } // StackLink public class StackLink { public int Data { get; set; } public StackLink Next { get; set; } public static StackLink Push(StackLink sl, int da) { StackLink node = new StackLink(); node.Data = da; node.Next = sl; return node; } public int Pop(StackLink sl) { int da = -111111; if (this != null) { da = sl.Data; sl = sl.Next; } else { Console.WriteLine("Stack underflow!"); } return da; } } public class Node { public int Data { get; set; } public Node Next { get; set; } public static void PrintList(Node head) { System.Console.WriteLine("List data:"); if (head == null) { System.Console.WriteLine("Null"); } else { StringBuilder sb = new StringBuilder(); Node node = head; while (node != null) { sb.Append(node.Data.ToString() + " "); node = node.Next; } System.Console.WriteLine(sb.ToString().Trim()); } } // 循环链表的遍历 public static void PrintLoopList(Node head) { System.Console.WriteLine("Loop list data:"); if (head == null) { System.Console.WriteLine("Null"); } else { StringBuilder sb = new StringBuilder(); Node node = head; int i = 0; while (i == 0 || node != head) { if (i == 0) { i = 1; } sb.Append(node.Data.ToString() + " "); node = node.Next; } System.Console.WriteLine(sb.ToString().Trim()); } } } public class TreeNode { public int Data { get; set; } public TreeNode LChild { get; set; } public TreeNode RChild { get; set; } } // Single linklist public class LinkList { #region Create Linklist // 向前插入发 private static Node CreateList(int[] data) { Node L = null; if (data != null) { Node head = null; Node node = null; for (int i = 0; i < data.Length; i++) { head = new Node(); head.Data = data[i]; head.Next = node; node = head; } L = head; } return L; } // 向后插入法 private static Node CreateList1(int[] data) { Node L = null; if (data != null) { Node head, last, p; head = last = p = new Node(); head.Data = data[0]; for (int i = 1; i < data.Length; i++) { last = new Node(); last.Data = data[i]; p.Next = last; p = last; } last.Next = null; L = head; } return L; } // 创建排序链表 private static Node CreateSortedList(int[] data) { Node head = null; for (int i = 0; i < data.Count(); i++) { head = InsertToSortedList(head, data[i]); } return head; } #endregion #region Insert // 将一个数插入到一个有序链表中,插入后,使之任然有序 public static Node InsertToSortedList(Node head, int da) { Node n = new Node(); n.Data = da; if (head != null) { Node p = null; Node q = head; while (q != null && q.Data <= da) { p = q; q = q.Next; } if (q == head) // 在头插入 { n.Next = head; head = n; } else { if (q == null) // 在尾插入 { p.Next = q; q.Next = null; } else { p.Next = n; n.Next = q; } } } else { head = n; head.Next = null; } return head; } #endregion #region Del private static Node DeleteOne(Node L, int da, bool print = true) { if (print) { System.Console.WriteLine(); System.Console.Write(string.Format("Delete data:{0}, befor delete ", da)); Node.PrintList(L); } Node head, current, previous = null; head = current = L; while (current != null) { if (current.Data == da) { break; } else { previous = current; current = current.Next; } } if (current != null) { // 删除第一个 if (current == head) { head = head.Next; } // 删除最后一个 else if (current.Next == null) { previous.Next = null; } // 删除中间 else { previous.Next = current.Next; } } if (print) { System.Console.Write("After delete "); Node.PrintList(head); System.Console.WriteLine(); } return head; } #endregion #region Reverse Linklist private static Node ReverseList(Node L) { Node p, q; p = q = null; Node head = L; while (head != null) { p = q; q = head; head = head.Next; q.Next = p; } head = q; return head; } #endregion public static void Test() { int[] data = new int[5] { 5, 4, 3, 2, 1 }; Console.WriteLine("Create linklist by forward-inserted."); Node head = CreateList(data); Node.PrintList(head); Console.WriteLine("Create linklist by backward-inserted."); head = CreateList1(data); Node.PrintList(head); Console.WriteLine("Create sorted linklist."); data = new int[5] { 5, 3, 4, 1, 2 }; head = CreateSortedList(data); Node.PrintList(head); Console.WriteLine("Reverse linklist."); head = ReverseList(head); Node.PrintList(head); int deleteData = 5; head = DeleteOne(head, deleteData); deleteData = 1; head = DeleteOne(head, deleteData); deleteData = 3; head = DeleteOne(head, deleteData); deleteData = 2; head = DeleteOne(head, deleteData); deleteData = 4; head = DeleteOne(head, deleteData); } } // Loop linklist public class LoopLinkList { #region Create linklist // 向后插入法 private static Node CreateList(int[] data) { Node head = null, last, p; if (data != null) { int c = data.Count(); if (c > 0) { head = last = new Node(); head.Data = data[0]; for (int i = 1; i < c; i++) { p = new Node(); p.Data = data[i]; last.Next = p; last = p; } last.Next = head; // 首尾相连 } } return head; } #endregion #region Reverse linklist private static Node ReverseList(Node L) { Node head = L; if (L != null) { Node q = null, p = null; int i = 0; while (i == 0 || head != L) { if (i == 0) { i = 1; } q = p; p = head; head = head.Next; p.Next = q; } L.Next = p; // 首尾相连 head = p; } return head; } #endregion #region Insert private static Node InsertSortedList(Node L, int da) { Node head = L; // 插入第一个 if (head == null) { head = new Node(); head.Data = da; head.Next = head; } // 插入第二个 else if (head.Next == L) { Node p = new Node(); p.Data = da; head.Next = p; p.Next = head; if (head.Data >= da) { } else { head = p; } } else { int i = 0; Node p = head; Node q = null; while (i == 0 || p.Next != head) { if (i == 0) { i = 1; } if (p.Data < da) { break; } else { q = p; p = p.Next; } } if (q == null) { if (p == head) // 插入到第一个元素前 { Node l = new Node(); l.Data = da; l.Next = head; // 将最后一个节点的next指向l Node ts = head; while (ts.Next != head) { ts = ts.Next; } ts.Next = l; head = l; } else if (p.Next == head) // 前面n-1个元素都比da大,比较da和最后一个元素的大小 { if (p.Data < da) // 插入到中间 { Node l = new Node(); l.Data = da; q.Next = l; l.Next = p; } else // 插入到最后 { Node l = new Node(); l.Data = da; p.Next = l; l.Next = head; } } else // 插入到中间 { Node l = new Node(); l.Data = da; q.Next = l; l.Next = p; } } } return head; } #endregion #region Delete public static Node Delete(Node head, int da, bool print = true) { if (print) { System.Console.WriteLine(); System.Console.Write(string.Format("Delete data:{0}, befor delete ", da)); Node.PrintLoopList(head); } Node p = head; if (p != null) { if (p.Data == da) // 头节点 { if (head.Next == head) // 就一个节点 { head = null; } else { int i = 0; // 找到最后一个节点 while (i == 0 || p.Next != head) { if (i == 0) { i = 1; } p = p.Next; } p.Next = head.Next; head = head.Next; } } else { Node q = null; int i = 0; while (i == 0 || (p.Data != da && p != head)) { if (i == 0) { i = 1; } q = p; p = p.Next; } if (p == head) // 没找到 { } //else if (p.Next == head) //最后一个 //{ // q.Next = p.Next; //} else { q.Next = p.Next; } } } if (print) { System.Console.Write("After delete "); Node.PrintLoopList(head); System.Console.WriteLine(); } return head; } #endregion public static void Test() { int[] data = new int[5] { 5, 4, 3, 2, 1 }; Console.WriteLine("Create linklist by backward-inserted."); Node head = CreateList(data); Node.PrintLoopList(head); Console.WriteLine("Reverse loop list."); head = ReverseList(head); Node.PrintLoopList(head); int deleteData = 5; head = Delete(head, deleteData); deleteData = 1; head = Delete(head, deleteData); deleteData = 3; head = Delete(head, deleteData); deleteData = 2; head = Delete(head, deleteData); deleteData = 4; head = Delete(head, deleteData); Console.WriteLine("Create sorted linklist."); data = new int[4] { 100, 90, 110, 1950 }; head = null; for (int i = 0; i < data.Count(); i++) { head = InsertSortedList(head, data[i]); } Node.PrintLoopList(head); } } public class TestStack { // ((a+b)*c-d)/(d+c), 检查表达式中括号是否匹配 public static void Test1() { string exp = "((a+b)*c-d)/(d+c"; StackArrary sa = new StackArrary(20); int position = -1; int tt = 0; for (int i = 0; i < exp.Length; i++) { if (exp[i] == '(') { sa.Push(exp[i]); tt = i; } else if (exp[i] == ')') { if (sa.Data[sa.Top] != 40) // 40---'(' { position = i; break; } else { sa.Pop(); } } } if (position < 0) { if (sa.Top == -1) { Console.WriteLine("Match success!"); } else { Console.WriteLine("Match failed at position:{0}!", tt); } } else { Console.WriteLine("Match failed at position:{0}!", position); } } // 将十进制转换成十六进制 275->113 public static void Test2(int dec) { int chushu, beichushu, yu, shang; shang = dec; StackArrary sa = new StackArrary(20); while (shang != 0) { chushu = shang; yu = chushu % 16; shang = chushu / 16; sa.Push(yu); } while (sa.Top != -1) { Console.Write(sa.Pop()); } } } // Empty condition:Front=Rear // Full condition:Front = MaxLength-1 public class QueueArrary { public int[] Data { get; set; } public int MaxLength { get; set; } public int Front { get; set; } public int Rear { get; set; } public QueueArrary(int maxLength) { if (maxLength <= 1) { MaxLength = 1; } else { MaxLength = maxLength; } Data = new int[MaxLength]; Front = Rear = -1; } public void DelQueue() { if (this.Front == this.Rear) { Console.WriteLine("queue is empty."); } else { this.Front++; } } public void InsertQueue(int da) { if (Rear == MaxLength - 1) { Console.WriteLine("queue is full."); } else { Rear++; Data[Rear] = da; } } } // Empty condition: Rear = Front // Full condition: public class LoopQueue { public int[] Data { get; set; } public int MaxLength { get; set; } public int Front { get; set; } public int Rear { get; set; } public LoopQueue(int maxLength) { if (maxLength <= 1) { MaxLength = 1; } else { MaxLength = maxLength; } Data = new int[MaxLength]; Front = Rear = -1; } } public class Queue { public int Data { get; set; } public Queue Next { get; set; } } public class LinkQueue { public Queue Front { get; set; } public Queue Rear { get; set; } public void Insert(int da) { Queue node = new Queue(); node.Data = da; node.Next = null; Rear.Next = node; Rear = node; } public void Delete() { if (Front.Next == null) { Console.WriteLine("Queue is empty."); } else { Front = Front.Next; } } } public class BTree { //先根遍历 public static void PrintByFirstRoot(TreeNode root) { TreeNode node = root; if (node != null) { Console.Write(node.Data.ToString() + " "); if (node.LChild != null) { PrintByFirstRoot(node.LChild); } if (node.RChild != null) { PrintByFirstRoot(node.RChild); } } } // 中根遍历 public static void PrintTreeByCenterRoot(TreeNode root) { TreeNode node = root; Stack<TreeNode> s = new Stack<TreeNode>(); while (node != null) { if (node.LChild != null) { s.Push(node); node = node.LChild; } else { Console.Write(node.Data.ToString() + " "); node = node.LChild; } } int count = s.Count(); for (int i = 0; i < count; i++) { node = s.Pop(); if (node != null) { Console.Write(node.Data.ToString() + " "); if (node.RChild == null) { node = node.RChild; } else { PrintTreeByCenterRoot(node.RChild); } } } } // 中根遍历 public static void PrintTreeByLastRoot(TreeNode root) { TreeNode node = root; Stack<TreeNode> s = new Stack<TreeNode>(); while (node != null) { if (node.LChild != null) { s.Push(node); node = node.LChild; } else { Console.Write(node.Data.ToString() + " "); node = node.LChild; } } int count = s.Count(); for (int i = 0; i < count; i++) { node = s.Pop(); if (node != null) { if (node.RChild == null) { Console.Write(node.Data.ToString() + " "); node = node.RChild; } else { PrintTreeByLastRoot(node.RChild); Console.Write(node.Data.ToString() + " "); } } } } #region Sorted BTree public static TreeNode FindOrder(TreeNode node, int da) { if (node.Data > da) { if (node.LChild != null) { return FindOrder(node.LChild, da); } else { return node; } } else { if (node.RChild != null) { return FindOrder(node.RChild, da); } else { return node; } } } public static TreeNode InsertSortedTree(TreeNode tree, int da) { if (tree == null) { tree = new TreeNode(); tree.Data = da; tree.LChild = tree.RChild = null; } else { TreeNode node = FindOrder(tree, da); TreeNode newNode = new TreeNode(); newNode.Data = da; newNode.LChild = newNode.RChild = null; if (node.Data > da) { node.LChild = newNode; } else { node.RChild = newNode; } } return tree; } #endregion public static void Test() { TreeNode root = null; root = InsertSortedTree(root, 20); root = InsertSortedTree(root, 10); root = InsertSortedTree(root, 15); root = InsertSortedTree(root, 9); root = InsertSortedTree(root, 30); PrintTreeByCenterRoot(root); } } // 二叉 public class SortedBTree { public static TreeNode ConbineTwoList(TreeNode A, TreeNode B) { if (A == null) { return B; } else { if (B != null) { TreeNode node = A; while (node.RChild != null) { node = node.RChild; } node.RChild = B; B.LChild = A; return A; } else { return A; } } } public static TreeNode Convert2DoubleLinkList(TreeNode head) { TreeNode list = null; Stack<TreeNode> s = new Stack<TreeNode>(); TreeNode node = head; // 由根节点找到最右边的节点,就是最大值节点,并将遍历的其他节点入栈。 while (node != null) { if (node.LChild != null) { s.Push(node); node = node.LChild; } else { node.RChild = list; list = node; } } int n = s.Count(); for (int i = 0; i < n; i++) { node = s.Pop(); list.RChild = node; node.LChild = list; if (node.RChild != null) { TreeNode nt = Convert2DoubleLinkList(node.LChild); list = ConbineTwoList(list, nt); } } return list; } // 将一个排序二叉树变成排序的双向链表 public static void TestConvert2DoubleLinkList() { TreeNode root = null; root = BTree.InsertSortedTree(root, 20); root = BTree.InsertSortedTree(root, 10); root = BTree.InsertSortedTree(root, 15); root = BTree.InsertSortedTree(root, 9); root = BTree.InsertSortedTree(root, 30); TreeNode list = Convert2DoubleLinkList(root); } } }
/* copy rice noorquacker industries 2018 or something just put it under the unilicense and be done with it aight so I made this thing when I was into hypermazes and stuff and it's a pile of poorly threaded garbage, I know after all, it's made by me, Noorquacker, and all I do is make Garry's Mod Wiremod Expression 2 chip thingys so have fun do whatever make it 12 thread please because I now have the 8700K or make it cuda wait no make it opencl */ using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using fNbt; using System.Threading; namespace HypermazeGen { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public Bitmap mazeBmp; public byte[] mazeBytes; public byte[] schBytes; public NbtCompound schRoot; //Variable stuff public int progress = 0; public int progressPercent = 0; public System.Windows.Forms.Timer loopTimer = new System.Windows.Forms.Timer(); private void Form1_Load(object sender, EventArgs e) { loopTimer.Tick += new EventHandler(TimerClk); loopTimer.Interval = 100; loopTimer.Start(); } private void button1_Click(object sender, EventArgs e) { BitmapDialog.ShowDialog(); } private void BitmapDialog_FileOk(object sender, CancelEventArgs e) { //Turn all of the image data to hex binary junk Image imgIn = Image.FromFile(BitmapDialog.FileName); mazeBmp = new Bitmap(imgIn); mazeBytes = new byte[mazeBmp.Height * mazeBmp.Width]; Console.WriteLine("starting thread"); Thread parseThread = new Thread(() => ParseImg()); parseThread.Start(); //Spent half an hour debugging when I realized I forgot this line. //At this point, you can File.Write(mazeBytes) and look at it with a hex editor with line wrapping set //to whatever the image width was and it'll show a really trashy representation of the image in hex. } private void ParseImg() { progress = 1; Console.WriteLine("parsing"); for (int x = 0; x < mazeBmp.Width; x++) { for (int y = 0; y < mazeBmp.Height; y++) { Color pixCol = mazeBmp.GetPixel(x, y); mazeBytes[y * mazeBmp.Width + x] = (byte)((Math.Sign(pixCol.R) & Math.Sign(pixCol.G) & Math.Sign(pixCol.B))); progressPercent = (int)Math.Floor((y * mazeBmp.Width + x) / (mazeBmp.Height * (decimal)mazeBmp.Width) * 100m); //m means decimal, like 100d = double and 100f = float } } Console.WriteLine("done"); progress = 2; } private void InvertCheck_CheckedChanged(object sender, EventArgs e) { invertList.Text = "Walls are " + (InvertCheck.Checked ? "BLACK" : "WHITE"); } private void button2_Click(object sender, EventArgs e) { try { if (mazeBmp.Width * mazeBmp.Height == LengthNum.Value * WidthNum.Value * HeightNum.Value) { //Set up an evniroman-thingy-environment to convert the image's hex bin junk to a YZX-formatted schematic byte[] schBytes = new byte[mazeBmp.Width * mazeBmp.Height * 2]; Console.WriteLine("Converting raw bitmap to YZX schematic..."); Thread convertThread = new Thread(() => ConvertImg(mazeBytes, (int)HeightNum.Value, (int)LengthNum.Value, (int)WidthNum.Value, mazeBmp.Width, mazeBmp.Height, InvertCheck.Checked)); convertThread.Start(); } else { if (BitmapDialog.FileName != "") { MessageBox.Show("Incorrect dimensions. Did you input incorrect dimensions?", "Failure", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show("Did you specify a file?"); } } } catch(DivideByZeroException) { MessageBox.Show("Attempted to divide by 0. Did you switch X/Y/Z dimensions?", "Exception thrown(DivideByZeroException)", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch(NullReferenceException) { MessageBox.Show("Attempted to reference a null value." + (BitmapDialog.FileName=="" ? "\nBecause you didn't specify a file." : " I don't know what happened."), "Exception thrown(NullReferenceException)", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void ConvertImg(byte[] mazeBytes, int HeightNum, int LengthNum, int WidthNum, int imgWidth, int imgHeight, bool InvertCheck) { progress = 3; int layerWidth; int layerHeight; layerWidth = (int)LayerWidth.Value; layerHeight = (int)LayerHeight.Value; byte[] FULLDANGBYTEARRAY = new byte[(LengthNum - 0) * HeightNum * (WidthNum - 0) * layerWidth * layerHeight]; for (int ya = 0; ya < HeightNum * layerHeight; ya++) { int y = (int)Math.Floor(ya / (decimal)layerHeight); for (int za = 0; za < LengthNum * layerWidth; za++) { //As you can see, we go in YZX order because .schematic int z = (int)Math.Floor(za / (decimal)layerWidth); //uses YZX order, and it's gonna save a heck of a lot of time for (int xa = 0; xa < WidthNum * layerWidth; xa++) { int x = (int)Math.Floor(xa / (decimal)layerWidth); FULLDANGBYTEARRAY[(ya * LengthNum * WidthNum) + (z * WidthNum) + x] = (byte)( mazeBytes[ x + //normal x value z * imgWidth + //1 down on Z axis is (imgWidth) pixels down (y % (int)Math.Floor(imgWidth / (decimal)WidthNum)) * WidthNum + //Y has to go 1 layer's height down, but when Y exceeds the layers per column, (int)Math.Floor(y / Math.Floor(imgWidth / (decimal)WidthNum)) * imgWidth * LengthNum //it must shift 1 row of layers down. Then we use modulus up above to make sure that it resets. ] * (InvertCheck ? -1 : 1) + (InvertCheck ? 1 : 0)); progressPercent = (int)Math.Floor((y * WidthNum * LengthNum + z * WidthNum + x) / (decimal)mazeBytes.Length * 100m); //Did You Know? this draws the maze mirrored on a flat plane(aka upside down), //which normally doesn't do anything unless you want it not upside down. } } } schBytes = FULLDANGBYTEARRAY; schRoot = new NbtCompound("Schematic"); schRoot.Add(new NbtList("Entities", NbtTagType.Compound)); schRoot.Add(new NbtList("TileEntities", NbtTagType.Compound)); schRoot.Add(new NbtShort("Height", (short)(HeightNum * layerHeight))); schRoot.Add(new NbtShort("Length", (short)(LengthNum * layerWidth))); schRoot.Add(new NbtShort("Width", (short)(WidthNum * layerWidth))); schRoot.Add(new NbtString("Materials", "Alpha")); schRoot.Add(new NbtByteArray("Data", new byte[HeightNum * LengthNum * WidthNum * layerHeight * layerWidth])); schRoot.Add(new NbtByteArray("Blocks", schBytes)); progress = 4; } private void SaveDialog_FileOk_1(object sender, CancelEventArgs e) { NbtFile file = new NbtFile(schRoot); file.SaveToFile(SaveDialog.FileName, NbtCompression.GZip); MessageBox.Show("Successfully saved to file!"); } private void TimerClk(object sender, EventArgs e) { progressBar1.Value = progressPercent; switch(progress) { case 0: button2.Enabled = false; progressBar1.Visible = false; label4.Text = "Progress: Please select a file"; break; case 1: button2.Enabled = false; progressBar1.Visible = true; label4.Text = "Progress: Parsing image, please wait..."; break; case 2: button2.Enabled = true; progressBar1.Visible = false; label4.Text = "Progress: Standby, ready to convert"; break; case 3: progressBar1.Visible = true; button2.Enabled = false; label4.Text = "Progress: Converting to schematic, please wait..."; break; case 4: progress = 0; progressBar1.Visible = false; button2.Enabled = false; label4.Text = "Progress: Finished!"; SaveDialog.ShowDialog(); break; default: //honey, where is my super suit? loopTimer.Stop(); DialogResult result = MessageBox.Show("Current conversion progress is invalid(" + progress.ToString() + ")", "HELP WHAT THE HECK IS HAPPENING TO ME", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); Application.Exit(); break; } } } }
using System.Xml.Serialization; namespace PlatformRacing3.Web.Responses.Procedures.Stamps; public class DataAccessGetMyStampsResponse : DataAccessDataResponse<DataAccessGetMyStampsResponse.MyStampData> { [XmlElement("category")] public string Category { get; set; } private DataAccessGetMyStampsResponse() { } public DataAccessGetMyStampsResponse(string category) { this.Rows = new List<MyStampData>(); this.Category = category; } public void AddStamp(uint stampId) { this.Rows.Add(new MyStampData(stampId)); } public class MyStampData { [XmlElement("stamp_id")] public uint StampId { get; set; } private MyStampData() { } public MyStampData(uint stampId) { this.StampId = stampId; } } }
using MXDbHelper; using MXDbHelper.MyExtend; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.IO; using System.Net; using System.Threading; namespace BusinessLogic { class ServerTempFile : BasicLogic, IBasiclogic { public readonly string FilePath = ""; public readonly string TempFileUrl = ""; public ServerTempFile() : base() { FilePath = ConfigurationManager.AppSettings["File"].ToString(); TempFileUrl = ConfigurationManager.AppSettings["FileUrl"].ToString(); Thread th = new Thread(new ThreadStart(clearTempFile)); th.Start(); } private static object obj = new object(); private static ServerTempFile _instance = null; //本身单例实体 public new static ServerTempFile getInstance() { if (_instance == null) { lock (obj) { if (_instance == null) { _instance = new ServerTempFile(); } } } return _instance; } /// <summary> /// 生成文件信息 /// </summary> /// <param name="ds"></param> /// <param name="st"></param> /// <returns></returns> public string GetExcelFile(DataSet ds, SheetTable[] st) { NpoiExcelHelper npo = new NpoiExcelHelper(); string str = NpoiExcelHelper.DataTableToExcel(FilePath + "\\TempFile\\", ds, st); Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("File", TempFileUrl + "TempFile/" + str); return dic.ToJson(); } /// <summary> /// 生成文件信息 /// </summary> /// <param name="ds"></param> /// <param name="st"></param> /// <returns></returns> public string GetExcelFile(string planName, string shortName, string strJson, string strConn, DataSet ds = null) { ComMethod com = new ComMethod(strConn); string str = com.ExecPlanExcel(planName, shortName, strJson, FilePath + "\\TempFile\\", ds); Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("File", TempFileUrl + "TempFile/" + str); return dic.ToJson(); } /// <summary> /// Http下载文件 /// </summary> public string HttpDownloadFile(string url, string path) { // 设置参数 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //发送请求并获取相应回应数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream responseStream = response.GetResponseStream(); //创建本地文件写入流 Stream stream = new FileStream(path, FileMode.Create); byte[] bArr = new byte[1024]; int size = responseStream.Read(bArr, 0, (int)bArr.Length); while (size > 0) { stream.Write(bArr, 0, size); size = responseStream.Read(bArr, 0, (int)bArr.Length); } stream.Close(); responseStream.Close(); return path; } /// <summary> /// 清空内存过期用户seesion /// </summary> private void clearTempFile() { while (true) { try { string strPath = FilePath + "\\TempFile"; if (Directory.Exists(strPath)) { DirectoryInfo dir = new DirectoryInfo(strPath); foreach (System.IO.FileInfo file in dir.GetFiles()) file.Delete(); foreach (System.IO.DirectoryInfo subDirectory in dir.GetDirectories()) subDirectory.Delete(true); } } catch (Exception ex) { LogError.AddErrorLog("clearTempFile", ex.ToString()); } Thread.Sleep(120000); } } } }
using System; namespace XorLog.Core { public class FileLoadedEventArgs : EventArgs { public long TotalSize { get; private set; } public string Path { get; private set; } public string FileName { get; private set; } public FileLoadedEventArgs(long totalSize, string path, string fileName) { TotalSize = totalSize; Path = path; FileName = fileName; } } }
using System; using Selenite.Enums; namespace Selenite.Attributes { public class CommandAttribute : Attribute { } public class DriverTypeAttribute : Attribute { DriverTypeAttribute(DriverType driverType) { DriverType = driverType; } public DriverType DriverType { get; private set; } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Linq.Expressions; namespace Reception.Domain.Services.Abstractions { /// <summary> /// Репозиторий с возможностью изменять данные. /// </summary> /// <typeparam name="TEntity">Тип сущности.</typeparam> public interface IMutableRepository<TEntity> : IReadOnlyRepository<TEntity> where TEntity : class, new() { /// <summary> /// Добавляет записи в БД на основе сущности. /// </summary> /// <param name="entity">Сущность.</param> /// <param name="cancellation">Отмена задачи.</param> /// <returns>Добавленная сущность.</returns> Task<TEntity> AddAsync(TEntity entity, CancellationToken cancellation); /// <summary> /// Добавляет записи в БД на основе сущностей. /// </summary> /// <param name="entity">Сущности.</param> /// <param name="cancellation">Отмена задачи.</param> /// <returns>Добавленные сущности.</returns> Task<IEnumerable<TEntity>> AddRangeAsync(IEnumerable<TEntity> entities, CancellationToken cancellation); /// <summary> /// Обновляет записи в БД на основе сущности. /// </summary> /// <param name="entity">Сущность.</param> /// <param name="cancellation">Отмена задачи.</param> /// <returns>Обновленная сущность.</returns> Task UpdateAsync(TEntity entity, CancellationToken cancellation); /// <summary> /// Удаляет записи в БД на основе сущности. /// </summary> /// <param name="entity">Сущность.</param> /// <param name="cancellation">Отмена задачи.</param> /// <returns>Задача, представляющая асинхронную операцию удаления записей.</returns> Task DeleteAsync(TEntity entity, CancellationToken cancellation); /// <summary> /// Удаляет записи в БД удовлетворяющие предикату. /// </summary> /// <param name="predicate">Предикат.</param> /// <param name="cancellation">Отмена задачи.</param> /// <returns>Задача, представляющая асинхронную операцию удаления записей.</returns> Task DeleteAsync(Expression<Func<TEntity, bool>> predicate, CancellationToken cancellation); /// <summary> /// Удаляет записи в БД на основе коллекции сущностей. /// </summary> /// <param name="entities">Коллекция сущностей.</param> /// <param name="cancellation">Отмена задачи.</param> /// <returns>Задача, представляющая асинхронную операцию удаления записей.</returns> Task DeleteRangeAsync(IEnumerable<TEntity> entities, CancellationToken cancellation); } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using UnityEngine; using UnityEngine.Assertions; using UnityEngine.Networking.NetworkSystem; using Object = UnityEngine.Object; namespace ReadyGamerOne.MemorySystem { /// <summary> /// 这个类提供关于内存的优化和管理 /// 1、所有资源只会从Resources目录加载一次,再取的时候会从这个类的字典中取,尤其是一些预制体,经常频繁加载,使用这个类封装的Instantiate方法可以很好地解决这个问题 /// 2、提供一些释放资源的接口 /// 3、以后会提供关于AssetBubble的方法和接口 /// 4、提供从Resources目录运行时加载一整个目录资源的接口,比如,加载某个文件夹下所有图片,音频 /// </summary> public static class MemoryMgr { #region Private //private static List<AssetBundle> assetBundleList=new List<AssetBundle>(); private static Dictionary<string, Object> sourceObjectDic; private static Dictionary<string, Object> SourceObjects { get { if(sourceObjectDic==null) sourceObjectDic=new Dictionary<string, Object>(); return sourceObjectDic; } set { sourceObjectDic = value; } } #endregion /// <summary> /// 根据路径获取资源引用,如果原来加载过,不会重写加载 /// </summary> /// <param name="path"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> /// <exception cref="Exception"></exception> public static T GetSourceFromResources<T>(string path)where T : Object { if (SourceObjects.ContainsKey(path))//加载过这个资源 { if(SourceObjects[path]==null) throw new Exception("资源已经释放,但字典中引用亦然保留"); var ans= SourceObjects[path] as T; if (ans == null) Debug.LogWarning("资源引用存在,但类型转化失败,小心bug"); return ans; } else//初次加载资源 { var source = Resources.Load<T>(path); if (source == null) { Debug.LogError("资源加载错误,错误路径:"+path); return null; } SourceObjects.Add(path, source); return source; } } /// <summary> /// 释放通过Resources.Load方法加载来的对象 /// </summary> /// <param name="path"></param> /// <param name="sourceObj"></param> /// <typeparam name="T"></typeparam> public static void ReleaseSourceFromResources<T>(string path, ref T sourceObj) where T : Object { if (!SourceObjects.ContainsKey(path)) { Debug.LogWarning("资源字典中并不包含这个路径,注意路径是否错误:" + path); return; } var ans = SourceObjects[path] as T; if (ans == null) { Debug.LogWarning("该资源路径下Object转化为null,注意路径是否错误:" + path); } SourceObjects.Remove(path); Resources.UnloadAsset(ans); sourceObj = null; } public static void ReleaseSourceFromResources<T>(ref T sourceObj) where T : Object { if (!SourceObjects.ContainsValue(sourceObj)) { Debug.LogWarning("资源字典中没有这个值,你真的没搞错?"); return; } var list = new List<string>(); foreach(var data in SourceObjects) if (data.Value == sourceObj) { Resources.UnloadAsset(data.Value); list.Add(data.Key); } foreach (var s in list) { SourceObjects.Remove(s); } list = null; sourceObj = null; } /// <summary> /// 释放游离资源 /// </summary> public static void ReleaseUnusedAssets() { SourceObjects.Clear(); Resources.UnloadUnusedAssets(); } /// <summary> /// 根据路径实例化对象 /// </summary> /// <param name="path"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> public static T Instantiate<T>(string path)where T:Object { return Object.Instantiate(GetSourceFromResources<T>(path)); } /// <summary> /// 实例化GameObject /// </summary> /// <param name="path"></param> /// <param name="parent"></param> /// <returns></returns> public static GameObject InstantiateGameObject(string path,Transform parent=null) { var source = GetSourceFromResources<GameObject>(path); Assert.IsTrue(source); return Object.Instantiate(source,parent); } public static GameObject InstantiateGameObject(string path, Vector3 pos, Quaternion quaternion, Transform parent = null) { var source = GetSourceFromResources<GameObject>(path); Assert.IsTrue(source); return Object.Instantiate(source,pos,quaternion,parent); } /// <summary> /// 从Resources目录中动态加载指定目录下所有内容 /// </summary> /// <param name="nameClassType">目录下所有资源的名字要作为一个静态类的public static 成员,这里传递 这个静态类的Type</param> /// <param name="dirPath">从Resources开始的根目录,比如“Audio/"</param> /// <param name="onLoadAsset">加载资源时调用的委托,不能为空</param> /// <typeparam name="TAssetType">加载资源的类型</typeparam> /// <exception cref="Exception">委托为空会抛异常</exception> public static void LoadAssetFromResourceDir<TAssetType>(Type nameClassType, string dirPath = "",Action<string,TAssetType> onLoadAsset=null) where TAssetType : Object { var infoList = nameClassType.GetFields(BindingFlags.Static|BindingFlags.Public); foreach (var fieldInfo in infoList) { string assetName = fieldInfo.GetValue(null) as string; var res = GetSourceFromResources<TAssetType>(dirPath +assetName); if(onLoadAsset==null) throw new Exception("onLoadAsset为 null, 那你加载资源干啥?? "); onLoadAsset.Invoke(assetName, res); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bullet : MonoBehaviour { public float speed = 0; internal Rigidbody2D rb; public GameObject explosionAtWall; private void Awake() { rb = GetComponent<Rigidbody2D>(); } // Start is called before the first frame update public virtual void Start() { rb.AddForce(Vector2.up * speed, ForceMode2D.Impulse); } // Update is called once per frame public virtual void Update() { rb.velocity = Vector2.up * Time.deltaTime * speed; } /// <summary> /// 子弹碰到空气墙,销毁子弹,并播放音效; /// </summary> /// <param name="collision"></param> public virtual void OnCollisionEnter2D(Collision2D collision) { //销毁子弹; Destroy(this.gameObject); if (collision.collider.gameObject.tag == "Wall") { //print(1); //播放爆炸动画; Animation anim = Instantiate(explosionAtWall, collision.contacts[0].point, Quaternion.identity).GetComponent<Animation>(); anim.Play(); Destroy(anim.gameObject, 0.5f); } //玩家子弹打中堡垒,销毁子弹和毁坏堡垒; if (collision.collider.gameObject.tag == "Fort") { Destroy(gameObject); Destroy(collision.collider.gameObject); } } }
using LuaInterface; using SLua; using System; using UnityEngine; public class Lua_UnityEngine_SleepTimeout : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { SleepTimeout o = new SleepTimeout(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_NeverSleep(IntPtr l) { int result; try { LuaObject.pushValue(l, true); LuaObject.pushValue(l, -1); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_SystemSetting(IntPtr l) { int result; try { LuaObject.pushValue(l, true); LuaObject.pushValue(l, -2); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "UnityEngine.SleepTimeout"); LuaObject.addMember(l, "NeverSleep", new LuaCSFunction(Lua_UnityEngine_SleepTimeout.get_NeverSleep), null, false); LuaObject.addMember(l, "SystemSetting", new LuaCSFunction(Lua_UnityEngine_SleepTimeout.get_SystemSetting), null, false); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_SleepTimeout.constructor), typeof(SleepTimeout)); } }
namespace Amazon.Suporte.Database { public class UnitOfWork : IUnitOfWork { private readonly SupportDBContext _context; public UnitOfWork(SupportDBContext context) { _context = context; ProblemRepository = new ProblemRepository(_context); } public IProblemRepository ProblemRepository { get; private set; } public int Complete() { return _context.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataTemplates { public class Flugzeug : INotifyPropertyChanged { public enum FlugzeugTyp { Passagier, Fracht, Agrar, Lösch, Militär } private string _typenName; public string TypenName { get { return _typenName; } set { _typenName = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(TypenName))); } } private double _spannweite; /// <summary> /// Spannweite in Metern /// </summary> public double Spannweite { get { return _spannweite; } set { _spannweite = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Spannweite))); } } private FlugzeugTyp _typ; public FlugzeugTyp Typ { get { return _typ; } set { _typ = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Typ))); } } private string _fotoUrl; public event PropertyChangedEventHandler PropertyChanged; public string FotoUrl { get { return _fotoUrl; } set { _fotoUrl = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(FotoUrl))); } } public Flugzeug(string typenName, double spannweite, FlugzeugTyp typ, string fotoUrl) { TypenName = typenName; Spannweite = spannweite; Typ = typ; FotoUrl = fotoUrl; } public Flugzeug() { } } }
using System; namespace Im.Access.GraphPortal.Data { public class DbChaosPolicy { public Guid Id { get; set; } public string MachineName { get; set; } public string ServiceName { get; set; } public string PolicyKey { get; set; } public bool Enabled { get; set; } public bool FaultEnabled { get; set; } public double FaultInjectionRate { get; set; } public bool LatencyEnabled { get; set; } public double LatencyInjectionRate { get; set; } public DateTimeOffset LastUpdated { get; set; } } }
using System.IO; using System.Reflection; using Newtonsoft.Json; namespace ChesterDevs.Core.Aspnet.App { public class FileSystemWrapper : IFileSystemWrapper { private static string rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); public T ReadJson<T>(string path) { var fullPath = BuildAndEnsurePath(path); if (!File.Exists(fullPath)) return default(T); using (var streamReader = File.OpenText(fullPath)) using (var jsonTextReader = new JsonTextReader(streamReader)) { var serializer = new JsonSerializer(); return serializer.Deserialize<T>(jsonTextReader); } } public void SaveFile(string path, string data) { var fullPath = BuildAndEnsurePath(path); File.WriteAllText(fullPath, data); } private string BuildAndEnsurePath(string path) { var cleanPath = path.Replace("/", "\\").TrimStart('\\'); var fullPath = $"{rootPath}\\{cleanPath}"; var directory = Path.GetDirectoryName(fullPath); if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); return fullPath; } } }
using System; using System.Collections.Generic; using Xamarin.Forms; using System.Collections.ObjectModel; namespace Dietando.ViewModel { public class ListRefeicoesViewModel : BaseViewModel { private ObservableCollection<Refeicao> _listrefeicoes = new ObservableCollection<Refeicao>(){ new Refeicao{ id = 1, Horario = new TimeSpan(7,0,0), Title = "Café da Manhã", dataInicial = new DateTime(2016, 1, 31), dataFinal = new DateTime(2016, 3, 31), check = false }, new Refeicao{ id = 2, Horario = new TimeSpan(7,0,0), Title = "Café da Manhã", dataInicial = new DateTime(2016, 1, 31), dataFinal = new DateTime(2016, 3, 31), check = false }, new Refeicao{ id = 3, Horario = new TimeSpan(7,0,0), Title = "Café da Manhã", dataInicial = new DateTime(2016, 1, 31), dataFinal = new DateTime(2016, 3, 31), check = false }, new Refeicao{ id = 4, Horario = new TimeSpan(7,0,0), Title = "Café da Manhã", dataInicial = new DateTime(2016, 1, 31), dataFinal = new DateTime(2016, 3, 31), check = false }, new Refeicao{ id = 5, Horario = new TimeSpan(7,0,0), Title = "Café da Manhã", dataInicial = new DateTime(2016, 1, 31), dataFinal = new DateTime(2016, 3, 31), check = false }, new Refeicao{ id = 6, Horario = new TimeSpan(7,0,0), Title = "Café da Manhã", dataInicial = new DateTime(2016, 1, 31), dataFinal = new DateTime(2016, 3, 31), check = false }, }; public ObservableCollection<Refeicao> ListRefeicoes{ get{ return _listrefeicoes; } set { _listrefeicoes = value; NotifyPropertyChange ("ListRefeicoes"); } } private ListView _listview; public ListView ListView{ get{ return _listview; } set{ _listview = value; NotifyPropertyChange ("ListView"); } } private String _onItemSelected; public String OnItemSelected{ get{ return _onItemSelected; } set{ if (value != null) MessagingCenter.Send<string> (value, "DetailRefeicao"); } } public ListRefeicoesViewModel () { } } }
/* * Copyright (c) 2020 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 SquatCounter.Services; using System.Windows.Input; using Xamarin.Forms; namespace SquatCounter.ViewModels { /// <summary> /// Provides welcome page view abstraction. /// </summary> public class WelcomePageViewModel : ViewModelBase { /// <summary> /// Navigates to guide page. /// </summary> public ICommand GoToGuideIndexPageCommand { get; } /// <summary> /// Initializes WelcomePageViewModel class instance. /// </summary> public WelcomePageViewModel() { GoToGuideIndexPageCommand = new Command(ExecuteGoToGuideIndexPageCommand); } /// <summary> /// Handles execution of GoToGuideIndexPageCommand. /// Navigates to guide page. /// </summary> private void ExecuteGoToGuideIndexPageCommand() { PageNavigationService.Instance.GoToGuidePage(); } } }
using System.Collections.Generic; using System.Linq; using CloneDeploy_DataModel; using CloneDeploy_Entities; using CloneDeploy_Entities.DTOs; namespace CloneDeploy_Services { public class ScriptServices { private readonly UnitOfWork _uow; public ScriptServices() { _uow = new UnitOfWork(); } public ActionResultDTO AddScript(ScriptEntity script) { var actionResult = new ActionResultDTO(); var validationResult = ValidateScript(script, true); if (validationResult.Success) { _uow.ScriptRepository.Insert(script); _uow.Save(); actionResult.Success = true; actionResult.Id = script.Id; } else { actionResult.ErrorMessage = validationResult.ErrorMessage; } return actionResult; } public ActionResultDTO DeleteScript(int scriptId) { var script = GetScript(scriptId); if (script == null) return new ActionResultDTO {ErrorMessage = "Script Not Found", Id = 0}; _uow.ScriptRepository.Delete(scriptId); _uow.Save(); var actionResult = new ActionResultDTO(); actionResult.Success = true; actionResult.Id = script.Id; return actionResult; } public ScriptEntity GetScript(int scriptId) { return _uow.ScriptRepository.GetById(scriptId); } public List<ScriptEntity> SearchScripts(string searchString = "") { return _uow.ScriptRepository.Get(s => s.Name.Contains(searchString)); } public string TotalCount() { return _uow.ScriptRepository.Count(); } public ActionResultDTO UpdateScript(ScriptEntity script) { var s = GetScript(script.Id); if (s == null) return new ActionResultDTO {ErrorMessage = "Script Not Found", Id = 0}; var validationResult = ValidateScript(script, false); var actionResult = new ActionResultDTO(); if (validationResult.Success) { _uow.ScriptRepository.Update(script, script.Id); _uow.Save(); actionResult.Success = true; actionResult.Id = script.Id; } else { actionResult.ErrorMessage = validationResult.ErrorMessage; } return actionResult; } private ValidationResultDTO ValidateScript(ScriptEntity script, bool isNewScript) { var validationResult = new ValidationResultDTO {Success = true}; if (string.IsNullOrEmpty(script.Name) || !script.Name.All(c => char.IsLetterOrDigit(c) || c == '_')) { validationResult.Success = false; validationResult.ErrorMessage = "Script Name Is Not Valid"; return validationResult; } if (isNewScript) { if (_uow.ScriptRepository.Exists(h => h.Name == script.Name)) { validationResult.Success = false; validationResult.ErrorMessage = "This Script Already Exists"; return validationResult; } } else { var originalScript = _uow.ScriptRepository.GetById(script.Id); if (originalScript.Name != script.Name) { if (_uow.ScriptRepository.Exists(h => h.Name == script.Name)) { validationResult.Success = false; validationResult.ErrorMessage = "This Script Already Exists"; return validationResult; } } } return validationResult; } } }