text
stringlengths
13
6.01M
using NTier.Model.Model.Entities; using NTier.Service.Service.Option; using NTier.UI.Areas.Admin.Models; using NTier.UI.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace NTier.UI.Areas.Admin.Controllers { [Role("Admin")] public class CategoryController : Controller { CategoryService _categoryService; public CategoryController() { _categoryService = new CategoryService(); } public ViewResult List() => View(_categoryService.GetActive()); [HttpGet] public ViewResult Add() => View(); [HttpPost] public RedirectToRouteResult Add(Category data) { _categoryService.Add(data); return RedirectToAction("List", "Category", new { area = "Admin" }); } public RedirectToRouteResult Delete(Guid? id) { if (id == null) return RedirectToAction("List", "Category", new { area = "Admin" }); _categoryService.Remove((Guid)id); return RedirectToAction("List", "Category", new { area = "Admin" }); } [HttpGet] public ActionResult Update(Guid? id) { if (id == null) return RedirectToAction("List", "Category", new { area = "Admin" }); Category cat = _categoryService.GetById((Guid)id); CategoryVM model = new CategoryVM() { ID = cat.ID, Name = cat.Name, Description = cat.Description }; return View(model); } [HttpPost] public RedirectToRouteResult Update(CategoryVM data) { if (!ModelState.IsValid) { return RedirectToAction("List", "Category", new { area = "Admin" }); } Category cat = _categoryService.GetById(data.ID); cat.Name = data.Name; cat.Description = data.Description; _categoryService.Update(cat); return RedirectToAction("List", "Category", new { area = "Admin" }); } } }
using UnityEngine; using System.Collections; public class FPSCameraMovement : MonoBehaviour { void Update () { var directionVector = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); if(directionVector != Vector3.zero){ transform.Translate(new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")), Space.Self); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Webcorp.lib.onedcut { public class BeamStock { public BeamStock() { } public BeamStock(int length,int cost) { this.Length = length; this.Cost = cost; } public int Length { get; set; } public int Cost { get; set; } } }
using Innouvous.Utils.MVVM; using System; using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Data; using ToDo.Client.Core.Tasks; using System.Collections.ObjectModel; using System.Windows.Input; using Innouvous.Utils; namespace ToDo.Client.ViewModels { public class HistoryViewerViewModel : ViewModel { private System.Windows.Controls.Calendar calendar; private CollectionViewSource tasksView; private ObservableCollection<TaskItemViewModel> tasks = new ObservableCollection<TaskItemViewModel>(); private Window window; public HistoryViewerViewModel(Window window, System.Windows.Controls.Calendar calendar) //TODO: Should use callback to UI instead? { this.window = window; this.calendar = calendar; DateStyleConverter.Logs = null; calendar.DisplayDateStart = GetStartDate(); calendar.DisplayDateEnd = DateTime.Today.AddDays(-1); calendar.DisplayDate = calendar.DisplayDateEnd.Value; SelectedDate = calendar.DisplayDateEnd; tasksView = new CollectionViewSource(); tasksView.Source = tasks; LoadTasksList(); } private static DateTime GetStartDate() { DateTime dt = DateTime.Today.AddMonths(-3); var first = Workspace.Instance.TasksLog.OrderBy(x => x.Date).FirstOrDefault(); if (first != null) dt = first.Date; return dt; } private void LoadTasksList() { var list = (from t in Workspace.Instance.TasksLog select t.Task).Distinct().OrderBy(x => x.Name); tasks.Clear(); foreach (var t in list) tasks.Add(new TaskItemViewModel(t)); } public ICollectionView Tasks { get { return tasksView.View; } } public bool TaskSelected { get { return selectedTask != null; } } private TaskItemViewModel selectedTask; public TaskItemViewModel SelectedTask { get { return selectedTask; } set { selectedTask = value; UpdateCalendar(); UpdateRadioBoxes(); RaisePropertyChanged(); RaisePropertyChanged("TaskSelected"); } } /// <summary> /// Updates the Calendar highlighting the log dates /// </summary> private void UpdateCalendar() { if (SelectedTask != null) { int taskId = SelectedTask.Data.TaskItemID; var logDates = Workspace.Instance.TasksLog .Where(x => x.TaskID == taskId) //&& x.Completed .OrderBy(x => x.Date); DateStyleConverter.Logs = logDates.ToList(); //Redraw Calendar var tmp = calendar.CalendarDayButtonStyle; calendar.CalendarDayButtonStyle = null; calendar.CalendarDayButtonStyle = tmp; } } #region Deprecated //TODO: Remove private DateTime? selectedDate; public DateTime? SelectedDate { get { return selectedDate; } set { selectedDate = value; RaisePropertyChanged(); UpdateRadioBoxes(); RaisePropertyChanged(); } } private bool yesSelected; public bool YesSelected { get { return yesSelected; } set { yesSelected = value; RaisePropertyChanged(); RaisePropertyChanged("NoSelected"); SetCompleted(value); } } private void SetCompleted(bool completed) { //Deprecated, no changing /* if (SelectedTask != null && SelectedDate != null) { Workspace.API.LogCompleted(SelectedDate.Value, SelectedTask.Data.TaskItemID, completed); UpdateCalendar(); } */ } public bool NoSelected { get { return !yesSelected; } } private void UpdateRadioBoxes() { if (SelectedDate != null && SelectedTask != null) { var log = GetLog(SelectedTask.Data, SelectedDate.Value); if (log != null) { YesSelected = log.Completed; return; } } YesSelected = false; } private TaskLog GetLog(TaskItem task, DateTime date) { var log = Workspace.Instance.TasksLog .Where(x => x.TaskID == task.TaskItemID && x.Date == date).FirstOrDefault(); return log; } #endregion public ICommand CloseCommand { get { return new CommandHelper(() => window.Close()); } } public ICommand ClearLogsCommand { get { return new CommandHelper(ClearLogs); } } private void ClearLogs() { try { if (selectedTask == null) return; else if (!MessageBoxFactory.ShowConfirmAsBool("Delete all log entries?", "Confirm Delete")) return; foreach (var t in Workspace.Instance.TasksLog.Where(x => x.TaskID == SelectedTask.Data.TaskItemID)) Workspace.Instance.TasksLog.Remove(t); Workspace.Instance.SaveChanges(); UpdateCalendar(); } catch (Exception e) { } } } }
using System; using Models; using System.Collections.Generic; using BL; namespace UI { public class MainMenu: IMenu { private IPetBL _petbl; public MainMenu(IPetBL bl) { _petbl = bl; } public void Start(){ // Cat cat = new Cat(); bool repeat = true; do { Console.WriteLine("Welcome to Cat Manager!"); Console.WriteLine("[0] Exit"); Console.WriteLine("[1] Add a Cat"); Console.WriteLine("[2] Feed All Cats"); Console.WriteLine("[3] ViewAllCats"); switch (Console.ReadLine()) { case "0": Console.WriteLine("Good bye!"); repeat = false; break; case "1": AddACat(); break; case "2": FeedACat(); break; case "3": ViewAllCats(); break; default: Console.WriteLine("We dont understand what you're doing"); break; } }while (repeat); } private void AddACat(){ Console.WriteLine("You're adding a Cat"); } private void FeedACat(){ Console.WriteLine("You're feeding a Cat"); } private void ViewAllCats(){ Console.WriteLine("You're Viewing all Cats"); } } }
using DataLayer.Models; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; namespace DataLayer { public class ProductsDAO { //Dependencies private string connectionString; //Basic Constructor public ProductsDAO(string connString) { connectionString = connString; } public List<ProductDO> ReadAllProducts() { //Declaring local variables List<ProductDO> productList = new List<ProductDO>(); try { //Creating a new connection to the NORTHWND database and a SqlCommand using a stored procedure using (SqlConnection northwndConnection = new SqlConnection(connectionString)) using (SqlCommand readAllCommand = new SqlCommand("READ_PRODUCTS_1", northwndConnection)) { //Setting command type and opening the database connection readAllCommand.CommandType = CommandType.StoredProcedure; northwndConnection.Open(); //Creating an object to read each row of the Products table using (SqlDataReader productReader = readAllCommand.ExecuteReader()) { //Reading NORTHWND Products table the end of the table is reached while (productReader.Read()) { //Reading table data to current ProductDO ProductDO toProduct = new ProductDO(); toProduct.productID = productReader.GetInt32(0); toProduct.productName = productReader.GetString(1); toProduct.quantityPerUnit = productReader.GetString(2); toProduct.unitPrice = productReader.GetDecimal(3); toProduct.unitsInStock = productReader.GetInt16(4); toProduct.unitsOnOrder = productReader.GetInt16(5); productList.Add(toProduct); } } } } catch (Exception ex) { throw ex; } return productList; } } }
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace WarehouseService.Migrations { public partial class InitialCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Product", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Name = table.Column<string>(maxLength: 100, nullable: true), Description = table.Column<string>(maxLength: 1000, nullable: true), AvalibleQuantity = table.Column<int>(nullable: false), UnavalibleQuantity = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Product", x => x.Id); }); migrationBuilder.CreateTable( name: "StockSector", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Description = table.Column<string>(nullable: true), Active = table.Column<bool>(nullable: false), SectorType = table.Column<string>(unicode: false, maxLength: 50, nullable: false) }, constraints: table => { table.PrimaryKey("PK_StockSector", x => x.Id); }); migrationBuilder.CreateTable( name: "StockPosition", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Description = table.Column<string>(maxLength: 100, nullable: true), Street = table.Column<string>(maxLength: 30, nullable: true), Column = table.Column<string>(maxLength: 30, nullable: true), Level = table.Column<string>(maxLength: 30, nullable: true), Active = table.Column<bool>(nullable: false), Availability = table.Column<string>(unicode: false, maxLength: 50, nullable: false), StockSectorId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_StockPosition", x => x.Id); table.ForeignKey( name: "FK_StockPosition_StockSector_StockSectorId", column: x => x.StockSectorId, principalTable: "StockSector", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "InventoryMovement", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), MovementType = table.Column<int>(nullable: false), Date = table.Column<DateTime>(nullable: false), Quantity = table.Column<int>(nullable: false), Document = table.Column<string>(nullable: true), DocumentType = table.Column<string>(nullable: true), ProductId = table.Column<int>(nullable: false), StockPositionId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_InventoryMovement", x => x.Id); table.ForeignKey( name: "FK_InventoryMovement_Product_ProductId", column: x => x.ProductId, principalTable: "Product", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_InventoryMovement_StockPosition_StockPositionId", column: x => x.StockPositionId, principalTable: "StockPosition", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "StockBalance", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), ProductId = table.Column<int>(nullable: false), StockPositionId = table.Column<int>(nullable: false), Balance = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_StockBalance", x => x.Id); table.ForeignKey( name: "FK_StockBalance_Product_ProductId", column: x => x.ProductId, principalTable: "Product", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_StockBalance_StockPosition_StockPositionId", column: x => x.StockPositionId, principalTable: "StockPosition", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_InventoryMovement_ProductId", table: "InventoryMovement", column: "ProductId"); migrationBuilder.CreateIndex( name: "IX_InventoryMovement_StockPositionId", table: "InventoryMovement", column: "StockPositionId"); migrationBuilder.CreateIndex( name: "IX_StockBalance_ProductId", table: "StockBalance", column: "ProductId"); migrationBuilder.CreateIndex( name: "IX_StockBalance_StockPositionId", table: "StockBalance", column: "StockPositionId"); migrationBuilder.CreateIndex( name: "IX_StockPosition_StockSectorId", table: "StockPosition", column: "StockSectorId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "InventoryMovement"); migrationBuilder.DropTable( name: "StockBalance"); migrationBuilder.DropTable( name: "Product"); migrationBuilder.DropTable( name: "StockPosition"); migrationBuilder.DropTable( name: "StockSector"); } } }
using CodeOwls.PowerShell.Paths; using CodeOwls.PowerShell.Provider.PathNodeProcessors; using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using TreeStore.Model; namespace TreeStore.PsModule.PathNodes { /// <summary> /// Categorizes a set of <see cref="EntityNode"/>. Has no accessible properties ecept the C# ones. /// </summary> public sealed class CategoryNode : ContainerNode, IGetChildItem, INewItem, IRemoveItem, ICopyItem, IRenameItem, IMoveItem { public sealed class Item { private Category category; public Item(Category category) { this.category = category; } public Guid Id => this.category.Id; public string Name => this.category.Name; public TreeStoreItemType ItemType => TreeStoreItemType.Category; } private readonly Category category; public CategoryNode(Category category) { this.category = category; } public Guid Id => this.category.Id; public override string Name => this.category.Name; #region PathNode public override IEnumerable<PathNode> Resolve(IProviderContext providerContext, string nodeName) { var persistence = providerContext.Persistence(); IEnumerable<PathNode> categories() => SubCategory(persistence, nodeName) .Yield() .Select(c => new CategoryNode(c)); IEnumerable<PathNode> entities() => SubEntity(persistence, nodeName) .Yield() .Select(e => new EntityNode(e)); return categories().Union(entities()); } #endregion PathNode #region IGetItem public override PSObject GetItem(IProviderContext providerContext) => PSObject.AsPSObject(new Item(this.category)); #endregion IGetItem #region IGetChildItem override public IEnumerable<PathNode> GetChildNodes(IProviderContext context) { var persistence = context.Persistence(); IEnumerable<PathNode> entities() => SubEntities(persistence).Select(e => new EntityNode(e)); IEnumerable<PathNode> categories() => SubCategories(persistence).Select(c => new CategoryNode(c)); return categories().Union(entities()); } #endregion IGetChildItem #region INewItem public object NewItemParameters => new RuntimeDefinedParameterDictionary(); public IEnumerable<string> NewItemTypeNames { get; } = new[] { nameof(TreeStoreItemType.Category), nameof(TreeStoreItemType.Entity) }; public PathNode NewItem(IProviderContext providerContext, string newItemName, string itemTypeName, object newItemValue) { Guard.Against.InvalidNameCharacters(newItemName, $"category(name='{newItemName}' wasn't created"); Guard.Against.InvalidReservedNodeNames(newItemName, $"category(name='{newItemName}' wasn't created"); switch (itemTypeName ?? nameof(TreeStoreItemType.Entity)) { case nameof(TreeStoreItemType.Category): return NewCategory(providerContext, newItemName); case nameof(TreeStoreItemType.Entity): return NewEntity(providerContext, newItemName); default: throw new InvalidOperationException($"ItemType '{itemTypeName}' not allowed in the context"); } } private PathNode NewCategory(IProviderContext providerContext, string newItemName) { var persistence = providerContext.Persistence(); if (SubCategory(persistence, newItemName) is { }) { throw new InvalidOperationException($"Name is already used by and item of type '{nameof(TreeStoreItemType.Category)}'"); } if (SubEntity(persistence, newItemName) is { }) { throw new InvalidOperationException($"Name is already used by and item of type '{nameof(TreeStoreItemType.Entity)}'"); } var subCategory = new Category(newItemName); this.category.AddSubCategory(subCategory); return new CategoryNode(persistence.Categories.Upsert(subCategory)); } private PathNode NewEntity(IProviderContext providerContext, string newItemName) { var persistence = providerContext.Persistence(); if (SubCategory(persistence, newItemName) is { }) { throw new InvalidOperationException($"Name is already used by and item of type '{nameof(TreeStoreItemType.Category)}'"); } if (SubEntity(persistence, newItemName) is { }) { throw new InvalidOperationException($"Name is already used by and item of type '{nameof(TreeStoreItemType.Entity)}'"); } var entity = new Entity(newItemName) { Category = this.category }; //todo: create entity with tag //switch (providerContext.DynamicParameters) //{ // case NewItemParametersDefinition d when d.Tags.Any(): // foreach (var tag in d.Tags.Select(t => Tag(persistence, t)).Where(t => t != null)) // { // entity.AddTag(tag!); // } // break; //} return new EntityNode(providerContext.Persistence().Entities.Upsert(entity)); } #endregion INewItem #region ICopyItem public object CopyItemParameters => new RuntimeDefinedParameterDictionary(); public void CopyItem(IProviderContext providerContext, string sourceItemName, string destinationItemName, PathNode destinationNode) { if (destinationItemName != null) Guard.Against.InvalidNameCharacters(destinationItemName, $"category(name='{destinationItemName}' wasn't created"); var persistence = providerContext.Persistence(); Category? parent = null;//newCategory = new Category(destinationItemName ?? sourceItemName); if (destinationNode is EntitiesNode) { // dont add the category yet to its parent parent = persistence.Categories.Root(); } else if (destinationNode is CategoryNode containerProvider) { parent = persistence.Categories.FindById(containerProvider.Id); } this.EnsureUniqueDestinationName(persistence, parent!, destinationItemName ?? sourceItemName); persistence.CopyCategory(this.category, parent!, providerContext.Recurse); } #endregion ICopyItem #region IRemoveItem public object RemoveItemParameters => new RuntimeDefinedParameterDictionary(); public void RemoveItem(IProviderContext providerContext, string path) { providerContext.Persistence().DeleteCategory(this.category, providerContext.Recurse); } #endregion IRemoveItem #region IRenameItem public object RenameItemParameters => new RuntimeDefinedParameterDictionary(); public void RenameItem(IProviderContext providerContext, string path, string newName) { Guard.Against.InvalidNameCharacters(newName, $"category(name='{newName}' wasn't renamed"); // this is explicitely not case insensitive. Renaming to different cases is allowed, // even if it has no effect to the the identification by name. if (this.category.Name.Equals(newName)) return; var persistence = providerContext.Persistence(); if (this.SiblingCategory(persistence, newName) is { }) return; if (this.SiblingEntity(persistence, newName) is { }) return; this.category.Name = newName; persistence.Categories.Upsert(this.category); } #endregion IRenameItem #region IMoveItem public object MoveItemParameters => new RuntimeDefinedParameterDictionary(); public void MoveItem(IProviderContext providerContext, string path, string? movePath, PathNode destinationNode) { if (destinationNode is CategoryNode categoryNode) { var persistence = providerContext.Persistence(); var destinationCategory = persistence.Categories.FindById(categoryNode.Id); var movePathResolved = movePath ?? this.category.Name; if (SubCategory(persistence, destinationCategory, movePathResolved) is { }) throw new InvalidOperationException($"Destination container contains already a category with name '{movePathResolved}'"); if (SubEntity(persistence, destinationCategory, movePathResolved) is { }) throw new InvalidOperationException($"Destination container contains already an entity with name '{movePathResolved}'"); this.category.Name = movePathResolved; destinationCategory.AddSubCategory(this.category); persistence.Categories.Upsert(this.category); } } #endregion IMoveItem #region Model Accessors private void EnsureUniqueDestinationName(ITreeStorePersistence persistence, Category category, string destinationName) { if (SubCategory(persistence, category, destinationName) is { }) throw new InvalidOperationException($"Destination container contains already a category with name '{destinationName}'"); if (SubEntity(persistence, category, destinationName) is { }) throw new InvalidOperationException($"Destination container contains already an entity with name '{destinationName}'"); } private IEnumerable<Entity> SubEntities(ITreeStorePersistence persistence) => persistence.Entities.FindByCategory(this.category); private Category? SubCategory(ITreeStorePersistence persistence, string name) => this.SubCategory(persistence, parentCategeory: this.category, name); private Category? SubCategory(ITreeStorePersistence persistence, Category parentCategeory, string name) => persistence.Categories.FindByParentAndName(parentCategeory, name); private IEnumerable<Category> SubCategories(ITreeStorePersistence persistence) => persistence.Categories.FindByParent(this.category); private Category? SiblingCategory(ITreeStorePersistence persistence, string name) => this.category.Parent switch { Category p when p != null => persistence.Categories.FindByParentAndName(p, name), _ => null }; private Entity? SiblingEntity(ITreeStorePersistence persistence, string name) => persistence.Entities.FindByCategoryAndName(this.category.Parent!, name); private Entity? SubEntity(ITreeStorePersistence persistence, string name) => this.SubEntity(persistence, parentCategory: this.category, name); private Entity? SubEntity(ITreeStorePersistence persistence, Category parentCategory, string name) => persistence.Entities.FindByCategoryAndName(parentCategory, name); private Tag? Tag(ITreeStorePersistence persistence, string name) => persistence.Tags.FindByName(name); #endregion Model Accessors } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace COM3D2.SimpleUI.Implementation { public interface ILayoutComponent { GameObject gameObject { get; } Vector2 position { get; } Vector2 size { get; } void SetSize(Vector2 size, bool triggerLayout); void SetPosition(Vector2 size, bool triggerLayout); void Init(BaseLayout parent); string Name { get; } bool Visible { get; } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // namespace DotNetNuke.HttpModules.RequestFilter { public enum RequestFilterRuleType { Redirect, PermanentRedirect, NotFound } public enum RequestFilterOperatorType { Equal, NotEqual, Regex } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Labra4 { public class Radio { private int VolumeApu; private int Volumemin = 0; private int Volumemax = 9; public bool Päällä { get; set; } public int Voimakkuus { get { return VolumeApu; } set { if (value < Volumemin) value = Volumemin; if (value > Volumemax) value = Volumemax; VolumeApu = value; } } private double TaajuusApu = 990; private double Taajuusmin = 2000.0; public double Taajuusmax = 26000.0; public double Taajuus {get { return TaajuusApu; } set { if (value < Taajuusmin) value = Taajuusmin; if (value > Taajuusmax) value = Taajuusmax; TaajuusApu = value; } } public Radio() { } public override string ToString() { return "Päällä: " + Päällä + " Äänenvoimakkuus: " + Voimakkuus + " Taajuus: " + Taajuus; } } }
using System; using System.Collections.Generic; using System.Text; /** * * name : IMemberRepositories.cs * author : Aleksy Ruszala * date : 29/04/2019 * * */ namespace Application.Repo.Contracts { interface IMemberRepositories { } }
namespace SFA.DAS.Notifications.Infrastructure.Configuration { public class NotificationServiceConfiguration { public string NotificationServiceApiKey { get; set; } public string DatabaseConnectionString { get; set; } public SmtpConfiguration SmtpConfiguration { get; set; } public NServiceBusConfiguration NServiceBusConfiguration { get; set; } public string EmailService { get; set; } } }
using UnityEngine; using UnityEditor; using System.Collections; [ExecuteInEditMode] [System.Serializable] public class SimpleChainConstraintCS : MonoBehaviour { [SerializeField] private float minDistance = 0.5f; [SerializeField] private float maxDistance = 2.0f; // smooth the chain element's position corrections [SerializeField] private bool smoothSolve; // time the smoothing interpolation should take [SerializeField] private float smoothTime = 1.0f; [SerializeField] private Transform[] chainElements; void LateUpdate() { // go through the chain and solve for position giving priority to the parent. // solve Transform prevTransform = transform; foreach (Transform trfrm in chainElements) { float distance = Vector3.Distance(prevTransform.position, trfrm.position); Vector3 childDir = trfrm.position - prevTransform.position; childDir.Normalize(); } // indicate the possible distances for the elemen foreach (Transform trfrm in chainElements) { float distance = Vector3.Distance(prevTransform.position, trfrm.position); Vector3 childDir = trfrm.position - prevTransform.position; childDir.Normalize(); if (distance > maxDistance) { trfrm.position = prevTransform.position + childDir * maxDistance; } else if(distance < minDistance) { trfrm.position = prevTransform.position + childDir * minDistance; } Vector3 minDistancePos = prevTransform.position + childDir * minDistance; Vector3 maxDistancePos = childDir * (maxDistance - minDistance) + minDistancePos; Debug.DrawLine(prevTransform.position, minDistancePos, Color.red); Debug.DrawLine(minDistancePos, maxDistancePos, Color.green); if (distance > maxDistance) Debug.DrawLine(maxDistancePos, trfrm.position, Color.red); prevTransform = trfrm; } } } /* [CustomEditor(typeof(SimpleChainConstraintCS))] [CanEditMultipleObjects] class SimpleChainConstraintEditor : Editor { SerializedProperty minDistanceProp; SerializedProperty maxDistanceProp; SerializedProperty smoothSolveProp; SerializedProperty smoothTimeProp; void OnEnable() { // Setup the serializedProperties minDistanceProp = serializedObject.FindProperty("minDistance"); maxDistanceProp = serializedObject.FindProperty("maxDistance"); smoothSolveProp = serializedObject.FindProperty("smoothSolve"); smoothTimeProp = serializedObject.FindProperty("smoothTime"); } public override void OnInspectorGUI() { serializedObject.Update(); FloorPrefabCS fbp = target as FloorPrefabCS; EditorGUILayout.PropertyField(sizeProp, new GUIContent("Size", "Change width and length of the floor prefab")); EditorGUILayout.PropertyField(borderSizeProp, new GUIContent("Border Size", "Change width and height of the border")); EditorGUILayout.PropertyField(floorMaterial, new GUIContent("Floor Material", "Change the material to spread on the floor")); EditorGUILayout.Space(); serializedObject.ApplyModifiedProperties(); // force an update fbp.UpdateSettings(); } } */
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PlayTennis.Model.Dto { public class PurposeCommunicationDto { public UserInformation UserInformation { get; set; } public IList<PurposeCommunication> PurposeCommunications { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace GUI.GUI { public partial class Login : Form { public Login() { InitializeComponent(); } private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e) { } private void btnLogin_Click_1(object sender, EventArgs e) { string taikhoan = txtUser.Text; if (taikhoan == "") { MessageBox.Show("\n Bạn cần nhập tên tai khoản", "MessageBoxButtons.OK"); txtUser.Focus(); return; } string mk = txtPass.Text; if (mk == "") { MessageBox.Show("\n Bạn cần nhâp mật khẩu"); txtPass.Focus(); return; } SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-TTFTRF5\MSSQLSERVER1;Initial Catalog=QLNhaTro;Integrated Security=True"); try { con.Open(); string tentk = txtUser.Text; string matk = txtPass.Text; string cl = "select * from login where password='" + txtPass.Text + "'and username='" + txtUser.Text + "'"; SqlCommand cm = new SqlCommand(cl, con); SqlDataReader dar = cm.ExecuteReader(); if (dar.Read() == true) { MessageBox.Show("\n Đăng nhập thành công!"); Home trangchu = new Home(); trangchu.Show(); } else { MessageBox.Show("\n Ban nhap sai mat khau hoac ten tai khoan"); } } catch { MessageBox.Show("\n loi ket noi"); } finally { con.Close(); } } private void btnReset_Click_1(object sender, EventArgs e) { txtUser.Clear(); txtPass.Clear(); txtUser.Focus(); } private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e) { } private void button1_Click(object sender, EventArgs e) { } } }
using JekossTest.Dal.Common; using JekossTest.Dal.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace JekossTest.Dal.Configurations { public class RoleConfiguration : DbEntityConfiguration<Role> { public override void Configure(EntityTypeBuilder<Role> entity) { entity.ToTable("Role"); entity.HasIndex(x => x.Id); entity.HasMany(x => x.Users).WithOne(x => x.Role).HasForeignKey(x => x.RoleId); } } }
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game; using Triton.Game.Mono; [Attribute38("AssetBundleInfo")] public class AssetBundleInfo : MonoClass { public AssetBundleInfo(IntPtr address) : this(address, "AssetBundleInfo") { } public AssetBundleInfo(IntPtr address, string className) : base(address, className) { } public static string BundlePathPlatformModifier() { return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "AssetBundleInfo", "BundlePathPlatformModifier", Array.Empty<object>()); } public static int NUM_ACTOR_BUNDLES { get { return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "AssetBundleInfo", "NUM_ACTOR_BUNDLES"); } } public static int NUM_BUNDLES_DEFAULT { get { return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "AssetBundleInfo", "NUM_BUNDLES_DEFAULT"); } } public static int NUM_CARD_BUNDLES { get { return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "AssetBundleInfo", "NUM_CARD_BUNDLES"); } } public static int NUM_CARDBACKS_BUNDLES { get { return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "AssetBundleInfo", "NUM_CARDBACKS_BUNDLES"); } } public static int NUM_CARDTEXTURES_BUNDLES { get { return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "AssetBundleInfo", "NUM_CARDTEXTURES_BUNDLES"); } } public static int NUM_DOWNLOADABLE_SOUND_LOCALE_BUNDLES { get { return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "AssetBundleInfo", "NUM_DOWNLOADABLE_SOUND_LOCALE_BUNDLES"); } } public static int NUM_DOWNLOADABLE_SPELL_LOCALE_BUNDLES { get { return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "AssetBundleInfo", "NUM_DOWNLOADABLE_SPELL_LOCALE_BUNDLES"); } } public static int NUM_GAMEOBJECTS_BUNDLES { get { return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "AssetBundleInfo", "NUM_GAMEOBJECTS_BUNDLES"); } } public static int NUM_MOVIE_BUNDLES { get { return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "AssetBundleInfo", "NUM_MOVIE_BUNDLES"); } } public static int NUM_PREMIUMMATERIALS_BUNDLES { get { return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "AssetBundleInfo", "NUM_PREMIUMMATERIALS_BUNDLES"); } } public static int NUM_SOUND_BUNDLES { get { return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "AssetBundleInfo", "NUM_SOUND_BUNDLES"); } } public static int NUM_SOUNDPREFAB_BUNDLES { get { return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "AssetBundleInfo", "NUM_SOUNDPREFAB_BUNDLES"); } } public static int NUM_SPELL_BUNDLES { get { return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "AssetBundleInfo", "NUM_SPELL_BUNDLES"); } } public static int NumSharedDependencyBundles { get { return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "AssetBundleInfo", "NumSharedDependencyBundles"); } } public static string SharedBundleName { get { return MonoClass.smethod_8(TritonHs.MainAssemblyPath, "", "AssetBundleInfo", "SharedBundleName"); } } public static bool UseSharedDependencyBundle { get { return MonoClass.smethod_6<bool>(TritonHs.MainAssemblyPath, "", "AssetBundleInfo", "UseSharedDependencyBundle"); } } } }
using System; using System.Collections.Generic; using System.Linq; using ETravel.Coffee.DataAccess.Interfaces; using Order = ETravel.Coffee.DataAccess.Entities.Order; namespace ETravel.Coffee.DataAccess.Repositories { public class OrdersRepository : Repository, IOrdersRepository { public virtual IList<Order> All() { return Session .CreateCriteria<Order>() .List<Order>() .OrderBy(x => x.ExpiresAt) .Reverse() .ToList(); } public virtual void Save(Order order) { Session.Save(order); Session.Flush(); } public virtual void Update(Order order) { Session.Update(order); Session.Flush(); } public virtual void Delete(Guid id) { Session.Delete(GetById(id)); Session.Flush(); } public virtual Order GetById(Guid id) { return Session.Get<Order>(id); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using CT.Data; using CT.Manager; namespace CT.UI { public class InteractGridManager : GridManager { public override Color NowBuildingHereColor => tileValidColor; public override Color StartBuildingHereColor => tileValidColor; public override Color ConstructionHereColor => tileValidColor; public UpgradeUIManager UpgradeUIManager { get; private set; } public ConstructionUIManager ConstructionUIManager { get; private set; } public Building SelectedBuilding { get; private set; } public Construction SelectedConstruction { get; private set; } public static InteractGridManager instance; InteractManager manager; public InteractGridManager() { instance = this; } void Start() { manager = InteractManager.instance; UpgradeUIManager = UpgradeUIManager.instance; ConstructionUIManager = ConstructionUIManager.instance; } void OnEnable() { if (grid != null) DestroyGrid(); GenerateGrid(); } void BuildingClicked(Building building) { switch (manager.interactMode) { case InteractManager.InteractMode.Interact: building.OnInteract(); break; case InteractManager.InteractMode.Upgrade: building.OnUpgradeUISelected(); break; } } void NewConstructionClicked(Construction construction) { //construction.OnInteract(); ConstructionUIManager.Init(construction); SelectedConstruction = construction; } public override void OnTileClicked(int x, int y) { var tile = grid[x, y]; var building = SelectedBuilding = tile.Building; var construction = (SelectedConstruction = tile.Construction); if (building == null) { if (construction == null) return; NewConstructionClicked(construction); return; } if (construction == null) BuildingClicked(building); else building.OnUpgradeUISelected(); } public void Deactivate() { //if (gameObject == null) return; //if (!gameObject.activeSelf) return; SelectedBuilding = null; if(grid != null) DestroyGrid(); if (UpgradeUIManager != null) UpgradeUIManager.TurnOff(); if (ConstructionUIManager != null) ConstructionUIManager.TurnOff(); if(gameObject != null) gameObject.SetActive(false); } public void OnUpgrade() { //Deactivate(); may do } } }
using System.Collections.Generic; using System.Threading.Tasks; using StoreDB.Models; using StoreDB.Repos; namespace StoreLib { public class ProductService { private IProductRepo repo; public ProductService(IProductRepo repo) { this.repo = repo; } public List<string> GetProductList() { List<string> productList = new List<string>(); Task<List<Product>> productListTask = repo.GetAllProductsAsync(); foreach(Product product in productListTask.Result) { productList.Add($"[{product.ProductId}] {product.Name} ({product.Price.ToString("C")})"); } return productList; } public Product GetProductById(int productId) { return repo.GetProductById(productId); } public List<string> ViewCart(Dictionary<int, int> cart, out decimal subtotal) { List<string> cartList = new List<string>(); subtotal = 0; foreach(KeyValuePair<int, int> item in cart) { Product cartItem = repo.GetProductById(item.Key); cartList.Add($" {item.Value} x ({cartItem.Name} @ {cartItem.Price.ToString("C")}/unit) = {(cartItem.Price * item.Value).ToString("C")}"); subtotal += cartItem.Price * item.Value; } cartList.Add("--------------------"); cartList.Add($"Subtotal: {subtotal.ToString("C")}"); return cartList; } public List<string> ViewProductsToStock(Dictionary<int, int> productsToStock) { decimal subtotal = 0; List<string> productList = new List<string>(); foreach(KeyValuePair<int, int> item in productsToStock) { Product product = repo.GetProductById(item.Key); productList.Add($" {item.Value} x ({product.Name} @ {product.Price.ToString("C")}/unit) = {(product.Price * item.Value).ToString("C")}"); subtotal += product.Price * item.Value; } productList.Add("--------------------"); productList.Add($"Subtotal: {subtotal.ToString("C")}"); return productList; } public List<string> ViewProductStockByLocation(int locationId, out Dictionary<int, int> menuMapping) { List<string> productStockList = new List<string>(); menuMapping = new Dictionary<int, int>(); Task<List<ProductStock>> productStockListTask = repo.GetProductStockByLocation(locationId); foreach(ProductStock productStock in productStockListTask.Result) { productStockList.Add($"[{menuMapping.Count}] {productStock.Product.Name} ({productStock.Product.Price.ToString("C")}): {productStock.QuantityStocked} in stock"); menuMapping.Add(menuMapping.Count, productStock.Product.ProductId); } return productStockList; } public List<string> ViewProductStockByProductId(int productId, out Dictionary<int, int> menuMapping) { List<string> productStockList = new List<string>(); menuMapping = new Dictionary<int, int>(); Task<List<ProductStock>> productStockListTask = repo.GetProductStockByProductId(productId); foreach(ProductStock productStock in productStockListTask.Result) { productStockList.Add($"[{menuMapping.Count}] {productStock.QuantityStocked} in stock at {productStock.Location.Name} ({productStock.Location.Address})"); menuMapping.Add(menuMapping.Count, productStock.Location.LocationId); } return productStockList; } public void UpdateProductStocks(int locationId, Dictionary<int, int> cart, bool isManager) { foreach(KeyValuePair<int, int> item in cart) { repo.UpdateProductStock(locationId, item.Key, isManager ? item.Value : item.Value * -1); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; //////////////////////////////////////////////////////////////////////////////// // *** A callback is never published. It’s private, and the method that’s *** // // *** doing the calling keeps tight control over who it’s calling. *** // //////////////////////////////////////////////////////////////////////////////// namespace Baseball { // We need to let the one Ball that’s being pitched hook itself up to the Bat, but we // need to do it in a way that doesn’t allow any other Ball objects to hook themselves up. // // That’s where a callback comes in handy. It’s a technique that you can use with delegates. // // Instead of exposing an event (OnBallInPlay) that anyone can subscribe to, // an object uses a method (often a constructor) that takes a delegate as an // argument and holds onto that delegate in a private field. We’ll use a // callback to make sure that the Bat notifies exactly one Ball: delegate void BatCallback(BallEventArgs e); }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using MonoGame.Extended; using MonoGame.Extended.BitmapFonts; using MonoGame.Extended.ViewportAdapters; namespace Demo.BitmapFonts { public class Game1 : Game { private Texture2D _backgroundTexture; private BitmapFont _bitmapFont; private Camera2D _camera; // ReSharper disable once NotAccessedField.Local private GraphicsDeviceManager _graphicsDeviceManager; private Vector2 _labelPosition = Vector2.Zero; private string _labelText = ""; private SpriteBatch _spriteBatch; private ViewportAdapter _viewportAdapter; public Game1() { _graphicsDeviceManager = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; IsMouseVisible = true; Window.AllowUserResizing = true; //Window.Position = Point.Zero; } protected override void LoadContent() { _viewportAdapter = new BoxingViewportAdapter(Window, GraphicsDevice, 800, 480); _camera = new Camera2D(_viewportAdapter); _backgroundTexture = Content.Load<Texture2D>("vignette"); _bitmapFont = Content.Load<BitmapFont>("montserrat-32"); _spriteBatch = new SpriteBatch(GraphicsDevice); } protected override void UnloadContent() { } protected override void Update(GameTime gameTime) { var keyboardState = Keyboard.GetState(); var mouseState = Mouse.GetState(); //if (keyboardState.IsKeyDown(Keys.Escape)) //{ // Exit(); //} _labelText = $"{mouseState.X}, {mouseState.Y}"; var stringRectangle = _bitmapFont.GetStringRectangle(_labelText, Vector2.Zero); _labelPosition = new Vector2(400 - stringRectangle.Width / 2, 440); base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); _spriteBatch.Begin(transformMatrix: _camera.GetViewMatrix()); _spriteBatch.Draw(_backgroundTexture, _viewportAdapter.BoundingRectangle, Color.White); _spriteBatch.DrawString(_bitmapFont, "MonoGame.Extended BitmapFont Sample", new Vector2(50, 10), Color.White); _spriteBatch.DrawString(_bitmapFont, "Contrary to popular belief, Lorem Ipsum is not simply random text.\n\n" + "It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard " + "McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin " + "words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, " + "discovered the undoubtable source.", new Vector2(50, 50), new Color(Color.Black, 0.5f), 750); _spriteBatch.DrawString(_bitmapFont, _labelText, _labelPosition, Color.Black); _spriteBatch.End(); base.Draw(gameTime); } } }
using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using ProtocolCS; using ProtocolCS.Constants; using GSF; using GSF.Concurrency; namespace Server.Ingame { using AI; class GameProcessor { public List<IngameEvent> eventBuffer { get; set; } public int currentFrameNo { get; set; } public int seed { get; private set; } public IngameService[] players { get; private set; } /// <summary> /// 플레이어 다나가고, 봇만 남아있는 좀비방인지 /// </summary> public bool isZombieGame { get { return players.Length == botPlayerCount; } } private BoundTask boundTask { get; set; } private ConcurrentSet<int> eventArrived { get; set; } private int eventArrivedCount; private ConcurrentBag<Frame> frameBuffer { get; set; } private int lastFrameTick; private int botPlayerCount; public GameProcessor(IngameService[] players) { this.players = players; this.eventArrived = new ConcurrentSet<int>(); this.eventBuffer = new List<IngameEvent>(); this.boundTask = new BoundTask(); this.frameBuffer = new ConcurrentBag<Frame>(); this.currentFrameNo = 0; this.seed = 0; this.lastFrameTick = Environment.TickCount; } public bool AddEvent(int playerId, IngameEvent ev){ bool lastPlayer = Interlocked.Increment(ref eventArrivedCount) == players.Length - botPlayerCount; if (eventArrived.TryAdd(playerId) == false) throw new InvalidOperationException("already has events"); boundTask.Run(() => eventBuffer.Add(ev)); if (lastPlayer) return true; return false; } public bool AddEvents(int playerId, IEnumerable<IngameEvent> ev) { bool lastPlayer = Interlocked.Increment(ref eventArrivedCount) == players.Length - botPlayerCount; if (eventArrived.TryAdd(playerId) == false) throw new InvalidOperationException("already has events"); boundTask.Run(() => eventBuffer.AddRange(ev)); if (lastPlayer) return true; return false; } public void ToAutoPlayer(int playerId) { Interlocked.Increment(ref botPlayerCount); boundTask.Run(() => { for (int i=0;i<players.Length;i++) { if (players[i].UserId == playerId) players[i] = AutoPlayer.MigrateFrom(players[i]); } }); } /// <summary> /// 현재 프레임을 끝내고, 다음 프레임을 준비한다. /// </summary> /// <returns>이번 프레임에서 발행한 이벤트들</returns> public async Task<IngameEvent[]> Step() { frameBuffer.Add(new Frame() { frameNo = currentFrameNo, events = eventBuffer.ToArray() }); eventArrived.Clear(); Interlocked.Exchange(ref eventArrivedCount, 0); currentFrameNo++; var delay = FrameRate.Interval - (Environment.TickCount - lastFrameTick); if (delay > 0) await Task.Delay(delay); lastFrameTick = Environment.TickCount; return await boundTask.Run(() => { foreach(var player in players) { if (player.isBotPlayer) eventBuffer.AddRange(((AutoPlayer)player).ProcessTurn()); } var events = eventBuffer.ToArray(); eventBuffer.Clear(); return events; }); } public Frame[] GetPreviousFrames() { // ****TODO**** : LOCK Frame[] ary = new Frame[currentFrameNo]; frameBuffer.CopyTo(ary, 0); return ary; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class ajax : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string action = string.Empty; action = Request["action"] != null ? Request["action"] : string.Empty; switch (action) { case "getData": getData(); break; case "deleteData": deleData(); break; default: break; } } private void deleData() { Response.Write("{ \"success\":true, \"allowDelete\": true}"); Response.End(); } private void getData() { StringBuilder json = new StringBuilder(); json.Append("["); for (int i = 1; i < 100; i++) { json.Append("{\"id\":\"" + i+ "\",\"label\":\"" + Request["term"].ToString()+ "--peng--" + i+ "\",\"value\":\"" + Request["term"].ToString() + "--peng--" + i + "\"}"); if (i <99) { json.Append(","); } } json.Append("]"); Response.Write(json.ToString()); Response.End(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BerlinClock.Classes.Time { public interface IBerlinTime { string ReturnBerlinPointer(string time); } }
using Code; using NUnit.Framework; using Rhino.Mocks; namespace Tests { class AutomaticUmbrellaTests { private IWetWeather _mockRain; private AutomaticUmbrella _umbrella; [SetUp] public void Init() { _mockRain = MockRepository.GenerateMock<IWetWeather>(); _umbrella = new AutomaticUmbrella {WetWeather = _mockRain}; // create a mockHail then uncomment the line below //_sturdyUmbrella = new AutomaticUmbrella {WetWeather = _mockHail}; } [Test] public void Should_OpenWhenWeatherIsWet() { _mockRain.Stub(x => x.IsOccuring()).Return(true); Assert.That(_umbrella.IsOpen, Is.EqualTo(true)); } [Test] public void Should_CloseWhenWetherIsNotWet() { // stub the rain so that when the umbrella it recieves the message IsOccuring it returns false // assert that the umbrella is not open (is open equals false) } // Write a test that tests that the sturdy umbrella opens when it's hailing } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace GetLabourManager.Models { public class GangSheetItems { public int Id { get; set; } public string StaffCode { get; set; } public int Group { get; set; } public int Category { get; set; } public int Header { get; set; } [ForeignKey("Header")] public GangSheetHeader SheetHeader { get; set; } public int AllocationId { get; set; } } }
using UnityEngine; using System.Collections.Generic; using System; using System.Linq; public class DisplayController: MonoBehaviour { public float cycleTime = 10f; public ScreenList screenList; public static int instagramTimeFilter = 72; public static int twitterTimeFilter = 72; private GameObject _displayContainer; private IDisplayManager _currentDisplayManager; private float _lastCycleTime = 0f; private bool _cyclingDisplay = false; private bool _readyToCycle = false; private bool _initialized = false; public void Initialize(GameObject displayContainer) { _displayContainer = displayContainer; Preloader.instance.ResetDisplayIndex (); _currentDisplayManager = GetCurrentDisplayManager (); //if none of the tags are supported we have to prevent initialization and show a message or something if (_currentDisplayManager == null) { //TODO SHOW UNSUPPORTED MESSAGE } else { _currentDisplayManager.gameObject.SetActive (true); _currentDisplayManager.InitializeDisplay (Preloader.instance.GetRunningDisplayId()); _cyclingDisplay = false; _lastCycleTime = Time.time; _initialized = true; } } public void FinalizeController() { if (_initialized) { _currentDisplayManager.FinalizeDisplay (); _currentDisplayManager.gameObject.SetActive (false); } _displayContainer.SetActive (false); screenList.gameObject.SetActive (true); _initialized = false; Cursor.visible = true; Preloader.instance.CancelUpdate (); //Preloader.instance.ResetVideoPool(); gameObject.SetActive (false); } // Update is called once per frame void Update () { if (Input.GetKeyDown (KeyCode.Backspace)) { FinalizeController(); } // TODO Should be somewhere else ? Also useless? if (Input.GetKeyDown (KeyCode.Escape)) { Application.Quit(); } //If the controller was not initialized we wont do any of what follows if (!_initialized) return; _readyToCycle = (_currentDisplayManager.timeDriven && Time.time - _lastCycleTime > _currentDisplayManager.cycleTime) || (!_currentDisplayManager.timeDriven && _currentDisplayManager.readyToCycle) || _currentDisplayManager.forceCycle; if (_readyToCycle) { //if we are on video Display and the next one is a video display too if (_currentDisplayManager is VideoDisplayManager && Preloader.instance.GetNextDisplayType() == DisplayType.VIDEO) { // Add 1 to the current index and initialize the next display Preloader.instance.SetNextDisplayIndex(); (_currentDisplayManager as VideoDisplayManager).AddNextVideo(Preloader.instance.GetRunningDisplayId()); _cyclingDisplay = false; _lastCycleTime = Time.time; } else { if (!_cyclingDisplay && !_currentDisplayManager.forceCycle) { if (_currentDisplayManager is PhotographyDisplayManager && Preloader.instance.GetNextDisplayType() == DisplayType.VIDEO) { (_currentDisplayManager as PhotographyDisplayManager).SetAuxPhoto(); } else if (_currentDisplayManager is VideoDisplayManager && Preloader.instance.GetNextDisplayType() == DisplayType.PHOTOGRAPHY) { (_currentDisplayManager as VideoDisplayManager).SetAuxPhoto(Preloader.instance.GetNextDisplayFirstPhoto()); } //Start the out animation for every avaialable display animator foreach (Animator displayAnimator in _currentDisplayManager.animators) { if (displayAnimator.gameObject.activeSelf) { displayAnimator.SetTrigger("DisplayOut"); } } _currentDisplayManager.DisplayOut(); _cyclingDisplay = true; } else { bool stillCycling = false; stillCycling = !_currentDisplayManager.DisplayOutFinished; if (!stillCycling && !_currentDisplayManager.forceCycle) { //We check in every display animator if the out animation finished foreach (Animator displayAnimator in _currentDisplayManager.animators) { if (displayAnimator.gameObject.activeSelf) { if (!displayAnimator.GetCurrentAnimatorStateInfo(0).IsName("DisplayOut")) { stillCycling = true; } else if (displayAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime < 1f) { stillCycling = true; } } } } //For now we just call the same display in animation if (!stillCycling) { // Finalize and de activate the current display _currentDisplayManager.FinalizeDisplay(); _currentDisplayManager.gameObject.SetActive(false); // Add 1 to the current index and initialize the next display Preloader.instance.SetNextDisplayIndex(); _currentDisplayManager = GetCurrentDisplayManager(); if (_currentDisplayManager == null) { _initialized = false; return; } _currentDisplayManager.gameObject.SetActive(true); //Here we should send the right display id to retreive the right data _currentDisplayManager.InitializeDisplay(Preloader.instance.GetRunningDisplayId()); _cyclingDisplay = false; _lastCycleTime = Time.time; } } } } } private IDisplayManager GetCurrentDisplayManager() { int tries = 0; do { IDisplayManager displayManager = GetDisplayManager(Preloader.instance.GetRunningDisplayType()); Preloader.instance.UpdateDisplayList(); if(Preloader.instance.IsLastDisplay()) { Preloader.instance.UpdateRunningDisplayListData(); } if(displayManager != null) { return displayManager; } else { Preloader.instance.SetNextDisplayIndex(); tries++; } }while(tries < Preloader.instance.GetDisplayListLength()); return null; } private IDisplayManager GetDisplayManager(string tag) { switch (tag) { case DisplayType.TWITTER: if(!Preloader.instance.HasTexts(Preloader.instance.GetRunningDisplay (), twitterTimeFilter)) { return null; } return _displayContainer.GetComponentsInChildren<TwitterDisplayManager>(true).FirstOrDefault(); case DisplayType.WORDCLOUD: return _displayContainer.GetComponentsInChildren<WordcloudDisplayManager>(true).FirstOrDefault(); case DisplayType.INSTAGRAM: if(!Preloader.instance.HasTexts (Preloader.instance.GetRunningDisplay (), instagramTimeFilter)) { return null; } return _displayContainer.GetComponentsInChildren<InstagramDisplayManager>(true).FirstOrDefault(); case DisplayType.PHOTOGRAPHY: if(!Preloader.instance.HasPhotos(Preloader.instance.GetRunningDisplay())) { return null; } return _displayContainer.GetComponentsInChildren<PhotographyDisplayManager>(true).FirstOrDefault(); case DisplayType.VIDEO: if(Preloader.instance.GetVideoPath(Preloader.instance.GetRunningDisplay()) == "") { return null; } return _displayContainer.GetComponentsInChildren<VideoDisplayManager>(true).FirstOrDefault(); case DisplayType.COUNTDOWN: if(IsCountdownTimeNegative(DateTime.Parse (Preloader.instance.GetString (Preloader.instance.GetRunningDisplay(), "time")))) { return null; } return _displayContainer.GetComponentsInChildren<CountdownDisplayManager>(true).FirstOrDefault(); case DisplayType.INFLUENCERS: return _displayContainer.GetComponentsInChildren<InfluencersDisplayManager>(true).FirstOrDefault(); case DisplayType.DEMOGRAPHIC: return _displayContainer.GetComponentsInChildren<DemographicDisplayManager>(true).FirstOrDefault(); default: //TODO What to do here? return null; } } private bool IsCountdownTimeNegative(DateTime conferenceTime) { // The -1 is a hack to be revised since for some reason time is coming with an extra hour from the backend return ((conferenceTime - DateTime.UtcNow).TotalHours < 0); } } public static class DisplayType { public const string COUNTDOWN = "countdown"; public const string DEMOGRAPHIC = "demographic"; public const string VIDEO = "video"; public const string PHOTOGRAPHY = "photography"; public const string INFLUENCERS = "influencer"; public const string INSTAGRAM = "instagram"; public const string TWITTER = "twitter"; public const string WORDCLOUD = "wordcloudterm"; }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace REQFINFO.Website.Infrastructure { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class CustomAuthorizeAttribute : AuthorizeAttribute { private bool _isAuthorized; public int UserRole { set; get; } protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { _isAuthorized = base.AuthorizeCore(httpContext); return _isAuthorized; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (HttpContext.Current.User.Identity.IsAuthenticated == false) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { // filterContext.Result = new RedirectToRouteResult(new //RouteValueDictionary(new { controller = "Error", action = "SessionTimeOut" })); filterContext.HttpContext.Response.StatusCode = 403; filterContext.Result = new JsonResult { Data = "LogOut", JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } else { //if(UserRole==(int)REQFINFO.Utility.Enums.Role.User) //{ // filterContext.Result = new RedirectToRouteResult(new // RouteValueDictionary(new { controller = "Site", action = "Index" })); //} //if (UserRole == (int)REQFINFO.Utility.Enums.Role.Admin) //{ // filterContext.Result = new RedirectToRouteResult(new // RouteValueDictionary(new { controller = "Site", action = "AdminLogin" })); //} } } //else if (!_isAuthorized) //{ // filterContext.Result = new RedirectToRouteResult(new // RouteValueDictionary(new { controller = "Error", action = "Index" })); //} } } public class FileTypesAttribute : ValidationAttribute { private readonly List<string> _types; public FileTypesAttribute(string types) { _types = types.Split(',').ToList(); } public override bool IsValid(object value) { if (value == null) return true; var fileExt = System.IO.Path.GetExtension((value as HttpPostedFileBase).FileName).Substring(1); return _types.Contains(fileExt, StringComparer.OrdinalIgnoreCase); } public override string FormatErrorMessage(string name) { return string.Format("Invalid file type. Only the following types {0} are supported.", String.Join(", ", _types)); } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using PlankCooking.Models; namespace PlankCooking.Api { [Produces("application/json")] [Route("api/v1/plankcooking")] public class PlankcookingController:Controller { private readonly JStanleyContext _context; public PlankcookingController(JStanleyContext context ) { _context = context; } [HttpGet] public async Task<List<Product>> getProducts() { var products = await _context.Product.ToListAsync(); return products; } [HttpGet("spicerubs")] public async Task<List<Product>> getSpiceRubs() { var spiceRubs = await _context.Product.Where(s => s.CategoryID == 1).ToListAsync(); return spiceRubs; } //Needs Fixed [HttpPost("/add/spicerubs")] public async Task<IActionResult> addQuantity([FromBody] OrderItem qty, OrderCart id) { OrderCart order = new OrderCart { OrderCartID = 1, Status = 1, WebsiteID = 1 }; OrderItem orderMe = new OrderItem { OrderItemID = 1, Qty = qty.Qty, ProductID = 3 }; if (!ModelState.IsValid) { return BadRequest(); } var productFound = await _context.Product.FirstOrDefaultAsync(s => s.ProductID == qty.ProductID); List<Product> productList = _context.Product.ToList(); int productsFound = productList.FindIndex(p => p.ProductID == qty.ProductID && p.ProductID == id.OrderCartID); if (productsFound >= 0) { return BadRequest("Product already exists."); } else { _context.OrderItem.Add(orderMe); _context.OrderCart.Add(order); _context.OrderItem.Add(qty); await _context.SaveChangesAsync(); return Ok(qty); } // var productFound = await _context.Product.FirstOrDefaultAsync(s => s.ProductID == qty.ProductID); // var itemFound = await _context.OrderItem.FirstOrDefaultAsync(s => s.OrderCartID == qty.OrderItemID); // List<OrderItem> itemList = _context.OrderItem.ToList(); // int itemsFound = itemList.FindIndex(h => h.Qty == qty.OrderItemID); // if (itemsFound >= 0) // { // return BadRequest("Item already exists"); // } // else // { // _context.OrderItem.Add(qty); // await _context.SaveChangesAsync(); // return Ok(qty); // } } [HttpGet("bakingplanks")] public async Task<List<Product>> getBakingPlanks() { var bakingPlanks = await _context.Product.Where(s => s.CategoryID == 4).ToListAsync(); return bakingPlanks; } [HttpGet("cookbooks")] public async Task<List<Product>> getCookBooks() { var cookBooks = await _context.Product.Where(s => s.CategoryID == 3).ToListAsync(); return cookBooks; } [HttpGet("bbqplanks")] public async Task<List<Product>> getBbqPlanks() { var bbqplanks = await _context.Product.Where(s => s.CategoryID == 5).ToListAsync(); return bbqplanks; } [HttpGet("nutdriver")] public async Task<List<Product>> getNutdriver() { var nutdriver = await _context.Product.Where(s => s.CategoryID == 6).ToListAsync(); return nutdriver; } // [Route("LinqDemo")] // public IEnumerable<string> LinqDemo() { // // string[] words = {"Hello", "Wonderful", "Linq", "Demo"}; // // //Lamda (Method) Syntax // // var shortWords = words.Where(w => w.Length == 4); // // //Query (Comprehension) Syntax // // //var shortWords = from w in words where w.Length == 4 select w; // // /* // // Select * from table where len(field) = 4 // // */ // // return shortWords; // } // [HttpGet] // public async Task<List<Student>> getStudents() { // //Lamda (Method) Syntax // var students = await _context.Students.Where(s => s.LastName.Length == 4).ToListAsync(); // return students; //Query (Comprehension) Syntax // var students = await _context.Students.ToListAsync(); // var shortNames = from s in students where s.LastName.Length == 4 select s; // return shortNames.ToList(); /* System.Threading.Thread.Sleep(5000); var students = new List<Student>(); students.Add(new Student { StudentId = 11, FirstName = "Tom", LastName = "Jones" }); students.Add(new Student { StudentId = 12, FirstName = "Bill", LastName = "Smith" }); students.Add(new Student { StudentId = 13, FirstName = "Eli", LastName = "Krohn" }); students.Add(new Student { StudentId = 14, FirstName = "Jason", LastName = "Stanley" }); return students; */ } }
using OnlineExaminationSystem.Core.DataAccess; using OnlineExaminationSystem.Entities; using System; using System.Collections.Generic; using System.Text; namespace OnlineExaminationSystem.DataAccess.Abstract { public interface IQuestionDal : IEntityRepository<Question> { } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using Lucene.Net.Analysis; using Lucene.Net.Analysis.Standard; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.QueryParsers; using Lucene.Net.Search; using Lucene.Net.Store; using Directory = System.IO.Directory; using Version = Lucene.Net.Util.Version; namespace StreetFinder { public class StreetRepositoryLucene: IStreetSearchRepository { private readonly string _luceneEdgeGramIndexDir = string.Empty; private const string LuceneIndeDefaultDir = "LuceneEdgegramIndex"; private const int MaxDocumentsBeforeIndexing = 1000; private int _insertedDocuments; private string StreetsEdgeGramIndexDirectory { get { return Environment.CurrentDirectory + "\\" + _luceneEdgeGramIndexDir; } } public StreetRepositoryLucene(): this(LuceneIndeDefaultDir) { } public StreetRepositoryLucene(string directoryName) { _luceneEdgeGramIndexDir = directoryName; _insertedDocuments = 0; } public void CreateStreetRepository() { var edgeGramDirectory = FSDirectory.Open(new DirectoryInfo(StreetsEdgeGramIndexDirectory)); var edgeGramIndex = new IndexWriter(edgeGramDirectory, new StandardAnalyzer(Version.LUCENE_30), true, IndexWriter.MaxFieldLength.LIMITED); edgeGramIndex.Commit(); edgeGramIndex.Dispose(true); edgeGramDirectory.Dispose(); } public bool ExistStreetRepository() { return Directory.Exists(StreetsEdgeGramIndexDirectory); } public void DeleteStreetRepository() { Directory.Delete(StreetsEdgeGramIndexDirectory, true); } public IEnumerable<Street> SearchForStreets(string zipCode, string streetName) { var foundStreetNames = new List<string>(); var ngramDirectory = FSDirectory.Open(new DirectoryInfo(StreetsEdgeGramIndexDirectory)); foreach (var street in SearchStreetInIndex(zipCode, streetName, ngramDirectory)) { if (!foundStreetNames.Contains(street.Name)) { foundStreetNames.Add(street.Name); yield return street; } } ngramDirectory.Dispose(); var ngramFuzziDirectory = FSDirectory.Open(new DirectoryInfo(StreetsEdgeGramIndexDirectory)); foreach (var street in FuzziSearchStreetInIndex(zipCode, streetName, ngramFuzziDirectory)) { if (!foundStreetNames.Contains(street.Name)) { foundStreetNames.Add(street.Name); yield return street; } } ngramFuzziDirectory.Dispose(); } private string GetQueryForStreetName(string streetName, string queryOperator) { var streetNameTrimmed = streetName.Trim('-', ' '); var streetNameWithoutMinus = streetNameTrimmed.Replace('-', ' '); var streetNameWithOneSpace = Regex.Replace(streetNameWithoutMinus, @"\s+", " "); var streetNameTokens = streetNameWithOneSpace.Replace('-', ' ').Split(' '); var result = ""; foreach (var streetNameToken in streetNameTokens) { result += string.Format("+Name:{0}{1} ", streetNameToken, queryOperator); } return result; } private IEnumerable<Street> SearchStreetInIndex(string zipCode, string streetName, FSDirectory directory) { return SearchStreetInIndex(zipCode, streetName, directory, "*"); } private IEnumerable<Street> FuzziSearchStreetInIndex(string zipCode, string streetName, FSDirectory directory) { return SearchStreetInIndex(zipCode, streetName, directory, "~0.6"); } private IEnumerable<Street> SearchStreetInIndex(string zipCode, string streetName, FSDirectory directory, string queryPostfix) { IndexReader indexReader = IndexReader.Open(directory, true); Searcher indexSearch = new IndexSearcher(indexReader); Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30); var queryParser = new QueryParser(Version.LUCENE_30, "Name", analyzer); // Search with Query parser var streetNameQuery = GetQueryForStreetName(streetName, queryPostfix); var query = queryParser.Parse(string.Format("{0} AND Pobox:{1}", streetNameQuery, zipCode)); var resultDocs = indexSearch.Search(query, 5); var hits = resultDocs.ScoreDocs; foreach (var hit in hits) { var documentFromSearcher = indexSearch.Doc(hit.Doc); yield return new Street { Name = documentFromSearcher.Get("Name"), Pobox = documentFromSearcher.Get("Pobox") }; } indexSearch.Dispose(); indexReader.Dispose(); } public void InsertStreet(Street street) { var streetDocument = new Document(); // streetDocument.Add(new Field("Id", Guid.NewGuid().ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED)); streetDocument.Add(new Field("Name", street.Name, Field.Store.YES, Field.Index.ANALYZED)); streetDocument.Add(new Field("Pobox", street.Pobox.ToString(CultureInfo.InvariantCulture), Field.Store.YES, Field.Index.NOT_ANALYZED)); // Write edgegram var edgeDirectory = FSDirectory.Open(new DirectoryInfo(StreetsEdgeGramIndexDirectory)); var streetEdgeGramAnalyzer = new StreetAnalyzer(Version.LUCENE_30); WriteInIndex(streetDocument, edgeDirectory, streetEdgeGramAnalyzer); edgeDirectory.Dispose(); } private void WriteInIndex(Document streetDocument, FSDirectory directory, Analyzer analyzer) { var indexWriter = new IndexWriter(directory, analyzer, false, IndexWriter.MaxFieldLength.LIMITED); indexWriter.AddDocument(streetDocument); _insertedDocuments++; if (_insertedDocuments == MaxDocumentsBeforeIndexing) { indexWriter.Optimize(); _insertedDocuments = 0; } indexWriter.Commit(); indexWriter.Dispose(true); } public void InsertStreets(string zipCode, ISet<string> streets) { var edgeDirectory = FSDirectory.Open(new DirectoryInfo(StreetsEdgeGramIndexDirectory)); var streetEdgeGramAnalyzer = new StreetAnalyzer(Version.LUCENE_30); var indexWriter = new IndexWriter(edgeDirectory, streetEdgeGramAnalyzer, false, IndexWriter.MaxFieldLength.LIMITED); foreach (var streetName in streets) { var streetDocument = new Document(); streetDocument.Add(new Field("Name", streetName, Field.Store.YES, Field.Index.ANALYZED)); streetDocument.Add(new Field("Pobox", zipCode, Field.Store.YES, Field.Index.NOT_ANALYZED)); // Write edgegram indexWriter.AddDocument(streetDocument); } indexWriter.Optimize(); indexWriter.Commit(); indexWriter.Dispose(true); edgeDirectory.Dispose(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class PlayManager : Singleton<PlayManager> { public TextMeshProUGUI winnerText; public InputManager inputManager; [HideInInspector] public SetupManager setupManager; public bool IsPlaying { private set; get; } Dictionary<int, HomeManager> homes; private void Awake() { homes = new Dictionary<int, HomeManager>(); IsPlaying = false; } public void StartSetup(int playerCount) { setupManager = FindObjectOfType<SetupManager>(); homes.Clear(); HomeManager[] activeHomes = setupManager.SetupPlayground(playerCount); foreach (var home in activeHomes) { homes[home.PlayerId] = home; } IsPlaying = true; InputManager.Instance.State = InputManager.PlayState.Play; } public BeetleControl GetBeetle(int id) { return homes[id].PlayerBeetle; } public void ClaimWinner(int id, float score) { if (score >= InputManager.Instance.winningScore) { IsPlaying = false; winnerText.text = "Player " + id + "\r\nWon"; StartCoroutine(DisplayWinner()); } } IEnumerator DisplayWinner() { winnerText.enabled = true; yield return new WaitForSeconds(1); } public void OnBackHome() { InputManager.Instance.State = InputManager.PlayState.End; } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using Newtonsoft.Json; using System.Text; using System.Reflection; namespace FSHook { public class ServerInterface : MarshalByRefObject { public void IsInstalled (int clientPID) { Console.WriteLine ("FSHook has been injected into process {0}.\r\n", clientPID); } public void ReportMessages (int clientPID, string[] messages) { for (int i = 0; i < messages.Length; i++) { Console.WriteLine (messages[i], clientPID); } } public void ReportMessage (int clientPID, string message) { Console.WriteLine (message); } public void ReportException (Exception e) { Console.WriteLine ("The target process has reported an error:\r\n" + e.ToString ()); } public void Ping () { } } public class InjectionEntryPoint : EasyHook.IEntryPoint { ServerInterface _server = null; Queue<string> _messageQueue = new Queue<string> (); string vfs_path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "V_FS.json"); string vfs_json = null; VFS _vfs = null; public InjectionEntryPoint ( EasyHook.RemoteHooking.IContext context, string channelName) { _server = EasyHook.RemoteHooking.IpcConnectClient<ServerInterface> (channelName); _server.Ping (); } public void Run ( EasyHook.RemoteHooking.IContext context, string channelName) { _server.IsInstalled (EasyHook.RemoteHooking.GetCurrentProcessId ()); try { vfs_json = new StreamReader (vfs_path).ReadToEnd (); _vfs = JsonConvert.DeserializeObject<VFS> (vfs_json); } catch (Exception e) { _server.ReportException (e); } var fsCreateFileHook = EasyHook.LocalHook.Create( EasyHook.LocalHook.GetProcAddress("kernel32.dll", "CreateFileW"), new WinAPI.CreateFileW_Delegate(CreateFile_Hook), this); fsCreateFileHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); _server.ReportMessage(EasyHook.RemoteHooking.GetCurrentProcessId(), "File: CreateFileW hook installed"); var fsDeleteFileHook = EasyHook.LocalHook.Create( EasyHook.LocalHook.GetProcAddress("kernel32.dll", "DeleteFileW"), new WinAPI.DeleteFileW_Delegate(DeleteFile_Hook), this); fsDeleteFileHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); _server.ReportMessage(EasyHook.RemoteHooking.GetCurrentProcessId(), "File: DeleteFileW hook installed"); var fsCopyFileHook = EasyHook.LocalHook.Create( EasyHook.LocalHook.GetProcAddress("kernel32.dll", "CopyFileW"), new WinAPI.CopyFileW_Delegate(CopyFile_Hook), this); fsCopyFileHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 }); _server.ReportMessage(EasyHook.RemoteHooking.GetCurrentProcessId(), "File: CopyFileW hook installed"); EasyHook.RemoteHooking.WakeUpProcess (); try { while (true) { System.Threading.Thread.Sleep (500); string[] queued = null; lock (_messageQueue) { queued = _messageQueue.ToArray (); _messageQueue.Clear (); } if (queued != null && queued.Length > 0) { _server.ReportMessages (EasyHook.RemoteHooking.GetCurrentProcessId (), queued); } else { _server.Ping (); } } } catch { } fsCreateFileHook.Dispose(); fsDeleteFileHook.Dispose(); fsCopyFileHook.Dispose(); EasyHook.LocalHook.Release (); } IntPtr CreateFile_Hook( string InFileName, int InDesiredAccess, int InShareMode, IntPtr InSecurityAttributes, int InCreationDisposition, int InFlagsAndAttributes, IntPtr InTemplateFile) { foreach (VFSMapping map in _vfs.Mapping) { if (InFileName.Contains(map.Source)) { string OriInFileName = InFileName; InFileName = InFileName.Replace(map.Source, map.Destination); this._messageQueue.Enqueue( string.Format("[{0}:{1}]: Original Path {2} has been redirected to {3}", EasyHook.RemoteHooking.GetCurrentProcessId(), EasyHook.RemoteHooking.GetCurrentThreadId(), OriInFileName, InFileName)); break; } } try { lock (this._messageQueue) { if (this._messageQueue.Count < 1000) { this._messageQueue.Enqueue( string.Format("[{0}:{1}]: Create {2}", EasyHook.RemoteHooking.GetCurrentProcessId(), EasyHook.RemoteHooking.GetCurrentThreadId(), InFileName)); } } } catch { } return WinAPI.CreateFile( InFileName, InDesiredAccess, InShareMode, InSecurityAttributes, InCreationDisposition, InFlagsAndAttributes, InTemplateFile); } bool ReadFileEx_Hook( IntPtr hFile, [Out] byte[] lpBuffer, uint nNumberOfBytesToRead, [In] ref System.Threading.NativeOverlapped lpOverlapped, System.Threading.IOCompletionCallback lpCompletionRoutine) { try { lock (this._messageQueue) { if (this._messageQueue.Count < 1000) { this._messageQueue.Enqueue( string.Format("[{0}:{1}]: Read {2}", EasyHook.RemoteHooking.GetCurrentProcessId(), EasyHook.RemoteHooking.GetCurrentThreadId(), hFile)); } } } catch { } return WinAPI.ReadFileEx( hFile, lpBuffer, nNumberOfBytesToRead, ref lpOverlapped, lpCompletionRoutine); } bool GetFileSize_Hook( IntPtr hFile, out long lpFileSize) { try { lock (this._messageQueue) { if (this._messageQueue.Count < 1000) { this._messageQueue.Enqueue( string.Format("[{0}:{1}]: Get Size {2}", EasyHook.RemoteHooking.GetCurrentProcessId(), EasyHook.RemoteHooking.GetCurrentThreadId(), hFile)); } } } catch { } return WinAPI.GetFileSize( hFile, out lpFileSize); } bool GetFileTime_Hook( IntPtr hFile, IntPtr lpCreationTime, IntPtr lpLastAccessTime, IntPtr lpLastWriteTime) { try { lock (this._messageQueue) { if (this._messageQueue.Count < 1000) { this._messageQueue.Enqueue( string.Format("[{0}:{1}]: Get Time {2} {3}", EasyHook.RemoteHooking.GetCurrentProcessId(), EasyHook.RemoteHooking.GetCurrentThreadId(), hFile, lpLastWriteTime)); } } } catch { } return WinAPI.GetFileTime( hFile, lpCreationTime, lpLastAccessTime, lpLastWriteTime); } IntPtr DeleteFile_Hook( string lpFileName) { foreach (VFSMapping map in _vfs.Mapping) { if (lpFileName.Contains(map.Source)) { string OrilpFileName = lpFileName; lpFileName = lpFileName.Replace(map.Source, map.Destination); this._messageQueue.Enqueue( string.Format("[{0}:{1}]: Original Path {2} has been redirected to {3}", EasyHook.RemoteHooking.GetCurrentProcessId(), EasyHook.RemoteHooking.GetCurrentThreadId(), OrilpFileName, lpFileName)); break; } } try { lock (this._messageQueue) { if (this._messageQueue.Count < 1000) { this._messageQueue.Enqueue( string.Format("[{0}:{1}]: Delete {2}", EasyHook.RemoteHooking.GetCurrentProcessId(), EasyHook.RemoteHooking.GetCurrentThreadId(), lpFileName)); } } } catch { } return WinAPI.DeleteFile( lpFileName); } bool CopyFile_Hook( string lpExistingFileName, string lpNewFileName, bool bFailIfExists) { foreach (VFSMapping map in _vfs.Mapping) { if (lpExistingFileName.Contains(map.Source)) { string OrilpExistingFileName = lpExistingFileName; lpExistingFileName = lpExistingFileName.Replace(map.Source, map.Destination); this._messageQueue.Enqueue( string.Format("[{0}:{1}]: Original Path {2} has been redirected to {3}", EasyHook.RemoteHooking.GetCurrentProcessId(), EasyHook.RemoteHooking.GetCurrentThreadId(), OrilpExistingFileName, lpExistingFileName)); break; } } foreach (VFSMapping map in _vfs.Mapping) { if (lpNewFileName.Contains(map.Source)) { string OrilpNewFileName = lpNewFileName; lpNewFileName = lpNewFileName.Replace(map.Source, map.Destination); this._messageQueue.Enqueue( string.Format("[{0}:{1}]: Original Path {2} has been redirected to {3}", EasyHook.RemoteHooking.GetCurrentProcessId(), EasyHook.RemoteHooking.GetCurrentThreadId(), OrilpNewFileName, lpNewFileName)); break; } } try { lock (this._messageQueue) { if (this._messageQueue.Count < 1000) { this._messageQueue.Enqueue( string.Format("[{0}:{1}]: Copy {2} {3}", EasyHook.RemoteHooking.GetCurrentProcessId(), EasyHook.RemoteHooking.GetCurrentThreadId(), lpExistingFileName, lpNewFileName)); } } } catch { } return WinAPI.CopyFileW( lpExistingFileName, lpNewFileName, bFailIfExists); } } }
using Figuras.Entidades; using Figuras.Entidades.Enums; using System; using System.Collections.Generic; namespace Figuras { class Program { static void Main(string[] args) { Figura figura; List<Figura> figuras = new List<Figura>(); Console.Write("Quantas figuras: "); int n = int.Parse(Console.ReadLine()); for (int i = 1; i <= n; i++) { Console.WriteLine($"Dados da Figura #{i}: "); Console.Write("Retângulo ou círculo (r/c)? "); string opc = Console.ReadLine(); Console.Write("Informe a cor: "); string cor = Console.ReadLine(); if (opc == "c") { Console.Write("Informe o valor do raio: "); int raio = int.Parse(Console.ReadLine()); figura = new Circulo(Enum.Parse<Cor>(cor), raio); figuras.Add(figura); } else if (opc == "r") { Console.Write("Informe o valor da base: "); int baser = int.Parse(Console.ReadLine()); Console.Write("Informe o valor da altura: "); int altura = int.Parse(Console.ReadLine()); figura = new Retangulo(Enum.Parse<Cor>(cor), baser, altura); figuras.Add(figura); } else { Console.WriteLine("Opção inválida!"); } Console.WriteLine(); } Console.WriteLine(); Console.WriteLine("ÁREA DAS FIGURAS:"); foreach(var item in figuras) { Console.WriteLine(item.Area()); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace LotteryWebService { public class UserInfo { public string FirstName { get; set; } public string LastName { get; set; } public string PhoneNumber { get; set; } public string EmailId { get; set; } public string Password { get; set; } public string DateOfBirth { get; set; } public string Nationality { get; set; } public string IDType { get; set; } public string IdNo { get; set; } public string Address { get; set; } public string State { get; set; } public string City { get; set; } public string ReferralCode { get; set; } public int Status { get; set; } public string Error { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CommonLib { public interface ISampleInterface { void SampleMethod(); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace IMS_Entity_Framework_DB_First_Approach.Models { public class ProductMetaData { public int ProductId { get; set; } [Required, MaxLength(5, ErrorMessage ="Maximum Length is 5")] public string ProductName { get; set; } [Required, Range(0,1000)] public double Price { get; set; } public int CategoryId { get; set; } public virtual Category Category { get; set; } } }
using System.Collections.Generic; using System.Windows.Navigation; using System.Windows.Controls; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Linq; using System.Net; using System; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using PopupManager.Resources; using PopupManager.Popuppy; namespace PopupManager { public partial class MainPage : PhoneApplicationPage { public MainPage() { InitializeComponent(); } private void ShowPopup(object s, EventArgs e) { var vars = new TextParams { Message = "Would you like to have some tea and crumpets in a half of an hour?", Ok = "Yes, please", Cancel = "No thanks" }; Manager.Show(vars, (se, ev) => Debug.WriteLine("OK"), (se, ev) => Debug.WriteLine("Cancel")); } protected override void OnBackKeyPress(CancelEventArgs e) { if (Manager.ActivePopup.IsOpen && Manager.ActiveDrag != null) { Manager.ActiveDrag.OnCancel(this, e); e.Cancel = true; } } } }
//------------------------------------------------------------------------------ // The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx. // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. // See the License for the specific language governing rights and limitations under the License. // // The Original Code is nopCommerce. // The Initial Developer of the Original Code is NopSolutions. // All Rights Reserved. // // Contributor(s): _______. //------------------------------------------------------------------------------ using System; using System.Collections.Specialized; using System.Configuration.Provider; using System.Data; using System.Data.Common; using Microsoft.Practices.EnterpriseLibrary.Data; namespace NopSolutions.NopCommerce.DataAccess.Shipping { /// <summary> /// ShippingByWeightAndCountry provider for SQL Server /// </summary> public partial class SQLShippingByWeightAndCountryProvider : DBShippingByWeightAndCountryProvider { #region Fields private string _sqlConnectionString; #endregion #region Utilities private DBShippingByWeightAndCountry GetShippingByWeightAndCountryFromReader(IDataReader dataReader) { DBShippingByWeightAndCountry shippingByWeightAndCountry = new DBShippingByWeightAndCountry(); shippingByWeightAndCountry.ShippingByWeightAndCountryID = NopSqlDataHelper.GetInt(dataReader, "ShippingByWeightAndCountryID"); shippingByWeightAndCountry.ShippingMethodID = NopSqlDataHelper.GetInt(dataReader, "ShippingMethodID"); shippingByWeightAndCountry.CountryID = NopSqlDataHelper.GetInt(dataReader, "CountryID"); shippingByWeightAndCountry.From = NopSqlDataHelper.GetDecimal(dataReader, "From"); shippingByWeightAndCountry.To = NopSqlDataHelper.GetDecimal(dataReader, "To"); shippingByWeightAndCountry.UsePercentage = NopSqlDataHelper.GetBoolean(dataReader, "UsePercentage"); shippingByWeightAndCountry.ShippingChargePercentage = NopSqlDataHelper.GetDecimal(dataReader, "ShippingChargePercentage"); shippingByWeightAndCountry.ShippingChargeAmount = NopSqlDataHelper.GetDecimal(dataReader, "ShippingChargeAmount"); return shippingByWeightAndCountry; } #endregion #region Methods /// <summary> /// Initializes the provider with the property values specified in the application's configuration file. This method is not intended to be used directly from your code /// </summary> /// <param name="name">The name of the provider instance to initialize</param> /// <param name="config">A NameValueCollection that contains the names and values of configuration options for the provider.</param> public override void Initialize(string name, NameValueCollection config) { if (config == null) { throw new ArgumentNullException("config"); } base.Initialize(name, config); string connectionStringName = config["connectionStringName"]; if (String.IsNullOrEmpty(connectionStringName)) throw new ProviderException("Connection name not specified"); this._sqlConnectionString = NopSqlDataHelper.GetConnectionString(connectionStringName); if ((this._sqlConnectionString == null) || (this._sqlConnectionString.Length < 1)) { throw new ProviderException(string.Format("Connection string not found. {0}", connectionStringName)); } config.Remove("connectionStringName"); if (config.Count > 0) { string key = config.GetKey(0); if (!string.IsNullOrEmpty(key)) { throw new ProviderException(string.Format("Provider unrecognized attribute. {0}", new object[] { key })); } } } /// <summary> /// Gets a ShippingByWeightAndCountry /// </summary> /// <param name="ShippingByWeightAndCountryID">ShippingByWeightAndCountry identifier</param> /// <returns>ShippingByWeightAndCountry</returns> public override DBShippingByWeightAndCountry GetByID(int ShippingByWeightAndCountryID) { DBShippingByWeightAndCountry shippingByWeightAndCountry = null; Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString); DbCommand dbCommand = db.GetStoredProcCommand("Nop_ShippingByWeightAndCountryLoadByPrimaryKey"); db.AddInParameter(dbCommand, "ShippingByWeightAndCountryID", DbType.Int32, ShippingByWeightAndCountryID); using (IDataReader dataReader = db.ExecuteReader(dbCommand)) { if (dataReader.Read()) { shippingByWeightAndCountry = GetShippingByWeightAndCountryFromReader(dataReader); } } return shippingByWeightAndCountry; } /// <summary> /// Deletes a ShippingByWeightAndCountry /// </summary> /// <param name="ShippingByWeightAndCountryID">ShippingByWeightAndCountry identifier</param> public override void DeleteShippingByWeightAndCountry(int ShippingByWeightAndCountryID) { Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString); DbCommand dbCommand = db.GetStoredProcCommand("Nop_ShippingByWeightAndCountryDelete"); db.AddInParameter(dbCommand, "ShippingByWeightAndCountryID", DbType.Int32, ShippingByWeightAndCountryID); int retValue = db.ExecuteNonQuery(dbCommand); } /// <summary> /// Gets all ShippingByWeightAndCountrys /// </summary> /// <returns>ShippingByWeightAndCountry collection</returns> public override DBShippingByWeightAndCountryCollection GetAll() { DBShippingByWeightAndCountryCollection shippingByWeightAndCountryCollection = new DBShippingByWeightAndCountryCollection(); Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString); DbCommand dbCommand = db.GetStoredProcCommand("Nop_ShippingByWeightAndCountryLoadAll"); using (IDataReader dataReader = db.ExecuteReader(dbCommand)) { while (dataReader.Read()) { DBShippingByWeightAndCountry shippingByWeightAndCountry = GetShippingByWeightAndCountryFromReader(dataReader); shippingByWeightAndCountryCollection.Add(shippingByWeightAndCountry); } } return shippingByWeightAndCountryCollection; } /// <summary> /// Inserts a ShippingByWeightAndCountry /// </summary> /// <param name="ShippingMethodID">The shipping method identifier</param> /// <param name="CountryID">The country identifier</param> /// <param name="From">The "from" value</param> /// <param name="To">The "to" value</param> /// <param name="UsePercentage">A value indicating whether to use percentage</param> /// <param name="ShippingChargePercentage">The shipping charge percentage</param> /// <param name="ShippingChargeAmount">The shipping charge amount</param> /// <returns>ShippingByWeightAndCountry</returns> public override DBShippingByWeightAndCountry InsertShippingByWeightAndCountry(int ShippingMethodID, int CountryID, decimal From, decimal To, bool UsePercentage, decimal ShippingChargePercentage, decimal ShippingChargeAmount) { DBShippingByWeightAndCountry shippingByWeightAndCountry = null; Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString); DbCommand dbCommand = db.GetStoredProcCommand("Nop_ShippingByWeightAndCountryInsert"); db.AddOutParameter(dbCommand, "ShippingByWeightAndCountryID", DbType.Int32, 0); db.AddInParameter(dbCommand, "ShippingMethodID", DbType.Int32, ShippingMethodID); db.AddInParameter(dbCommand, "CountryID", DbType.Int32, CountryID); db.AddInParameter(dbCommand, "From", DbType.Decimal, From); db.AddInParameter(dbCommand, "To", DbType.Decimal, To); db.AddInParameter(dbCommand, "UsePercentage", DbType.Boolean, UsePercentage); db.AddInParameter(dbCommand, "ShippingChargePercentage", DbType.Decimal, ShippingChargePercentage); db.AddInParameter(dbCommand, "ShippingChargeAmount", DbType.Decimal, ShippingChargeAmount); if (db.ExecuteNonQuery(dbCommand) > 0) { int ShippingByWeightAndCountryID = Convert.ToInt32(db.GetParameterValue(dbCommand, "@ShippingByWeightAndCountryID")); shippingByWeightAndCountry = GetByID(ShippingByWeightAndCountryID); } return shippingByWeightAndCountry; } /// <summary> /// Updates the ShippingByWeightAndCountry /// </summary> /// <param name="ShippingByWeightAndCountryID">The ShippingByWeightAndCountry identifier</param> /// <param name="ShippingMethodID">The shipping method identifier</param> /// <param name="CountryID">The country identifier</param> /// <param name="From">The "from" value</param> /// <param name="To">The "to" value</param> /// <param name="UsePercentage">A value indicating whether to use percentage</param> /// <param name="ShippingChargePercentage">The shipping charge percentage</param> /// <param name="ShippingChargeAmount">The shipping charge amount</param> /// <returns>ShippingByWeightAndCountry</returns> public override DBShippingByWeightAndCountry UpdateShippingByWeightAndCountry(int ShippingByWeightAndCountryID, int ShippingMethodID, int CountryID, decimal From, decimal To, bool UsePercentage, decimal ShippingChargePercentage, decimal ShippingChargeAmount) { DBShippingByWeightAndCountry shippingByWeightAndCountry = null; Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString); DbCommand dbCommand = db.GetStoredProcCommand("Nop_ShippingByWeightAndCountryUpdate"); db.AddInParameter(dbCommand, "ShippingByWeightAndCountryID", DbType.Int32, ShippingByWeightAndCountryID); db.AddInParameter(dbCommand, "ShippingMethodID", DbType.Int32, ShippingMethodID); db.AddInParameter(dbCommand, "CountryID", DbType.Int32, CountryID); db.AddInParameter(dbCommand, "From", DbType.Decimal, From); db.AddInParameter(dbCommand, "To", DbType.Decimal, To); db.AddInParameter(dbCommand, "UsePercentage", DbType.Boolean, UsePercentage); db.AddInParameter(dbCommand, "ShippingChargePercentage", DbType.Decimal, ShippingChargePercentage); db.AddInParameter(dbCommand, "ShippingChargeAmount", DbType.Decimal, ShippingChargeAmount); if (db.ExecuteNonQuery(dbCommand) > 0) shippingByWeightAndCountry = GetByID(ShippingByWeightAndCountryID); return shippingByWeightAndCountry; } /// <summary> /// Gets all ShippingByWeightAndCountrys by shipping method identifier /// </summary> /// <param name="ShippingMethodID">The shipping method identifier</param> /// <param name="CountryID">The country identifier</param> /// <returns>ShippingByWeightAndCountry collection</returns> public override DBShippingByWeightAndCountryCollection GetAllByShippingMethodIDAndCountryID(int ShippingMethodID, int CountryID) { DBShippingByWeightAndCountryCollection shippingByWeightAndCountryCollection = new DBShippingByWeightAndCountryCollection(); Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString); DbCommand dbCommand = db.GetStoredProcCommand("Nop_ShippingByWeightAndCountryLoadByShippingMethodIDAndCountryID"); db.AddInParameter(dbCommand, "ShippingMethodID", DbType.Int32, ShippingMethodID); db.AddInParameter(dbCommand, "CountryID", DbType.Int32, CountryID); using (IDataReader dataReader = db.ExecuteReader(dbCommand)) { while (dataReader.Read()) { DBShippingByWeightAndCountry shippingByWeightAndCountry = GetShippingByWeightAndCountryFromReader(dataReader); shippingByWeightAndCountryCollection.Add(shippingByWeightAndCountry); } } return shippingByWeightAndCountryCollection; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using DemoStandardProject.Data; using DemoStandardProject.DTOs; using DemoStandardProject.Models.ServiceResponse; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using DemoStandardProject.Models.Products; namespace DemoStandardProject.Services { public class ProductService : IProductService { private readonly AppDBContext _db; private readonly IMapper _mapper; private readonly IHttpContextAccessor _httpAccessor; public ProductService(AppDBContext db, IMapper mapper, IHttpContextAccessor httpAccessor) { _httpAccessor = httpAccessor; _mapper = mapper; _db = db; } public async Task<ServiceResponse<List<ProductDto>>> AddProduct(AddProductDto newProduct) { ServiceResponse<List<ProductDto>> response = new ServiceResponse<List<ProductDto>>(); var ProductGroupId = await _db.ProductGroups .FirstOrDefaultAsync(x => x.ProductGroupId == newProduct.ProductGroupId); if (ProductGroupId == null) { response.IsSuccess = false; response.Message = "productGroupId not found"; } var PromotionId = await _db.Promotions.FirstOrDefaultAsync(x => x.PromotionId == newProduct.PromotionId); if (PromotionId == null) { response.IsSuccess = false; response.Message = "PromotionId not found"; } Product products = _mapper.Map<Product>(newProduct); /* var products = new Product { productGroups = newProduct.ProductGroupId, PromotionId = newProduct.PromotionId, ProductCode = newProduct.ProductCode, ProductDetail = newProduct.ProductDetail, Price = newProduct.Price, Discount = newProduct.Discount, Stock = newProduct.Stock, CreatedDate = response.ServerDateTime, UpdateDate = response.ServerDateTime, IsActice = true };*/ _db.Products.Add(products); await _db.SaveChangesAsync(); //response.Data = _mapper.Map<ProductDto>(products); response.Data = (_db.Products.Select(c => _mapper.Map<ProductDto>(c))).ToList(); return response; } public async Task<ServiceResponse<List<ProductDto>>> GetProductAll() { ServiceResponse<List<ProductDto>> response = new ServiceResponse<List<ProductDto>>(); List<Product> proudcts = await _db.Products .Include(c => c.ProductGroup) .Include(c => c.Promotions) .ToListAsync(); response.Data = _mapper.Map<List<ProductDto>>(proudcts); return response; } public async Task<ServiceResponse<ProductDto>> GetProductGetById(int Id) { ServiceResponse<ProductDto> response = new ServiceResponse<ProductDto>(); Product product = await _db.Products .Include(c => c.ProductGroup) .Include(c => c.Promotions) .FirstOrDefaultAsync(x => x.ProductId == Id); if (product == null) { response.IsSuccess = false; response.Message = "ProductId Not Found"; } response.Data = _mapper.Map<ProductDto>(product); return response; } public async Task<ServiceResponse<ProductDto>> UpdateProduct(UpdateProductDto updateProduct) { ServiceResponse<ProductDto> response = new ServiceResponse<ProductDto>(); Product product = await _db.Products .Include(x => x.ProductGroup) .Include(x => x.Promotions) .FirstOrDefaultAsync(x => x.ProductId == updateProduct.ProductId); if (product == null) { // response.IsSuccess = false; // response.Message = "ProductId not Found"; return ResponseResult.Failure<ProductDto>("ProductId not Found"); } try { product.ProductDetail = updateProduct.ProductDetail; product.ProductGroupId = updateProduct.ProductGroupId; product.PromotionId = updateProduct.PromotionId; product.Stock = updateProduct.Stock; product.Price = updateProduct.Price; product.UpdateDate = DateTime.Now; _db.Products.Update(product); await _db.SaveChangesAsync(); response.Data = _mapper.Map<ProductDto>(product); } catch (Exception ex) { response.IsSuccess = false; response.Message = ex.Message; } return response; } public async Task<ServiceResponse<List<ProductDto>>> DelectProduct(int Id) { ServiceResponse<List<ProductDto>> response = new ServiceResponse<List<ProductDto>>(); Product product = await _db.Products.FirstOrDefaultAsync(c => c.ProductId == Id); if (product == null) { // response.IsSuccess = false; // response.Message = "ProductId not found"; return ResponseResult.Failure<List<ProductDto>>("ProductId not found"); } try { _db.Products.Remove(product); await _db.SaveChangesAsync(); response.Data = (_db.Products.Select(c => _mapper.Map<ProductDto>(c))).ToList(); } catch (Exception ex) { response.IsSuccess = false; response.Message = ex.Message; } return response; } } }
namespace WebsitePerformance.DAL.EF { using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using WebsitePerformance.ContractsBetweenBLLandDAL.Entities; using System.Data.SqlClient; public partial class WebsitePerformanceModel : DbContext { public WebsitePerformanceModel() : base("name=WebsitePerformanceModel") { } public virtual DbSet<link> link { get; set; } public virtual DbSet<test> test { get; set; } public virtual DbSet<website> website { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<link>() .Property(e => e.url) .IsUnicode(false); modelBuilder.Entity<link>() .HasMany(e => e.tests) .WithRequired(e => e.link) .HasForeignKey(e => e.link_id) .WillCascadeOnDelete(false); modelBuilder.Entity<website>() .Property(e => e.url) .IsUnicode(false); modelBuilder.Entity<website>() .HasMany(e => e.links) .WithRequired(e => e.website) .HasForeignKey(e => e.site_id); } } }
using System; using System.Collections.Concurrent; using System.Linq; using Core.Internal.Dependency; using LinqToDB.Data; using Core.Services; #if DEBUG using System.Threading; using System.Diagnostics; #endif namespace Core.Internal.LinqToDB { public class DataConnectionFactory : IDisposable, IDataConnectionFactory { // Каждой конфигурации положено только одно соединение в рамках HttpRequest-а private readonly ConcurrentDictionary<string, CoreDataContext> _connections = new ConcurrentDictionary<string, CoreDataContext>(); public IDataConnection GetDataConnection(string configurationString) { #if DEBUG Debug.WriteLine($@"DataConnectionFactory.GetDataConnection(""{configurationString}"");"); #endif return _connections.GetOrAdd(configurationString, s => { #if DEBUG var ts = new Stopwatch(); ts.Start(); try { #endif return new CoreDataContext(s); #if DEBUG } finally { ts.Stop(); Debug.WriteLine($@"DataConnectionFactory.Add(new DataConnection(""{s}"")); Connection added with {ts.ElapsedMilliseconds} ms"); } #endif }); } #if DEBUG public DataConnectionFactory() { Debug.WriteLine($"DataConnectionFactory.ctor(); Thread.CurrentThread.ManagedThreadId == {Thread.CurrentThread.ManagedThreadId}"); } #endif public void Dispose() { _connections.Keys.ToList().ForEach(k => { CoreDataContext connection; if (_connections.TryRemove(k, out connection)) connection.Dispose(); }); #if DEBUG Debug.WriteLine($"DataConnectionFactory.Dispose(); Thread.CurrentThread.ManagedThreadId == {Thread.CurrentThread.ManagedThreadId}"); #endif } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class BackButton : MonoBehaviour { private Button backButton; void Awake() { backButton = GetComponent<Button>(); } void Start() { backButton.onClick.AddListener(OnClick); } void OnClick() { Game.sceneTransitionManager.ChangeScene("Menu"); } }
using System; using System.Collections.Generic; using System.Linq; namespace PaderbornUniversity.SILab.Hip.EventSourcing.Mongo { /// <summary> /// Provides read/write access to a Mongo database. /// Each <see cref="ResourceType"/> corresponds to one collection in the database. /// </summary> public interface IMongoDbContext { IQueryable<T> GetCollection<T>(ResourceType resourceType) where T : IEntity<int>; /// <summary> /// Retrieves the entity with the specified ID from the database. /// If no entity with that ID exists, the default value of <typeparamref name="T"/> /// is returned (which is usually null). /// </summary> T Get<T>(EntityId entity) where T : IEntity<int>; /// <summary> /// Retrieves the entities with the specified IDs from the database. /// IDs for which no entity exists are ignored, so the number of returned entities may be /// smaller than the number of specified IDs. /// </summary> IReadOnlyList<T> GetMany<T>(ResourceType resourceType, IEnumerable<int> ids) where T : IEntity<int>; /// <summary> /// Inserts an entity with the specified ID into the database. /// Throws an exception if an entity of the same ID already exists. /// </summary> void Add<T>(ResourceType resourceType, T entity) where T : IEntity<int>; /// <summary> /// Deletes an entity. /// </summary> /// <returns>True if the entity was found and deleted</returns> bool Delete(EntityId entity); /// <summary> /// Replaces an entity with another one. The IDs of the existing entity /// and the replacement must match, otherwise an exception is thrown. /// </summary> /// <returns>True if the original entity was found and replaced</returns> bool Replace<T>(EntityId entity, T newEntity) where T : IEntity<int>; /// <summary> /// Updates specific properties of an entity. /// </summary> /// <returns>True if the entity was found and updated</returns> bool Update<T>(EntityId entity, Action<IMongoUpdater<T>> updateFunc) where T : IEntity<int>; /// <summary> /// Creates a reference from <paramref name="source"/> to <paramref name="target"/>. /// Duplicate references are not created: If the reference to be added already exists, the /// method does nothing. /// </summary> void AddReference(EntityId source, EntityId target); void AddReferences(EntityId source, IEnumerable<EntityId> targets); bool RemoveReference(EntityId source, EntityId target); /// <summary> /// Removes all references from other entities to the specified <paramref name="entity"/>. /// </summary> void ClearIncomingReferences(EntityId entity); /// <summary> /// Removes all references from the specified <paramref name="entity"/> to other entities. /// </summary> void ClearOutgoingReferences(EntityId entity); } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class HealthController : MonoBehaviour { //this was for that scene where we werent using the scale. //not in the game public Image health; public float totalHealth = 1f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { health.fillAmount = totalHealth; } }
// Copyright 2021 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.Net.Tls; using NtApiDotNet.Utilities.Text; using System.Collections.Generic; using System.IO; using System.Text; namespace NtApiDotNet.Win32.Security.Authentication.Schannel { /// <summary> /// Authentication token for Schannel and CredSSP. /// </summary> /// <remarks>This is a simple parser for the TLS record format.</remarks> public class SchannelAuthenticationToken : AuthenticationToken { #region Public Properties /// <summary> /// List of TLS records. /// </summary> public IReadOnlyList<TlsRecord> Records { get; } #endregion #region Public Methods /// <summary> /// Format the authentication token. /// </summary> /// <returns>The token as a formatted string.</returns> public override string Format() { StringBuilder builder = new StringBuilder(); int index = 0; foreach (var record in Records) { builder.AppendLine($"SChannel Record {index++}"); builder.AppendLine($"Type : {record.Type}"); builder.AppendLine($"Version: {record.Version}"); builder.AppendLine("Data :"); HexDumpBuilder hex_builder = new HexDumpBuilder(true, true, true, false, 0); hex_builder.Append(record.Data); hex_builder.Complete(); builder.AppendLine(hex_builder.ToString()); } return builder.ToString(); } #endregion #region Constructors internal SchannelAuthenticationToken(byte[] data, List<TlsRecord> records) : base(data) { Records = records.AsReadOnly(); } #endregion #region Internal Static Methods /// <summary> /// Try and parse data into an SChannel authentication token. /// </summary> /// <param name="data">The data to parse.</param> /// <param name="token">The SChannel authentication token.</param> /// <param name="client">True if this is a token from a client.</param> /// <param name="token_count">The token count number.</param> /// <returns>True if parsed successfully.</returns> internal static bool TryParse(byte[] data, int token_count, bool client, out SchannelAuthenticationToken token) { token = null; MemoryStream stm = new MemoryStream(data); BinaryReader reader = new BinaryReader(stm); List<TlsRecord> records = new List<TlsRecord>(); while (stm.RemainingLength() > 0) { if (!TlsRecord.TryParse(reader, out TlsRecord record)) { return false; } records.Add(record); } token = new SchannelAuthenticationToken(data, records); return true; } #endregion } }
using System; using System.Collections.Generic; namespace MADSPack.Compression { public class MadsPackEntry { public MadsPackEntry() { } public short getHash() { return hash; } public void setHash(short hash) { this.hash = hash; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public int getCompressedSize() { return compressedSize; } public void setCompressedSize(int compressedSize) { this.compressedSize = compressedSize; } public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } private short hash; private int size; private int compressedSize; private byte[] data; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using g = GSShared; namespace GSShared { public class Exceptions { public static void Catch(string strException) { throw new Exception(strException); } } }
namespace Standard { using System; internal enum DWMWA { ALLOW_NCPAINT = 4, CAPTION_BUTTON_BOUNDS = 5, DISALLOW_PEEK = 11, EXCLUDED_FROM_PEEK = 12, EXTENDED_FRAME_BOUNDS = 9, FLIP3D_POLICY = 8, FORCE_ICONIC_REPRESENTATION = 7, HAS_ICONIC_BITMAP = 10, NCRENDERING_ENABLED = 1, NCRENDERING_POLICY = 2, NONCLIENT_RTL_LAYOUT = 6, TRANSITIONS_FORCEDISABLED = 3 } }
using System.Data.Entity.ModelConfiguration; using RMAT3.Models; namespace RMAT3.Data.Mapping { public class SectionQuestionAnswerTypeMap : EntityTypeConfiguration<SectionQuestionAnswerType> { public SectionQuestionAnswerTypeMap() { // Primary Key HasKey(t => t.SectionQuestionAnswerTypeId); // Properties Property(t => t.AddedByUserId) .IsRequired() .HasMaxLength(20); Property(t => t.UpdatedByUserId) .IsRequired() .HasMaxLength(20); Property(t => t.UpdatedCommentTxt) .HasMaxLength(500); Property(t => t.AnswerTypeTxt) .HasMaxLength(200); Property(t => t.GroupTypeTxt) .HasMaxLength(200); // Table & Column Mappings ToTable("SectionQuestionAnswerType", "OLTP"); Property(t => t.SectionQuestionAnswerTypeId).HasColumnName("SectionQuestionAnswerTypeId"); Property(t => t.AddedByUserId).HasColumnName("AddedByUserId"); Property(t => t.AddTs).HasColumnName("AddTs"); Property(t => t.UpdatedByUserId).HasColumnName("UpdatedByUserId"); Property(t => t.UpdatedCommentTxt).HasColumnName("UpdatedCommentTxt"); Property(t => t.UpdatedTs).HasColumnName("UpdatedTs"); Property(t => t.IsActiveInd).HasColumnName("IsActiveInd"); Property(t => t.EffectiveFromDt).HasColumnName("EffectiveFromDt"); Property(t => t.EffectiveToDt).HasColumnName("EffectiveToDt"); Property(t => t.AnswerTypeTxt).HasColumnName("AnswerTypeTxt"); Property(t => t.GroupTypeTxt).HasColumnName("GroupTypeTxt"); Property(t => t.ShowChildInd).HasColumnName("ShowChildInd"); Property(t => t.SectionQuestionTypeId).HasColumnName("SectionQuestionTypeId"); Property(t => t.AnswerGroupTypeId).HasColumnName("AnswerGroupTypeId"); // Relationships HasOptional(t => t.AnswerGroupType) .WithMany(t => t.SectionQuestionAnswerTypes) .HasForeignKey(d => d.AnswerGroupTypeId); HasOptional(t => t.SectionQuestionType) .WithMany(t => t.SectionQuestionAnswerTypes) .HasForeignKey(d => d.SectionQuestionTypeId); } } }
using System.Collections.Generic; using System.Xml; namespace DipDemo.Cataloguer.Infrastructure.AppController.Environment { public interface IFileSystem { void Copy(string from, string to); void Delete(string path); bool Exists(string path); IEnumerable<string> GetFiles(string directory); void CreateDirectory(string path); IList<string> GetDirectories(string path); void DeleteDirectory(string path); byte[] ReadBytes(string path); string ReadText(string path); XmlDocument ReadXml(string fileName); void WriteBytes(string path, byte[] data); void WriteText(string path, string text); void WriteXml(string path, XmlDocument doc); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SampleList; using Microsoft.Pex.Framework; using Microsoft.Pex.Framework.Settings; using Microsoft.Pex.Framework.Exceptions; using Microsoft.VisualStudio.TestTools.UnitTesting; using PexAPIWrapper; namespace SampleList.Test { [PexClass(typeof(SampleList.List))] [TestClass] public partial class ListTest { [PexMethod] public void CheckSample([PexAssumeNotNull]List l, int x) { PexObserve.ValueForViewing("$input_x", x); PexObserve.ValueForViewing("$input_Count", l.Count()); AssumePrecondition.IsTrue(!(((l.Count() <= 1)))); int oldCount = l.Count(); l.addToEnd(x); NotpAssume.IsTrue((oldCount + 1) == l.Count()); PexAssert.IsTrue((oldCount + 1) == l.Count()); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using TX.Framework.WindowUI.Forms; namespace Ljc.Com.CjzfNews.UI.SubForm { public partial class NewsSearchByTimeSpanSubForm : BaseForm { public NewsSearchByTimeSpanSubForm() { InitializeComponent(); DTStart.Text = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd"); DTEnd.Text = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"); } public DateTime StartTime { get { if (string.IsNullOrWhiteSpace(DTStart.text)) { return DateTime.MinValue; } return DateTime.Parse(DTStart.text); } } public DateTime EndTime { get { if (string.IsNullOrWhiteSpace(DTEnd.text)) { return DateTime.MinValue; } return DateTime.Parse(DTEnd.text); } } private void skinButton2_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; } private void BtnOk_Click(object sender, EventArgs e) { if (StartTime > EndTime) { TX.Framework.WindowUI.Forms.TXMessageBoxExtensions.Error("开始不能大于结束时间。"); return; } this.DialogResult = DialogResult.OK; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TeaseAI_CE.Settings { [Serializable] public class Ranges { //Tease public int minTeaseLength { get; set; } = 15; public int maxTeaseLength { get; set; } = 60; } }
using System; using KompasKeyboardPlugin; using NUnit.Framework; using NUnit.Framework.Constraints; namespace UnitTests.KompasKeyboardPlugin { /// <summary> /// Модульное тестирование класса KeyboardParameters. /// </summary> [TestFixture] public class KeyboardParametersStorageTest { /// <summary> /// Тестирование метода Record с негативными сценариями. /// </summary> /// <param name="bodyLength">Длина клавиатуры</param> /// <param name="bodyHeight">Высота клавиатуры</param> /// <param name="bodyDepth">Глубина клавиатуры</param> /// <param name="panelDisplay">Наличие дисплея</param> /// <param name="panelButtons">Наличие кнопок</param> /// <param name="panelKnobs">Наличие ручек</param> /// <param name="panelWheel">Наличие колеса модуляции</param> /// <param name="commutationXLRSockets">Количество разъемов XLR /// </param> /// <param name="commutationTRSSockets">Количество разъемов TRS /// </param> /// <param name="commutationMIDISockets">Количество разъемовMIDI /// </param> /// <param name="keyboardType">Тип клавиатуры</param> /// <param name="keyAmount">Количество клавиш</param> [Test] [TestCase(0, 0, 0, true, true, true, true, 0, 0, 0, KeyboardType.Piano, KeysAmountMode.High, TestName = "Негативный тест с нулевыми значениями")] [TestCase(double.MinValue, double.MinValue, double.MinValue, true, true, true, true, int.MinValue, int.MinValue, int.MinValue, KeyboardType.Piano, KeysAmountMode.High, TestName = "Негативный тест с минимальными значениями")] public void RecordTestNegative(double bodyLength, double bodyHeight, double bodyDepth, bool panelDisplay, bool panelButtons, bool panelKnobs, bool panelWheel, int commutationXLRSockets, int commutationTRSSockets, int commutationMIDISockets, KeyboardType keyboardType, KeysAmountMode keyAmount) { var obj = new KeyboardParametersStorage(); Assert.Throws<ArgumentException>(() => obj.Record(bodyLength, bodyHeight, bodyDepth, panelDisplay, panelButtons, panelKnobs, panelWheel, commutationXLRSockets, commutationTRSSockets, commutationMIDISockets, keyboardType, keyAmount)); } /// <summary> /// Тестирование метода Record с позитивными сценариями. /// </summary> /// <param name="bodyLength">Длина клавиатуры</param> /// <param name="bodyHeight">Высота клавиатуры</param> /// <param name="bodyDepth">Глубина клавиатуры</param> /// <param name="panelDisplay">Наличие дисплея</param> /// <param name="panelButtons">Наличие кнопок</param> /// <param name="panelKnobs">Наличие ручек</param> /// <param name="panelWheel">Наличие колеса модуляции</param> /// <param name="commutationXLRSockets">Количество разъемов XLR /// </param> /// <param name="commutationTRSSockets">Количество разъемов TRS /// </param> /// <param name="commutationMIDISockets">Количество разъемов MIDI /// </param> /// <param name="keyboardType">Тип клавиатуры</param> /// <param name="keyAmount">Количество клавиш</param> [Test] [TestCase(130, 10, 30, true, true, true, true, 1, 1, 1, KeyboardType.Piano, KeysAmountMode.High, TestName = "Позитивный тест (88 клавиш)")] [TestCase(130, 10, 30, true, true, true, true, 1, 1, 1, KeyboardType.Piano, KeysAmountMode.Middle, TestName = "Позитивный тест (76 клавиш)")] [TestCase(130, 10, 30, true, true, true, true, 1, 1, 1, KeyboardType.Piano, KeysAmountMode.Low, TestName = "Позитивный тест (61 клавиша)")] public void RecordTestPositive(double bodyLength, double bodyHeight, double bodyDepth, bool panelDisplay, bool panelButtons, bool panelKnobs, bool panelWheel, int commutationXLRSockets, int commutationTRSSockets, int commutationMIDISockets, KeyboardType keyboardType, KeysAmountMode keyAmount) { var obj = new KeyboardParametersStorage(); obj.Record(bodyLength, bodyHeight, bodyDepth, panelDisplay, panelButtons, panelKnobs, panelWheel, commutationXLRSockets, commutationTRSSockets, commutationMIDISockets, keyboardType, keyAmount); Assert.AreEqual(obj.BodyLength, bodyLength); Assert.AreEqual(obj.BodyHeight, bodyHeight); Assert.AreEqual(obj.BodyDepth, bodyDepth); Assert.AreEqual(obj.CommutationXLR, commutationXLRSockets); Assert.AreEqual(obj.CommutationTRS, commutationTRSSockets); Assert.AreEqual(obj.CommutationMIDI, commutationMIDISockets); } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using TheLastSlice.Managers; using TheLastSlice.Models; namespace TheLastSlice.Entities { //Ingredients/Toppings //AN Anchovy, BA Bacon, CH Cheese, FRR Frog Left, //FRL Frog Right, GA Garlic, GB Green Peppers, HB Habenero, //JP Jalapeno, MR Mushrooms, OL Olives, ON Onions, //PA Pineapple, PP Pepperoni, SA Sausage, TM Tomatoes public enum IngredientType { AN, BA, CH, FRR, FRL, GA, GB, HB, JP, MR, OL, ON, PA, PP, SA, TM }; public class Ingredient : Pickup { public IngredientType IngredientType { get; private set; } public Ingredient(Vector2 position, String assetCode) : base(position) { AssetCode = assetCode; PickupType = PickupType.IN; IngredientType type; Enum.TryParse(assetCode, out type); IngredientType = type; } public override void LoadTexture() { int currentLevel = TheLastSliceGame.LevelManager.CurrentLevelNum; String assetPath = ""; if (AssetCode == "UIFRL") { assetPath = "UI/" + AssetCode; } else { assetPath = "Entity/Level" + currentLevel.ToString() + "/Pickups/Ingredients/" + AssetCode; } Texture2D ingredientTexture = TheLastSliceGame.Instance.Content.Load<Texture2D>(assetPath); if (ingredientTexture != null) { int numberOfFrames = ingredientTexture.Width / ingredientTexture.Height; Texture = null; Dictionary<string, Animation> animations = new Dictionary<string, Animation>(); animations.Add("IDLE", new Animation(ingredientTexture, numberOfFrames)); Animations = new Dictionary<string, Animation>(animations); AnimationManager = new AnimationManager(Animations.First().Value); Height = (Animations.First().Value.FrameHeight); Width = (Animations.First().Value.FrameWidth); } else { Debug.WriteLine(" *** ERROR - No asset found for asset code {0}", AssetCode); } if (AssetCode == "FRL" || AssetCode == "FRR") { SoundEffect = TheLastSliceGame.Instance.Content.Load<SoundEffect>("Sounds/Frog-Hit"); } else { SoundEffect = TheLastSliceGame.Instance.Content.Load<SoundEffect>("Sounds/Pickup"); } CollisionComponent = new Rectangle((int)Position.X, (int)Position.Y, Width, Height); } protected override void SetAnimations() { if (IsFrog()) { AnimationManager.Play(Animations["IDLE"]); } } public override int GetScore() { switch (IngredientType) { case IngredientType.FRL: case IngredientType.FRR: { return 500; } default: { return 50; } } } public override void OnCollided(Entity collidedWith) { Player player = collidedWith as Player; if (player != null) { if (!player.IsInventoryFull() && !(IsFrog() && player.HeartMode)) { if (SoundEffect != null) { SoundEffect.Play(); } TheLastSliceGame.MapManager.CurrentMap.AddEntityForRemoval(this); } } } public static string ToIngredientName(IngredientType ingredientType) { switch (ingredientType) { case IngredientType.AN: return "Anchovy"; case IngredientType.BA: return "Bacon"; case IngredientType.CH: return "Cheese"; case IngredientType.GA: return "Garlic"; case IngredientType.GB: return "Green Peppers"; case IngredientType.HB: return "Habenero"; case IngredientType.JP: return "Jalapeno"; case IngredientType.MR: return "Mushrooms"; case IngredientType.OL: return "Olives"; case IngredientType.ON: return "Onions"; case IngredientType.PA: return "Pineapple"; case IngredientType.PP: return "Pepperoni"; case IngredientType.SA: return "Sausage"; case IngredientType.TM: return "Tomatoes"; default: return null; } } public bool IsFrog() { return (IngredientType == IngredientType.FRL || IngredientType == IngredientType.FRR); } } }
// Copyright 2021 Google LLC. 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.Reflection; #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member namespace NtApiDotNet.Net.Firewall { /// <summary> /// Engine option to query or set. /// </summary> [SDKName("FWPM_ENGINE_OPTION")] public enum FirewallEngineOption { [SDKName("FWPM_ENGINE_COLLECT_NET_EVENTS")] CollectNetEvents = 0, [SDKName("FWPM_ENGINE_NET_EVENT_MATCH_ANY_KEYWORDS")] NetEventMatchAnyKeywords, [SDKName("FWPM_ENGINE_NAME_CACHE")] NameCache, [SDKName("FWPM_ENGINE_MONITOR_IPSEC_CONNECTIONS")] MonitorIPsecConnections, [SDKName("FWPM_ENGINE_PACKET_QUEUING")] PacketQueuing, [SDKName("FWPM_ENGINE_TXN_WATCHDOG_TIMEOUT_IN_MSEC")] TxnWatchdogTimeoutInMsec } } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
using UnityEngine; using System.Collections; public class CameraScript : MonoBehaviour { GameObject CameraNode; GameObject puppet; float turnSpd = 45; float verTurnSpd = 25; float zoomSpd = 111; float spdAdd = 1; float scrollZoomFactor = 1; float dist = 250; float minDist = 3; float maxDist = 600; float tilt = 0; float minTilt = -10; float maxTilt = -75; Vector3 vel = new Vector3(0, 0, 0); void Start() { dist = 42; tilt = -55; //puppet.SetActive(false); } void Update() { scrollZoomFactor = dist * 0.001f; if (scrollZoomFactor < 0.1f) { scrollZoomFactor = 0.1f; } if (scrollZoomFactor > 1f) { scrollZoomFactor = 1f; } if (CameraNode == null) { //try to find a camera node CameraNode = GameObject.FindGameObjectWithTag("CameraNode"); if (CameraNode != null) { puppet = CameraNode.transform.Find("puppet").gameObject; puppet.SetActive(false); } } if (CameraNode == null) { return; } if (ChatScript.typing) { return; } //Zoom dist += -Input.GetAxis("MouseScrollWheel") * zoomSpd * Time.deltaTime; if(Input.GetKey(KeyCode.Minus)) {dist += 1f * zoomSpd * Time.deltaTime; } if(Input.GetKey(KeyCode.Equals)) {dist -= 1f * zoomSpd * Time.deltaTime; } if (dist < minDist) { dist = minDist; } if (dist > maxDist) { dist = maxDist; } //Rotate node if (Input.GetKey(KeyCode.Space)) { //spin the cameraNode horizontally CameraNode.transform.AddAngY(Input.GetAxis("Horizontal") * turnSpd * Time.deltaTime); //tilt the cameraNode vertically tilt += Input.GetAxis("Vertical") * verTurnSpd * Time.deltaTime; if (tilt < -75) { tilt = maxTilt; } if (tilt > -10) { tilt = minTilt; } } CameraNode.transform.SetAngX(tilt); //Debug.Log("tilt: " + tilt + ", y: " + CameraNode.transform.localEulerAngles.y + ", dist: " + dist); //Move node Vector3 oldAngs = CameraNode.transform.localEulerAngles; CameraNode.transform.SetAngX(0); if (Input.GetKey(KeyCode.W)) { vel.z -= spdAdd * scrollZoomFactor; } if (Input.GetKey(KeyCode.S)) { vel.z += spdAdd * scrollZoomFactor; } if (Input.GetKey(KeyCode.A)) { vel.x += spdAdd * scrollZoomFactor; } if (Input.GetKey(KeyCode.D)) { vel.x -= spdAdd * scrollZoomFactor; } CameraNode.transform.Translate(vel); CameraNode.transform.SetAngX(oldAngs.x); vel *= 0.5f; //Place camera transform.position = MathFuncs.ProjectVec(CameraNode.transform.position, CameraNode.transform.localEulerAngles, dist, Vector3.forward); //Look at CameraNode transform.LookAt(CameraNode.transform.position); } }
 namespace FloatingActionButtonXamarin { public interface IScrollDirectorListener { void OnScrollDown(); void OnScrollUp(); } }
using AutoMapper; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Whale.API.Services.Abstract; using Whale.DAL; using Whale.DAL.Models; using Whale.DAL.Settings; using Whale.Shared.Exceptions; using Whale.Shared.Extentions; using Whale.Shared.Models.Meeting; using Whale.Shared.Models.User; using Whale.Shared.Services; namespace Whale.API.Services { public class MeetingHistoryService : BaseService { private readonly BlobStorageSettings _blobStorageSettings; private readonly ElasticSearchService _elasticSearchService; public MeetingHistoryService(WhaleDbContext context, IMapper mapper, BlobStorageSettings blobStorageSettings, ElasticSearchService elasticSearchService) : base(context, mapper) { _blobStorageSettings = blobStorageSettings; _elasticSearchService = elasticSearchService; } public async Task<IEnumerable<MeetingDTO>> GetMeetingsWithParticipantsAndPollResultsAsync(Guid userId, int skip, int take) { var meetings = await _context.Participants .Include(p => p.Meeting) .ThenInclude(m => m.PollResults) .Where(p => p.UserId == userId && p.Meeting.EndTime != null && p.Meeting.EndTime != p.Meeting.StartTime) .Select(p => p.Meeting) .OrderByDescending(m => m.StartTime) .Skip(skip) .Take(take) .ToListAsync(); var allParticipnts = await _context.Participants.Include(p => p.User).ToListAsync(); var meetingTasks = meetings .GroupJoin( allParticipnts, m => m.Id, p => p.MeetingId, (m, pGroup) => new Meeting(m, pGroup)) .AsParallel() .Select(async m => { m.Participants = await m.Participants.LoadAvatarsAsync(_blobStorageSettings, p => p.User); var mDto = _mapper.Map<MeetingDTO>(m); var stats = await _elasticSearchService.SearchSingleAsync(userId, m.Id); if (stats != null) { mDto.SpeechDuration = stats.SpeechTime; mDto.PresenceDuration = stats.PresenceTime; } return mDto; }); var meetingList = await Task.WhenAll(meetingTasks); return meetingList; } public async Task<IEnumerable<MeetingSpeechDTO>> GetMeetingScriptAsync(Guid meetingId) { var scriptJson = await _context.MeetingScripts.FirstOrDefaultAsync(m => m.MeetingId == meetingId); if (scriptJson is null) throw new NotFoundException("MeetingScripts", meetingId.ToString()); var script = JsonConvert.DeserializeObject<IEnumerable<MeetingSpeech>>(scriptJson.Script); var scriptTasks = script.OrderBy(m => m.SpeechDate).Join(_context.Users, m => m.UserId, u => u.Id, async (m, u) => new MeetingSpeechDTO { User = _mapper.Map<UserDTO>(await u.LoadAvatarAsync(_blobStorageSettings)), Message = m.Message, SpeechDate = m.SpeechDate } ); return (await Task.WhenAll(scriptTasks)).ToList(); } } }
using System.Data.Entity.ModelConfiguration; using RMAT3.Models; namespace RMAT3.Data.Mapping { public class PartyCertificationMap : EntityTypeConfiguration<PartyCertification> { public PartyCertificationMap() { // Primary Key HasKey(t => t.PartyCertificationId); // Properties Property(t => t.AddedByUserId) .IsRequired() .HasMaxLength(20); Property(t => t.UpdatedByUserId) .IsRequired() .HasMaxLength(20); Property(t => t.CertificationTxt) .HasMaxLength(100); Property(t => t.JurisdictionStateCd) .HasMaxLength(50); // Table & Column Mappings ToTable("PartyCertification", "OLTP"); Property(t => t.PartyCertificationId).HasColumnName("PartyCertificationId"); Property(t => t.AddedByUserId).HasColumnName("AddedByUserId"); Property(t => t.AddTs).HasColumnName("AddTs"); Property(t => t.UpdatedByUserId).HasColumnName("UpdatedByUserId"); Property(t => t.UpdatedTs).HasColumnName("UpdatedTs"); Property(t => t.IsActiveInd).HasColumnName("IsActiveInd"); Property(t => t.CertificationNbr).HasColumnName("CertificationNbr"); Property(t => t.CertificationTxt).HasColumnName("CertificationTxt"); Property(t => t.JurisdictionStateCd).HasColumnName("JurisdictionStateCd"); Property(t => t.PartyId).HasColumnName("PartyId"); Property(t => t.CertificationTypeId).HasColumnName("CertificationTypeId"); // Relationships HasRequired(t => t.CertificationType) .WithMany(t => t.PartyCertifications) .HasForeignKey(d => d.CertificationTypeId); HasRequired(t => t.Party) .WithMany(t => t.PartyCertifications) .HasForeignKey(d => d.PartyId); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class Movimiento_pelota1 : MonoBehaviour { public bool ver; public bool hor; public bool inicio; public bool juego; public bool gana_vida; public float limite_ver; public float limite_ver_n; public float velocidad; public float limite_hor; public float limite_hor_n; public Transform pos_inicial; public int vida ; public Text text_vida; public Text text_puntos; public Text text_terminado; public GameObject player; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (juego) { // _____________________MOVIMIENTO_____ VERTICAL___________________________________ if (ver) { transform.Translate (Vector2.up * (velocidad * Time.deltaTime)); if (transform.position.y >= limite_ver) { ver = false; } } else { transform.Translate (Vector2.down * (velocidad * Time.deltaTime)); if (transform.position.y <= limite_ver_n) { } } // _____________________MOVIMIENTO_____ HORIZONTAL___________________________________ if (hor) { transform.Translate (Vector2.left * (velocidad * Time.deltaTime)); if (transform.position.x <= limite_hor_n) { hor = false; } } else { transform.Translate (Vector2.right * (velocidad * Time.deltaTime)); if (transform.position.x >= limite_hor) { hor = true; } } // _____________________POSICION _____INICIAL___________________________________ if (transform.position.y <= limite_ver_n) { // Global.vida = Global.vida - 1; //text_vida.text = Global.vida.ToString (); //inicio = true; } } } void OnTriggerEnter2D (Collider2D contacto) { if (contacto.gameObject.tag == "Player") { ver = true; velocidad += 0.2f; } if (contacto.gameObject.tag == "Ladrillo") { Global.puntos = Global.puntos + 1; text_puntos.text = Global.puntos.ToString (); velocidad += 0.1f; contacto.gameObject.SetActive(false); if (ver) { ver = false; } else { ver = true; } } if (contacto.gameObject.tag == "Ladrillo2") { Global.puntos = Global.puntos + 3; text_puntos.text = Global.puntos.ToString(); velocidad += 0.2f; contacto.gameObject.SetActive(false); if (ver) { ver = false; } else { ver = true; } } if (contacto.gameObject.tag == "Ladrillo3") { Global.puntos = Global.puntos + 5; text_puntos.text = Global.puntos.ToString(); velocidad += 0.3f; contacto.gameObject.SetActive(false); if (ver) { ver = false; } else { ver = true; } } } void sumar_vida() { if (gana_vida) { Global.vida = Global.vida + 1; text_vida.text = Global.vida.ToString(); gana_vida = false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TDD { class BankAccount { static void Main(string[] args) { } public static void Deposit(int amount) { } public static int Withdrawal(int amount) { if (amount <= 1000) { return amount; } else { return -1; } //return amount; } public static bool CheckPassword() { return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FiasWebApi.Model { public interface ISearchRepository { IEnumerable<AddressObject> GetFullNameBySearchString(string searchString, int limit = 0); IEnumerable<Words> GetWordsBySearchString(string searchString, int limit = 0); IEnumerable<House> GetHouseByAoGuid(Guid aoGuid); } }
using System; namespace Biggy { public class PrimaryKeyAttribute : Attribute { public PrimaryKeyAttribute(bool Auto) { this.IsAutoIncrementing = Auto; } public bool IsAutoIncrementing { get; private set; } } }
using System; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Automatron.Interfaces.Workflow.Nodes { /// <summary> /// All workflow elements which contains Left connector / Input /// </summary> public interface IHasLeftPoint<TSettings> : IWorkflowElement<TSettings> where TSettings : IWorkflowElementSettings { string Execute(IWorkflowElementSettings a_settings); } }
using System; using System.ComponentModel; using Abp.AutoMapper; namespace MyCompanyName.AbpZeroTemplate.Card.Dtos { /// <summary> /// 订单表编辑用Dto /// </summary> [AutoMap(typeof(Biz_CardInfo))] public class Biz_CardInfoEditDto { /// <summary> /// 主键Id /// </summary> [DisplayName("主键Id")] public long? Id { get; set; } /// <summary> /// 身份证号码 /// </summary> [DisplayName("身份证号码")] public string IdCard { get; set; } /// <summary> /// 姓名 /// </summary> [DisplayName("姓名")] public string RealName { get; set; } /// <summary> /// 客户订单号 /// </summary> public string OrderNum { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Billboard : MonoBehaviour { public Transform cam; private GameObject mainCamera; void Start() { mainCamera = GameObject.FindGameObjectWithTag("MainCamera"); cam = mainCamera.transform; } void LateUpdate() { transform.LookAt(transform.position + cam.forward); } }
using System; using System.Collections.Generic; using System.IO; namespace RO { [CustomLuaClass] public class FileIOHelper { public static void AppendBytes(string path, byte[] datas, bool writeLength) { FileStream fileStream; if (File.Exists(path)) { fileStream = new FileStream(path, 6); } else { fileStream = new FileStream(path, 4); } if (writeLength) { BinaryWriter binaryWriter = new BinaryWriter(fileStream); binaryWriter.Write(datas.Length); binaryWriter.Write(datas); binaryWriter.Close(); } else { fileStream.Write(datas, 0, datas.Length); } fileStream.Close(); } public static byte[][] OpenRead(string path, bool readLength) { if (File.Exists(path)) { List<byte[]> list = new List<byte[]>(); FileStream fileStream = File.OpenRead(path); BinaryReader binaryReader = new BinaryReader(fileStream); while (binaryReader.get_BaseStream().get_Position() < binaryReader.get_BaseStream().get_Length()) { int num = binaryReader.ReadInt32(); byte[] array = binaryReader.ReadBytes(num); list.Add(array); } return list.ToArray(); } return null; } public static byte[][] ReadBytes(string path) { byte[][] bytes = null; FileStream fs = null; FileDirectoryHandler.LoadFile(path, delegate(FileStream x) { fs = x; if (fs != null) { List<byte[]> list = new List<byte[]>(); BinaryReader binaryReader = new BinaryReader(fs); try { while (binaryReader.get_BaseStream().get_Position() < binaryReader.get_BaseStream().get_Length()) { int num = binaryReader.ReadInt32(); if (num < 0) { LoggerUnused.Log("FileIOHelper ReadBytes : length < 0"); break; } byte[] array = binaryReader.ReadBytes(num); list.Add(array); } } catch (EndOfStreamException ex) { LoggerUnused.Log("FileIOHelper ReadBytes " + ex.get_Message().ToString()); } bytes = list.ToArray(); } }); return bytes; } } }
// GIMP# - A C# wrapper around the GIMP Library // Copyright (C) 2004-2009 Maurits Rijk // // Selection.cs // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. // using System; using System.Runtime.InteropServices; namespace Gimp { public sealed class Selection : Channel { readonly Int32 _imageID; internal Selection(Int32 imageID, Int32 selectionID) : base(selectionID) { _imageID = imageID; } /// <summary> /// Find the bounding box of the current selection /// </summary> /// <param name="nonEmpty"></param> /// <param name="x1"></param> /// <param name="y1"></param> /// <param name="x2"></param> /// <param name="y2"></param> public new void Bounds(out bool nonEmpty, out int x1, out int y1, out int x2, out int y2) { if (!gimp_selection_bounds(_imageID, out nonEmpty, out x1, out y1, out x2, out y2)) { throw new GimpSharpException(); } } public new Rectangle Bounds(out bool nonEmpty) { int x1, y1, x2, y2; Bounds(out nonEmpty, out x1, out y1, out x2, out y2); return new Rectangle(x1, y1, x2, y2); } public void All() { if (!gimp_selection_all(_imageID)) { throw new GimpSharpException(); } } public void None() { if (!gimp_selection_none(_imageID)) { throw new GimpSharpException(); } } public bool Empty { get {return gimp_selection_is_empty(_imageID);} } public Layer Float(Drawable drawable, int offx, int offy) { return new Layer(gimp_selection_float(_imageID, drawable.ID, offx, offy)); } public void Load(Channel channel) { if (!gimp_selection_load(channel.ID)) { throw new GimpSharpException(); } } public Channel Save() { return new Channel(gimp_selection_save(_imageID)); } public int Value(int x, int y) { return gimp_selection_value(_imageID, x, y); } public int this[int x, int y] { get {return Value(x, y);} } public void Grow(int steps) { if (!gimp_selection_grow(_imageID, steps)) { throw new GimpSharpException(); } } public void Shrink(int radius) { if (!gimp_selection_shrink(_imageID, radius)) { throw new GimpSharpException(); } } public new void Invert() { if (!gimp_selection_invert(_imageID)) { throw new GimpSharpException(); } } public void Feather(double radius) { if (!gimp_selection_feather(_imageID, radius)) { throw new GimpSharpException(); } } public void Sharpen() { if (!gimp_selection_sharpen(_imageID)) { throw new GimpSharpException(); } } public void Border(int radius) { if (!gimp_selection_border(_imageID, radius)) { throw new GimpSharpException(); } } public void Translate(int offx, int offy) { if (!gimp_selection_translate(_imageID, offx, offy)) { throw new GimpSharpException(); } } public void Translate(Offset offset) { Translate(offset.X, offset.Y); } public void LayerAlpha(Layer layer) { if (!gimp_selection_layer_alpha(layer.ID)) { throw new GimpSharpException(); } } public void Combine(Channel channel, ChannelOps operation) { if (!gimp_selection_combine(channel.ID, operation)) { throw new GimpSharpException(); } } [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_selection_bounds (Int32 image_ID, out bool non_empty, out int x1, out int y1, out int x2, out int y2); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_selection_all (Int32 image_ID); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_selection_none (Int32 image_ID); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_selection_is_empty (Int32 image_ID); [DllImport("libgimp-2.0-0.dll")] extern static Int32 gimp_selection_float (Int32 image_ID, Int32 drawable_ID, int offx, int offy); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_selection_load (Int32 channel_ID); [DllImport("libgimp-2.0-0.dll")] extern static Int32 gimp_selection_save (Int32 image_ID); [DllImport("libgimp-2.0-0.dll")] extern static int gimp_selection_value (Int32 image_ID, int x, int y); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_selection_grow (Int32 image_ID, int steps); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_selection_shrink (Int32 image_ID, int radius); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_selection_invert (Int32 image_ID); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_selection_feather (Int32 image_ID, double radius); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_selection_sharpen (Int32 image_ID); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_selection_border (Int32 image_ID, int radius); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_selection_translate (Int32 image_ID, int offx, int offy); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_selection_layer_alpha (Int32 layer_ID); [DllImport("libgimp-2.0-0.dll")] extern static bool gimp_selection_combine (Int32 channel_ID, ChannelOps operation); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EARQ = EAAddinFramework.Requirements; using TSF.UmlToolingFramework.Wrappers.EA; using RequirementsFramework; using System.Net.Http; namespace EAAddinFramework.Requirements.DoorsNG { public class DoorsNGFolder : EARQ.Folder { private DoorsNGProject doorsNGProject { get => (DoorsNGProject)this.project; } public DoorsNGFolder(Package wrappedPackage, DoorsNGProject project, DoorsNGFolder parentFolder):base(wrappedPackage, project, parentFolder) { this.wrappedPackage = wrappedPackage; this.project = project; this.parentFolder = parentFolder; } public string url { //TODO: implement get; set; } private List<Requirement> _requirements; public override IEnumerable<RequirementsFramework.Requirement> requirements { get { if (_requirements == null) { this._requirements = this.getRequirementsDoorsNG(); } return _requirements; } set { this._requirements = value.Cast<Requirement>().ToList(); } } private List<Requirement> getRequirementsDoorsNG() { var serverRequirements = new List<Requirement>(); //first make sure we are authenticated HttpClient client = this.doorsNGProject.Authenticate(); return null; } public override Folder createNewFolder(Package wrappedPackage, Project project, Folder parentFolder) { throw new NotImplementedException(); } } }
using Ghost.Extensions; using System; using UnityEngine; namespace RO { [CustomLuaClass] public class SceneInitializer : MonoBehaviour { public GameObject[] dontDestroyPrefabs; public GameObject[] prefabs; private void Awake() { if (!this.dontDestroyPrefabs.IsNullOrEmpty<GameObject>()) { Transform transform = (!(null != SingleTonGO<LuaLuancher>.Me)) ? null : SingleTonGO<LuaLuancher>.Me.get_transform(); for (int i = 0; i < this.dontDestroyPrefabs.Length; i++) { GameObject gameObject = this.dontDestroyPrefabs[i]; if (null != gameObject) { GameObject gameObject2 = Object.Instantiate<GameObject>(gameObject); if (null != transform) { gameObject2.get_transform().SetParent(transform); } else { Object.DontDestroyOnLoad(gameObject2); } } } } if (!this.prefabs.IsNullOrEmpty<GameObject>()) { for (int j = 0; j < this.prefabs.Length; j++) { GameObject gameObject3 = this.prefabs[j]; if (null != gameObject3) { GameObject gameObject4 = Object.Instantiate<GameObject>(gameObject3); } } } if (null != SingleTonGO<LuaLuancher>.Me) { SingleTonGO<LuaLuancher>.Me.Call("OnSceneAwake", new object[] { this }); } } private void Start() { if (null != SingleTonGO<LuaLuancher>.Me) { SingleTonGO<LuaLuancher>.Me.Call("OnSceneStart", new object[] { this }); } Object.Destroy(base.get_gameObject()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MessingWithInterfaces { public interface IPokable { bool WasPoked { get; set; } } public class Person: IPokable { public string FirstName { get; set; } public string LastName { get; set; } public bool WasPoked { get; set; } public Person(bool wasPoked) { WasPoked = wasPoked; } public void Poke(IPokable pokable) { new PokeHelper().HandlePokeOn(pokable); } } internal class PokeHelper { internal void HandlePokeOn(IPokable pokable) { pokable.WasPoked = true; } } }
using System; using System.ComponentModel.DataAnnotations; namespace ImmedisHCM.Web.Models { public class CountryViewModel { public Guid Id { get; set; } public string Name { get; set; } public string ShortName { get; set; } [Display(Name = "Country")] public string CombinedName => $"{Name} ({ShortName})"; } }
// ----------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root // for license information. // </copyright> // ----------------------------------------------------------------------- // // This file provides optional assembly wide annotations for both the codegen output and the // compiled SettingsRegistry assembly dll. using System.Runtime.CompilerServices; using Mlos.SettingsSystem.Attributes; // This is ths namespace used for the C++ codegen output for the messages and settings in this // Settings Registry. [assembly: DispatchTableNamespace(@namespace: "ExternalIntegrationExample")]
using System; using System.Collections.Generic; using System.Text; namespace Json { public class Text : IPattern { readonly string prefix; public Text(string prefix) { this.prefix = prefix; } public IMatch Match(string text) { if(string.IsNullOrEmpty(text) || text.Length < prefix.Length || !text.StartsWith(prefix)) { return new Match(text, false); } return new Match(text[prefix.Length..], true); } } }
using System.Web; using Idealize.Web.Models; using Microsoft.AspNetCore.Http; using Sistema.Arquitetura.Library.Core.Util.Security; namespace Idealize.Web.Models { public static class SecurityHelper { public static ObjectSecurity GetObjectSecurity() { User obj = new User(); return (new ObjectSecurity() { UserSystem = obj.CodUsuario, IdAluno = obj.CodUsuario, Login = obj.Login, Nome = obj.NomeUsuario }); } public static void SetUserLogged(User objUsuario) { //HttpContext.Current.Session["UsuarioLogado"] = objUsuario; //HttpContext.Current.Session["CodUsuario"] = objUsuario.CodUsuario; //HttpContext.Current.Session["Login"] = objUsuario.Login; //HttpContext.Current.Session["cpf"] = objUsuario.CPF; } public static User getUserLogged() { //if (HttpContext.Current != null && HttpContext.Current.Session["UsuarioLogado"] is User) //{ // User obj = (User)HttpContext.Current.Session["UsuarioLogado"]; // return obj; //} return new User(); } } }
using Imposto.Core.Service; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Imposto.Core.Domain; using Imposto.Core.Data; namespace TesteImposto { public partial class FormNotaFiscal: Form { private NotaFiscal notaFiscal; private Pedido pedido = new Pedido(); private NotaFiscalService service; public FormNotaFiscal(NotaFiscal notaFiscal, NotaFiscalService service) { this.notaFiscal = notaFiscal; this.service = service; InitializeComponent(); dataGridViewPedidos.AutoGenerateColumns = true; dataGridViewPedidos.DataSource = GetTablePedidos(); ResizeColumns(); CarregarDadosNotaFiscal(notaFiscal); ControleBotoes(this.notaFiscal.Id == 0); } private void ResizeColumns() { double mediaWidth = dataGridViewPedidos.Width / dataGridViewPedidos.Columns.GetColumnCount(DataGridViewElementStates.Visible); for (int i = dataGridViewPedidos.Columns.Count - 1; i >= 0; i--) { var coluna = dataGridViewPedidos.Columns[i]; coluna.Width = Convert.ToInt32(mediaWidth); } } private object GetTablePedidos() { DataTable table = new DataTable("pedidos"); table.Columns.Add(new DataColumn("Nome do produto", typeof(string))); table.Columns.Add(new DataColumn("Codigo do produto", typeof(string))); table.Columns.Add(new DataColumn("Valor", typeof(decimal))); table.Columns.Add(new DataColumn("Brinde", typeof(bool))); return table; } private void buttonGerarNotaFiscal_Click(object sender, EventArgs e) { if (!Validacao()) return; pedido.EstadoOrigem = txtEstadoOrigem.Text; pedido.EstadoDestino = txtEstadoDestino.Text; pedido.NomeCliente = textBoxNomeCliente.Text; DataTable table = (DataTable)dataGridViewPedidos.DataSource; foreach (DataRow row in table.Rows) { var boolValue = false; pedido.ItensDoPedido.Add( new PedidoItem() { Brinde = bool.TryParse(row["Brinde"].ToString(), out boolValue), CodigoProduto = row["Codigo do produto"].ToString(), NomeProduto = row["Nome do produto"].ToString(), ValorItemPedido = Convert.ToDouble(row["Valor"].ToString()) }); } string retorno = service.GerarNotaFiscal(pedido); if (string.IsNullOrEmpty(retorno)) { MessageBox.Show("Operação efetuada com sucesso"); LimparTela(); } else MessageBox.Show(retorno, "Ocorreu um erro", MessageBoxButtons.OK, MessageBoxIcon.Error); } private void LimparTela() { txtEstadoOrigem.Text = string.Empty; txtEstadoDestino.Text = string.Empty; textBoxNomeCliente.Text = string.Empty; DataTable table = (DataTable)dataGridViewPedidos.DataSource; table.Clear(); } private void buttonSair_Click(object sender, EventArgs e) { Close(); } private void buttonCancelar_Click(object sender, EventArgs e) { LimparTela(); } private bool Validacao() { if (!Util.ValidaCliente(textBoxNomeCliente.Text)) { MessageBox.Show("É necessário informar um Cliente válido", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } if (!Util.ValidaUF(txtEstadoOrigem.Text) || !Util.ValidaUF(txtEstadoDestino.Text)) { MessageBox.Show("É necessário informar UFs válidos.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } return true; } private void CarregarDadosNotaFiscal(NotaFiscal notaFiscal) { if (notaFiscal.NumeroNotaFiscal > 0) { textBoxNomeCliente.Text = notaFiscal.NomeCliente; txtEstadoOrigem.Text = notaFiscal.EstadoOrigem; txtEstadoDestino.Text = notaFiscal.EstadoDestino; dataGridViewPedidos.DataSource = Repository.ObterNotaFiscalItens(notaFiscal.NumeroNotaFiscal); } } private void ControleBotoes(bool habilita) { textBoxNomeCliente.Enabled = habilita; txtEstadoOrigem.Enabled = habilita; txtEstadoDestino.Enabled = habilita; dataGridViewPedidos.ReadOnly = habilita; buttonGerarNotaFiscal.Visible = habilita; buttonCancelar.Visible = habilita; } } }
using System; using System.Collections.Generic; namespace App1 { public interface IMp3Player : IDisposable { event EventHandler PlayMp3Completed; string MP3Value { get; set; } void Play(); void Pause(); void Stop(); void Seek(double position); double Duration { get; } double CurrentPosition { get; } bool IsPlaying { get; } bool CanSeek { get; } double Volume { get; set; } double Balance { get; set; } List<string> GetMusic(); } }
using System; using System.Text.RegularExpressions; using System.Windows.Media; using System.Windows.Media.Imaging; using WMagic; using WMaper.Base; using WMaper.Meta.Param; using WMaper.Plat; using WMaper.Proj.Epsg; namespace WMaper.Protocol { /// <summary> /// 天地图瓦片类 /// </summary> public sealed class MapWorld : Tile { private static readonly Regex AMEND_REGEX = new Regex("^(VEC|TER)$", RegexOptions.IgnoreCase); private static readonly Regex STYLE_REGEX = new Regex("^(VEC|IMG|TER|C(V|I|T)A)$", RegexOptions.IgnoreCase); #region 变量 // 地图类型 private string style; #endregion #region 属性方法 public string Style { get { return this.style; } set { if (MapWorld.STYLE_REGEX.IsMatch(value)) { this.style = value.ToLower(); } } } #endregion #region 构造函数 public MapWorld() : base() { // 默认配置 this.Radix = 1; this.Close = 19; this.Style = "vec"; this.Units = WMaper.Units.DD; this.Projcs = new EPSG_4326(); this.Origin = new Coord(-180, 90); this.Extent = new Bound(new Coord(-180, 90), new Coord(180, -90)); this.Factor = new double[] { 0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625, 0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625, 6.866455078125E-4, 3.4332275390625E-4, 1.71661376953125E-4, 8.58306884765625E-5, 4.291534423828125E-5, 2.1457672119140625E-5, 1.0728836059570313E-5, 5.36441802978515625E-6, 2.682209014892578E-6 }; } public MapWorld(Option option) : this() { if (!MatchUtils.IsEmpty(option)) { // 用户配置 if (option.Exist("Index")) this.Index = option.Fetch<string>("Index"); if (option.Exist("Group")) this.Group = option.Fetch<string>("Group"); if (option.Exist("Title")) this.Title = option.Fetch<string>("Title"); if (option.Exist("Style")) this.Style = option.Fetch<string>("Style"); if (option.Exist("Allow")) this.Allow = option.Fetch<bool>("Allow"); if (option.Exist("Cover")) this.Cover = option.Fetch<bool>("Cover"); if (option.Exist("Alarm")) this.Alarm = option.Fetch<bool>("Alarm"); if (option.Exist("Speed")) this.Speed = option.Fetch<int>("Speed"); if (option.Exist("Alpha")) this.Alpha = option.Fetch<int>("Alpha"); if (option.Exist("Level")) this.Level = option.Fetch<int>("Level"); if (option.Exist("Close")) this.Close = option.Fetch<int>("Close"); if (option.Exist("Start")) this.Start = option.Fetch<int>("Start"); if (option.Exist("Extent")) this.Extent = option.Fetch<Bound>("Extent"); } } #endregion #region 函数方法 protected sealed override ImageSource Repair(int l, int r, int c) { return new BitmapImage(new Uri("http://api.tianditu.com/img/" + (MapWorld.AMEND_REGEX.IsMatch(this.style) ? this.style : "") + "404.png", UriKind.Absolute)); } protected sealed override string Source(int l, int r, int c) { return "http://t" + (new Random()).Next(0, 7) + ".tianditu.com/" + this.Style + "_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=" + this.Style + "&STYLE=default&TILEMATRIXSET=c&TILEMATRIX=" + (this.Radix + this.Start + l) + "&TILEROW=" + r + "&TILECOL=" + c + "&FORMAT=tiles"; } #endregion } }
using System.Collections.ObjectModel; namespace Hsp.Mvvm.UiModel { public class UiCommandPage : ObservableEntity { public ObservableCollection<UiCommandGroup> Groups { get; } public string Caption { get { return GetAutoFieldValue<string>(); } set { SetAutoFieldValue(value); } } public bool Visible { get { return GetAutoFieldValue<bool>(); } set { SetAutoFieldValue(value); } } public UiCommandPage(params UiCommandGroup[] groups) { Groups = new ObservableCollection<UiCommandGroup>(); foreach (var group in groups) Groups.Add(group); Visible = true; } public UiCommandPage(string caption, params UiCommandGroup[] groups) : this(groups) { Caption = caption; } } }
using System; using System.Collections.Generic; using System.Text; using OCP.FullTextSearch.Model; namespace OCP.FullTextSearch.Service { /** * Interface IIndexService * * @since 15.0.0 * * @package OCP\FullTextSearch\Service */ public interface IIndexService { /** * Create an Index * * @since 15.0.1 * * @param string providerId * @param string documentId * @param string userId * @param int status * @return IIndex */ IIndex createIndex(string providerId, string documentId, string userId, int status); /** * Retrieve an Index from the database, based on the Id of the Provider * and the Id of the Document * * @since 15.0.0 * * @param string providerId * @param string documentId * * @return IIndex */ IIndex getIndex(string providerId, string documentId); /** * Update the status of an Index. status is a bit flag, setting reset to * true will reset the status to the value defined in the parameter. * * @since 15.0.0 * * @param string providerId * @param string documentId * @param int status * @param bool reset */ void updateIndexStatus(string providerId, string documentId, int status, bool reset = false); /** * Update the status of an array of Index. status is a bit flag, setting reset to * true will reset the status to the value defined in the parameter. * * @since 15.0.0 * * @param string providerId * @param array documentIds * @param int status * @param bool reset */ void updateIndexesStatus(string providerId, IList<string> documentIds, int status, bool reset = false); /** * Update an array of Index. * * @since 15.0.0 * * @param array indexes */ void updateIndexes(IList<string> indexes); } }
using System; namespace TaylorBurchLab5 { class MainClass { public static void Main(string[] args) { string[] deck = new string[52]; string[] suite = { "Hearts", "Spades", "Diamonds", "Clubs" }; string[] valueNum = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" }; bool play = getRunProgram(); //Ask user if they want to shuffle cards while (play == true) { populateDeck(deck, suite, valueNum); //Populate the deck of cards in order Console.WriteLine("Here is a full deck of cards.----------------------------------"); displayDeck(deck); //Show that deck of cards is all there to user shuffleDeck(deck); //Shuffle the cards using swap method Console.WriteLine("Here is the shuffled deck. ------------------------------------"); displayDeck(deck); //Display the shuffled deck play = getRunProgram(); //Ask user to shuffle another deck Y/N } } static bool getRunProgram() { char userInput = 'q'; Console.WriteLine("Do you want to shuffle a deck? Enter Y for Yes or any other key to quit."); userInput = char.Parse(Console.ReadLine()); if (userInput == 'y' || userInput == 'Y') { return true; } else { return false; } } static void populateDeck(string[] deck, string[] suite, string[] valueNum) { int i = 0; for (int x = 0; x < suite.Length; x++) //For every suite out of the four total { for (int y = 0; y < valueNum.Length; y++) //And for every value possible { deck[i] = valueNum[y] + " of " + suite[x]; //Take the value and suite and put them together into deck i++; } //Repeated until all values added for each suite } } static void displayDeck(string[] deck) { for (int i = 0; i < deck.Length; i++) { Console.WriteLine(deck[i]); //Write out all of the deck array's length } } static void shuffleDeck(string[] deck) { string temp = null; Random num = new Random(); int n = deck.Length; while (n > 1) { int k = num.Next(n); n--; temp = deck[n]; deck[n] = deck[k]; deck[k] = temp; } } } }
using System; namespace ControlStatements92 { class Program { static void Main() { char ch; for(ch='A'; ch <= 'E'; ch++) switch (ch) { case 'A': Console.WriteLine("ch is A"); break; case 'B': Console.WriteLine("ch is B"); break; case 'C': Console.WriteLine("ch is C"); break; case 'D': Console.WriteLine("ch is D"); break; case 'E': Console.WriteLine("ch is E"); break; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace MyCore { public class CharacterCommandMoveToTarget : CharacterCommand { public CharacterCommandMoveToTarget(PlayerCharacter character) : base(character) { } public override void OnStart() { m_character.MoveToTarget(); } public override void OnUpdate() { if(Vector3.Distance(m_character.transform.position, m_character.target.transform.position) < 0.3f) { m_isEnd = true; } } public override void OnEnd() { m_character.MoveEnd(); } } }
using System; using System.Collections.Generic; using System.Text; namespace AppSettingsGenerator { internal class ConfigurationExtensionsModel { public ConfigurationExtensionsModel(string type, string propertyPath, string sanitizedName, string name) { Type = type; PropertyPath = propertyPath; SanitizedName = sanitizedName; Name = name; } public string Type { get; } public string PropertyPath { get; } public string SanitizedName { get; } public string Name { get; } } internal class ConfigurationExtensionsMainModel { public List<ConfigurationExtensionsModel> Properties { get; } public ConfigurationExtensionsMainModel(List<ConfigurationExtensionsModel> properties) { Properties = properties; } } class ConfigurationExtensionsModelComparer : IEqualityComparer<ConfigurationExtensionsModel> { public bool Equals(ConfigurationExtensionsModel x, ConfigurationExtensionsModel y) { return x.Name == y.Name || x.SanitizedName == y.SanitizedName; } public int GetHashCode(ConfigurationExtensionsModel obj) { return obj.SanitizedName.GetHashCode(); } } }
using UnityEngine; public class LaserBlast : Projectile { public float Speed { get; } public float Duration { get; } private float currentAge; public LaserBlast(float speed, float duration, float damage, float radius, GameObject gameObject) :base(damage, radius, gameObject) { Speed = speed; Duration = duration; } public void Fire(Vector3 position, Quaternion rotation) { currentAge = 0; this.isActive = true; GameObject.transform.position = position; GameObject.transform.rotation = rotation; } public override void MoveEntity() { Vector3 movement = this.GameObject.transform.forward * Speed; this.GameObject.transform.position += movement; } protected override ProjectileKey MakeKeyFromCurrentState() { float progression = currentAge / Duration; return new ProjectileKey(GameObject.transform.position, GameObject.transform.rotation, progression); } public override void UpdateState() { currentAge += 1; this.isActive = currentAge < Duration; } public override void OnSpaceshipHit(SpaceShip spaceship) { this.isActive = false; } }
namespace Decorator { public class BananaDecorator : PancakeDecorator { public BananaDecorator(Pancake pancake) : base(pancake) { } public override double CalculateCalories() { return this.Pancake.CalculateCalories() + 33.30; } public override string GetDescription() { return this.Pancake.GetDescription() + "\n\t + banana;"; } } }
using System; using Service; using MKModel; using System.Collections.ObjectModel; using ReDefNet; using System.Runtime.Serialization; using MKService.Updates; namespace MKService.Messages { public class UserSignUp : MessageBase { [DataMember] public string UserName { get; set; } [DataMember] public string Password { get; set; } [DataMember] public Guid Id { get; set; } } }
// Copyright 2021 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.Win32.DirectoryService; using NtApiDotNet.Win32.Security.Authorization; namespace NtObjectManager.Cmdlets.Accessible { /// <summary> /// Access check result for an object type. /// </summary> public sealed class DsObjectTypeAccessCheckResult<T> where T : IDirectoryServiceObjectTree { /// <summary> /// The object for the access check. /// </summary> public T Object { get; } /// <summary> /// The granted access. /// </summary> public DirectoryServiceAccessRights GrantedAccess { get; } /// <summary> /// Indicates if a specific access has been granted. /// </summary> /// <param name="access">The access to check.</param> /// <returns>True if access granted.</returns> public bool IsAccessGranted(DirectoryServiceAccessRights access) { return GrantedAccess.HasFlag(access); } /// <summary> /// Overridden ToString method. /// </summary> /// <returns>The name of the object.</returns> public override string ToString() { return Object.Name; } internal DsObjectTypeAccessCheckResult(T obj, AuthZAccessCheckResult result) { Object = obj; GrantedAccess = result.GrantedAccess.ToSpecificAccess<DirectoryServiceAccessRights>(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace MPD.Entities.Domain { public partial class JobComment { public Guid JobCommentId { get; set; } public Guid JobQuoteId { get; set; } [Required] public string Comment { get; set; } public Guid CommentBy { get; set; } public bool IsDeleted { get; set; } [Column(TypeName = "smalldatetime")] public DateTime CreatedDate { get; set; } [Column(TypeName = "smalldatetime")] public DateTime ModifiedDate { get; set; } [ForeignKey("CommentBy")] [InverseProperty("JobComment")] public UserLogin CommentByNavigation { get; set; } [ForeignKey("JobQuoteId")] [InverseProperty("JobComment")] public JobQuote JobQuote { get; set; } } }
using System.Diagnostics.CodeAnalysis; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Ioc; using Microsoft.Practices.ServiceLocation; using OltivaHotel.PCL.Design; using OltivaHotel.PCL.Model; using OltivaHotel.PCL.ViewModel; using OltivaHotel.WP.Services; namespace OltivaHotel.WP.ViewModel { public class ViewModelLocator { static ViewModelLocator() { ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); if (!SimpleIoc.Default.IsRegistered<IDownloader>()) SimpleIoc.Default.Register<IDownloader, Downloader>(); if (!SimpleIoc.Default.IsRegistered<INotificationService>()) SimpleIoc.Default.Register<INotificationService, NotificationService>(); if (ViewModelBase.IsInDesignModeStatic) { SimpleIoc.Default.Register<IDataService, DesignDataService>(); } else { SimpleIoc.Default.Register<IDataService, DataService>(); } SimpleIoc.Default.Register<MainViewModel>(); SimpleIoc.Default.Register<MenuViewModel>(); SimpleIoc.Default.Register<OrderViewModel>(); } [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This non-static member is needed for data binding purposes.")] public MainViewModel Main { get { return ServiceLocator.Current.GetInstance<MainViewModel>(); } } [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This non-static member is needed for data binding purposes.")] public MenuViewModel MenuViewModel { get { return ServiceLocator.Current.GetInstance<MenuViewModel>(); } } [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This non-static member is needed for data binding purposes.")] public OrderViewModel OrderViewModel { get { return ServiceLocator.Current.GetInstance<OrderViewModel>(); } } /// <summary> /// Cleans up all the resources. /// </summary> public static void Cleanup() { } } }
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 Supervisoria___tcc { public partial class TelaEscolhas : Form { public TelaEscolhas() { InitializeComponent(); } private void Button3_Click(object sender, EventArgs e) { this.Close(); } private void Botao_Tela_Controle_Click(object sender, EventArgs e) { TelaDeControle tela_Controle = new TelaDeControle(); this.Hide(); tela_Controle.ShowDialog(); this.Close(); } private void Botao_Tela_Autonoma_Click(object sender, EventArgs e) { TelaAutonoma tela_Autonoma = new TelaAutonoma(); this.Hide(); tela_Autonoma.Show(); this.Close(); } private void TelaEscolhas_Load(object sender, EventArgs e) { } } }
using PlatformRacing3.Server.API.Game.Commands; using PlatformRacing3.Server.Game.Client; namespace PlatformRacing3.Server.Game.Commands.Selector; internal interface ICommandTargetSelector { public IEnumerable<ClientSession> FindTargets(ICommandExecutor executor, string parameter); }
using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace MyPage.Migrations { public partial class ListaExerciciosnaAtividade : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Atividades_Exercicios_ExercicioId1", table: "Atividades"); migrationBuilder.DropIndex( name: "IX_Atividades_ExercicioId1", table: "Atividades"); migrationBuilder.DropColumn( name: "ExercicioId", table: "Atividades"); migrationBuilder.DropColumn( name: "ExercicioId1", table: "Atividades"); migrationBuilder.CreateTable( name: "AtividadeExercicio", columns: table => new { ExercicioId = table.Column<long>(nullable: false), AtividadeId = table.Column<long>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AtividadeExercicio", x => new { x.ExercicioId, x.AtividadeId }); table.ForeignKey( name: "FK_AtividadeExercicio_Atividades_AtividadeId", column: x => x.AtividadeId, principalTable: "Atividades", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AtividadeExercicio_Exercicios_ExercicioId", column: x => x.ExercicioId, principalTable: "Exercicios", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_AtividadeExercicio_AtividadeId", table: "AtividadeExercicio", column: "AtividadeId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AtividadeExercicio"); migrationBuilder.AddColumn<int>( name: "ExercicioId", table: "Atividades", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<long>( name: "ExercicioId1", table: "Atividades", nullable: true); migrationBuilder.CreateIndex( name: "IX_Atividades_ExercicioId1", table: "Atividades", column: "ExercicioId1"); migrationBuilder.AddForeignKey( name: "FK_Atividades_Exercicios_ExercicioId1", table: "Atividades", column: "ExercicioId1", principalTable: "Exercicios", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
 namespace MFW.LALLib { public enum DeviceTypeEnum { NULL, AUDIO_INPUT, AUDIO_OUTPUT, VIDEO_INPUT, DEV_MONITOR, APPLICATIONS } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; /// <summary> /// 敵のステータスクラス /// </summary> public class EnemyStatus : MonoBehaviour { [SerializeField, Tooltip("攻撃力")] private int m_attack = 10; //攻撃力 [SerializeField, Tooltip("防御力")] private int m_defence = 5; //防御力 [SerializeField, Tooltip("体力")] private int m_hp = 100; //体力 private int m_maxHp = 0; //体力最大値 [SerializeField, Tooltip("体力ゲージ")] protected Slider m_hpBer; private void Start() { m_maxHp = GetHp(); if (m_hpBer == null) { m_hpBer = this.GetComponentInChildren<Slider>(); } m_hpBer.maxValue = m_maxHp; m_hpBer.value = m_maxHp; } public void SetAttack(int attack) { m_attack = attack; } public void SetDefence(int defence) { m_defence = defence; } public void SetHp(int hp) { m_hp = hp; } /// <summary> /// 攻撃力 /// </summary> /// <returns>現在の攻撃力を返す</returns> public int GetAttack() { return m_attack; } /// <summary> /// 防御力 /// </summary> /// <returns>現在の防御力を返す</returns> public int GetDefence() { return m_defence; } /// <summary> /// 体力 /// </summary> /// <returns>現在の体力を返す</returns> public int GetHp() { return m_hp; } /// <summary> /// 通常攻撃 /// </summary> /// <returns>(Enemy_AT)</returns> public int Attack() { return GetAttack(); } /// <summary> /// 通常で攻撃を受けた /// </summary> /// <param name="damage">相手のステータス</param> public void Damage(int damage) { m_hp = (int)(Mathf.Max(0, m_hp - (damage - GetDefence()))); //StartCoroutine(Blink(0.1f)); } //IEnumerator Blink(float interval) //{ // SpriteRenderer renderer = GetComponent<SpriteRenderer>(); // while (true) // { // renderer.enabled = !renderer.enabled; // yield return new WaitForSeconds(interval); // } //} /// <summary> /// 死亡処理 /// </summary> public void Dead() { m_hp = 0; } /// <summary> /// 関連UI表示 /// </summary> public void StatusUI() { //HPバー m_hpBer.value = GetHp(); } }
 using System; using System.Collections.Generic; using System.Web.Mvc; using HCL.Academy.Model; using HCLAcademy.Controllers; using System.Net.Http; using System.Threading.Tasks; using OfficeOpenXml; using OfficeOpenXml.Style; using System.IO; using System.Configuration; using Microsoft.ApplicationInsights; using System.Diagnostics; namespace HCL.Academy.Web.Controllers { public class ChecklistReportController : BaseController { // GET: ChecklistReport public async Task<ActionResult> Index() { InitializeServiceClient(); UserOnBoarding objUserOnBoarding = new UserOnBoarding(); HttpResponseMessage projectResponse = await client.PostAsJsonAsync("Project/GetAllProjects", req); List<Project> projects = await projectResponse.Content.ReadAsAsync<List<Project>>(); objUserOnBoarding.Projects = projects; HttpResponseMessage geoResponse = await client.PostAsJsonAsync("Geo/GetAllGEOs", req); objUserOnBoarding.GEOs = await geoResponse.Content.ReadAsAsync<List<GEO>>(); HttpResponseMessage roleResponse = await client.PostAsJsonAsync("User/GetAllRoles", req); objUserOnBoarding.Roles = await roleResponse.Content.ReadAsAsync<List<Role>>(); return View(objUserOnBoarding); } // GET: ChecklistReport/Details/5 public ActionResult Details(int id) { return View(); } /// <summary> /// Fetches users of a particular status in a project /// </summary> /// <param name="status"></param> /// <param name="project"></param> /// <returns></returns> [Authorize] [HttpPost] [SessionExpire] public async Task<ActionResult> UserChecklistReport(int project, int roleId, int geoId,string option,string search) { InitializeServiceClient(); OnboardingReportRequest request = new OnboardingReportRequest(); request.ClientInfo = req.ClientInfo; request.IsExcelDownload = false; request.GEOId = geoId; request.RoleId = roleId; request.ProjectId = project; if(option==null) { option = "Name"; } request.option = option; request.search = search; HttpResponseMessage response = await client.PostAsJsonAsync("Onboarding/GetOnBoardingChecklistReport", request); List<UserChecklistReportItem> lstUserChecklist = await response.Content.ReadAsAsync<List<UserChecklistReportItem>>(); return PartialView("UserChecklistReport", lstUserChecklist); } /// <summary> /// /// </summary> /// <param name="project"></param> /// <param name="roleId"></param> /// <param name="geoId"></param> /// <returns></returns> [Authorize] [HttpPost] [SessionExpire] public async Task<ActionResult> LastChecklistReport(int project, int roleId, int geoId,string option,string search) { InitializeServiceClient(); OnboardingReportRequest request = new OnboardingReportRequest(); request.ClientInfo = req.ClientInfo; request.IsExcelDownload = false; request.GEOId = geoId; request.RoleId = roleId; request.ProjectId = project; request.option = option; request.search = search; HttpResponseMessage response = await client.PostAsJsonAsync("Onboarding/GetLastChecklistReport", request); List<UserChecklistReportItem> lstUserChecklist = await response.Content.ReadAsAsync<List<UserChecklistReportItem>>(); return PartialView("LastChecklistReport", lstUserChecklist); } /// <summary> /// Gets the report in Excel format. /// </summary> /// <returns></returns> [Authorize] [SessionExpire] public async Task<FileResult> DownloadChecklistReport(int project, int roleId, int geoId) { ExcelPackage excel = new ExcelPackage(); var workSheet = excel.Workbook.Worksheets.Add("Sheet1"); workSheet.TabColor = System.Drawing.Color.Black; workSheet.DefaultRowHeight = 12; InitializeServiceClient(); OnboardingReportRequest request = new OnboardingReportRequest(); request.ClientInfo = req.ClientInfo; request.IsExcelDownload = false; request.GEOId = geoId; request.RoleId = roleId; request.ProjectId = project; HttpResponseMessage response = await client.PostAsJsonAsync("Onboarding/GetOnBoardingChecklistReport", request); List<UserChecklistReportItem> lstUserChecklist = await response.Content.ReadAsAsync<List<UserChecklistReportItem>>(); if (lstUserChecklist.Count > 0) { workSheet.Row(1).Height = 40; workSheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; workSheet.Row(1).Style.VerticalAlignment = ExcelVerticalAlignment.Top; workSheet.Row(1).Style.Fill.PatternType = ExcelFillStyle.Solid; workSheet.Row(1).Style.Font.Bold = true; workSheet.Row(1).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.SkyBlue); workSheet.Cells[1, 1].Value = "Name"; workSheet.Cells[1, 2].Value = "EmployeeId"; workSheet.Cells[1, 3].Value = "EmailAddress"; workSheet.Cells[1, 4].Value = "CheckListItem"; workSheet.Cells[1, 5].Value = "Completed"; workSheet.Cells[1, 6].Value = "OnboardingDate"; workSheet.Cells[1, 7].Value = "CompletionDate"; workSheet.Column(1).Width = 28; workSheet.Column(2).Width = 28; workSheet.Column(3).Width = 28; workSheet.Column(4).Width = 28; for (int i = 0; i < lstUserChecklist.Count; i++) { workSheet.Cells[i + 2, 1].Value = lstUserChecklist[i].Name; workSheet.Cells[i + 2, 2].Value = lstUserChecklist[i].EmployeeID; workSheet.Cells[i + 2, 3].Value = lstUserChecklist[i].EmailAddress; workSheet.Cells[i + 2, 4].Value = lstUserChecklist[i].CheckListItem; workSheet.Cells[i + 2, 5].Value = lstUserChecklist[i].CheckListStatus; workSheet.Cells[i + 2, 6].Value = lstUserChecklist[i].OnboardingDate; workSheet.Cells[i + 2, 7].Value = lstUserChecklist[i].CompletionDate; } } string clientName = ConfigurationManager.AppSettings["ClientName"].ToString(); string excelName = clientName + "_ChecklistReport_" + DateTime.Now + ".xlsx"; using (var memoryStream = new MemoryStream()) { Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment; filename=" + excelName); excel.SaveAs(memoryStream); memoryStream.WriteTo(Response.OutputStream); Response.Flush(); Response.End(); return File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"); } } /// <summary> /// Gets the report in Excel format. /// </summary> /// <returns></returns> [Authorize] [SessionExpire] public async Task<FileResult> DownloadLastChecklistItemReport(int project, int roleId, int geoId) { ExcelPackage excel = new ExcelPackage(); var workSheet = excel.Workbook.Worksheets.Add("Sheet1"); workSheet.TabColor = System.Drawing.Color.Black; workSheet.DefaultRowHeight = 12; InitializeServiceClient(); OnboardingReportRequest request = new OnboardingReportRequest(); request.ClientInfo = req.ClientInfo; request.IsExcelDownload = false; request.GEOId = geoId; request.RoleId = roleId; request.ProjectId = project; HttpResponseMessage response = await client.PostAsJsonAsync("Onboarding/GetLastChecklistReport", request); List<UserChecklistReportItem> lstUserChecklist = await response.Content.ReadAsAsync<List<UserChecklistReportItem>>(); if (lstUserChecklist.Count > 0) { workSheet.Row(1).Height = 40; workSheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; workSheet.Row(1).Style.VerticalAlignment = ExcelVerticalAlignment.Top; workSheet.Row(1).Style.Fill.PatternType = ExcelFillStyle.Solid; workSheet.Row(1).Style.Font.Bold = true; workSheet.Row(1).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.SkyBlue); workSheet.Cells[1, 1].Value = "Name"; workSheet.Cells[1, 2].Value = "EmployeeId"; workSheet.Cells[1, 3].Value = "EmailAddress"; workSheet.Cells[1, 4].Value = "CheckListItem"; workSheet.Cells[1, 5].Value = "OnboardingDate"; workSheet.Cells[1, 6].Value = "CompletionDate"; workSheet.Column(1).Width = 28; workSheet.Column(2).Width = 28; workSheet.Column(3).Width = 28; workSheet.Column(4).Width = 28; for (int i = 0; i < lstUserChecklist.Count; i++) { workSheet.Cells[i + 2, 1].Value = lstUserChecklist[i].Name; workSheet.Cells[i + 2, 2].Value = lstUserChecklist[i].EmployeeID; workSheet.Cells[i + 2, 3].Value = lstUserChecklist[i].EmailAddress; workSheet.Cells[i + 2, 4].Value = lstUserChecklist[i].CheckListItem; workSheet.Cells[i + 2, 5].Value = lstUserChecklist[i].OnboardingDate; workSheet.Cells[i + 2, 6].Value = lstUserChecklist[i].CompletionDate; } } string clientName = ConfigurationManager.AppSettings["ClientName"].ToString(); string excelName = clientName + "_LastChecklistItemReport_" + DateTime.Now + ".xlsx"; using (var memoryStream = new MemoryStream()) { Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment; filename=" + excelName); excel.SaveAs(memoryStream); memoryStream.WriteTo(Response.OutputStream); Response.Flush(); Response.End(); return File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"); } } } }