text stringlengths 13 6.01M |
|---|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CoursePagerAdapter.cs" company="GSD Logic">
// Copyright © 2018 GSD Logic. All Rights Reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Courses.AndroidBlankApp
{
using Android.Support.V4.App;
using Courses.Library;
public class CoursePagerAdapter : FragmentStatePagerAdapter
{
private readonly CourseManager courseManager;
public CoursePagerAdapter(FragmentManager fm, CourseManager courseManager)
: base(fm)
{
this.courseManager = courseManager;
}
public override int Count => this.courseManager.Count;
public override Fragment GetItem(int position)
{
this.courseManager.MoveTo(position);
return new CourseFragment(this.courseManager.Current);
}
}
} |
using System;
using System.Runtime.Serialization;
namespace ContBancar
{
[Serializable]
internal class InvalidAmmountException : Exception
{
public InvalidAmmountException()
{
}
public InvalidAmmountException(string message) : base(message)
{
}
public InvalidAmmountException(string message, Exception innerException) : base(message, innerException)
{
}
protected InvalidAmmountException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
} |
using System.Threading.Tasks;
using SFA.DAS.CommitmentsV2.Shared.Interfaces;
using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests.DraftApprenticeship;
using SFA.DAS.ProviderCommitments.Web.Models;
namespace SFA.DAS.ProviderCommitments.Web.Mappers
{
public class AddDraftApprenticeshipRequestMapper : IMapper<AddDraftApprenticeshipViewModel, AddDraftApprenticeshipApimRequest>
{
public Task<AddDraftApprenticeshipApimRequest> Map(AddDraftApprenticeshipViewModel source)
{
return Task.FromResult(new AddDraftApprenticeshipApimRequest
{
ProviderId = source.ProviderId,
ReservationId = source.ReservationId,
FirstName = source.FirstName,
LastName = source.LastName,
Email = source.Email,
DateOfBirth = source.DateOfBirth.Date,
Uln = source.Uln,
CourseCode = source.CourseCode,
EmploymentPrice = source.EmploymentPrice,
Cost = source.Cost,
StartDate = source.StartDate.Date,
ActualStartDate = source.ActualStartDate.Date,
EmploymentEndDate = source.EmploymentEndDate.Date,
EndDate = source.EndDate.Date,
OriginatorReference = source.Reference,
DeliveryModel = source.DeliveryModel,
IsOnFlexiPaymentPilot = source.IsOnFlexiPaymentPilot
});
}
}
}
|
using ChainOfResponsibility.Approver;
using System;
namespace ChainOfResponsibility
{
class Program
{
static void Main(string[] args)
{
var director = new Director();
var vicePresident = new VicePresident();
director.SetNext(vicePresident);
director.ProcessRequest(9999);
director.ProcessRequest(10001);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
namespace HighSchool
{
public class ControlPlayer : MonoBehaviour
{
//Outlet
Rigidbody2D _rigidbody2D;
public Transform aimPivot;
public GameObject projectilePrefab;
public Image imageHealthBar;
public static ControlPlayer instance;
public int jumpsLeft;
//configuration
//public float moveSpeed;
//State tracking
public float healthMax = 100f;
public float health = 100f;
public bool isPaused;
/*
void Awake()
{
instance = this;
}
*/
// Start is called before the first frame update
void Start()
{
_rigidbody2D = GetComponent<Rigidbody2D>();
isPaused = false;
}
// Update is called once per frame
void Update()
{
if (isPaused)
{
return;
}
// Show menu
if (Input.GetKey(KeyCode.P))
{
MenuController.instance.Show();
}
if (health > 0)
{
if (Input.GetKey(KeyCode.LeftArrow))
{
//time.deltaTime normalizes for frame rate
//forcemode, apply force immediately
_rigidbody2D.AddForce(Vector2.left * 9f * Time.deltaTime, ForceMode2D.Impulse);
//so that character turns in appropriate direction
// _rigidbody2D.AddForce(Vector2.left * moveSpeed * Time.deltaTime, ForceMode2D.Impulse);
}
//move player right
if (Input.GetKey(KeyCode.RightArrow))
{
//time.deltaTime normalizes for frame rate
//forcemode, apply force immediately
_rigidbody2D.AddForce(Vector2.right * 9f * Time.deltaTime, ForceMode2D.Impulse);
// _rigidbody2D.AddForce(Vector2.right * moveSpeed * Time.deltaTime, ForceMode2D.Impulse);
}
//aim at the mouse--> get mouse coordinates
Vector3 mousePosition = Input.mousePosition;
Vector3 mousePositionInWorld = Camera.main.ScreenToWorldPoint(mousePosition);
//hypotensue of triangle for shooting
Vector3 directionFromPlayerToMouse = mousePositionInWorld - transform.position;
//SHOOT, right click is 0, left is 1
if (Input.GetKeyDown(KeyCode.Space))
{
//creates a game object when mouse is clicked
GameObject newProjectile = Instantiate(projectilePrefab);
//shoot where character is, in same position
newProjectile.transform.position = transform.position;
//position where the aimpivot is
newProjectile.transform.rotation = aimPivot.rotation;
}
//JUMP
//get key happens every frame, getkeydown doesnt(happens once), passage of tiem doesnt matter
//so no need to normalize using deltaTime
if (Input.GetKeyDown(KeyCode.UpArrow))
{
if (jumpsLeft > 0)
{
jumpsLeft--;
_rigidbody2D.AddForce(Vector2.up * 7f, ForceMode2D.Impulse);
}
}
}
}
void TakeDamage(float damageAmount)
{
health -= damageAmount;
if (health <= 0)
{
Die();
//Time.timeScale = 0;
}
imageHealthBar.fillAmount = health / healthMax;
}
void GiveHealth(float healthAmount)
{
health += healthAmount;
/*
if (health <= 0)
{
Die();
}
*/
imageHealthBar.fillAmount = health + healthMax;
}
void Die()
{
//stop timer
StopCoroutine("FiringTimer");
GetComponent<Rigidbody2D>().gravityScale = 0;
//so if we get shoved by an asteroid, ship will float away
GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;
SceneManager.LoadScene("HighSchool");
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.GetComponent<Obstacle>())
{
TakeDamage(10f);
}
if (other.gameObject.GetComponent<ChaserController>())
{
TakeDamage(20f);
}
if (other.gameObject.GetComponent<HealthObject>())
{
GiveHealth(10f);
}
//check that we collided w ground (below our feet)
if (other.gameObject.layer == LayerMask.NameToLayer("Ground"))
{
//check what is directly below character's feet, collection of hits
//raycastall, full colleciton of things below feet, 'rays' should start from our positon
//raycast downward, and dont wat to raycast forever, so limit distance
RaycastHit2D[] hits = Physics2D.RaycastAll(transform.position, -transform.up, 0.85f);
Debug.DrawRay(transform.position, -transform.up * 0.85f);
//may have multiple things below our feet, filter through hits
//want to see if its ground, so loop through it
for (int i = 0; i < hits.Length; i++)
{
RaycastHit2D hit = hits[i];
//check we collided w the ground right below our feet
//check if layer we hit is the gorund
if (hit.collider.gameObject.layer == LayerMask.NameToLayer("Ground"))
{
//reset jump count
jumpsLeft = 2;
}
}
}
}
}
} |
using UnityEngine;
using System.Collections;
using GameFrame;
class TestStateIdDefine
{
public static FSMStateId state1 = new FSMStateId("state1");
public static FSMStateId state2 = new FSMStateId("state2");
public static FSMStateId state3 = new FSMStateId("state3");
}
class State1 : FSMState
{
protected override void Init()
{
m_stateId = TestStateIdDefine.state1;
// m_executeDalegate = State1Execute;
m_stateTime = 3;
m_break = true;
}
protected override void EndOfExecute()
{
Debug.Log("State1 EndOfExecute");
}
void State1Execute()
{
Debug.Log("State1 Execute");
}
}
class State2 : FSMState
{
protected override void Init()
{
m_stateId = TestStateIdDefine.state2;
// m_executeDalegate = State2Execute;
m_stateTime = 3;
m_break = false;
}
protected override void EndOfExecute()
{
Debug.Log("State2 EndOfExecute");
}
void State2Execute()
{
Debug.Log("State2 Execute");
}
}
class State3 : FSMState
{
protected override void Init()
{
m_stateId = TestStateIdDefine.state3;
// m_executeDalegate = State3Execute;
m_stateTime = 3;
m_break = false;
}
protected override void EndOfExecute()
{
Debug.Log("State3 EndOfExecute");
}
void State3Execute()
{
Debug.Log("State3 Execute");
}
}
public class TestFSM : MonoBehaviour {
FSMManager fsmManager = new FSMManager();
// Use this for initialization
void Start () {
fsmManager.AddState(new State1());
fsmManager.AddState(new State2());
fsmManager.AddState(new State3());
}
public void clickState1()
{
fsmManager.ChangeState(TestStateIdDefine.state1);
}
public void clickState2()
{
fsmManager.ChangeState(TestStateIdDefine.state2);
}
public void clickState3()
{
fsmManager.ChangeState(TestStateIdDefine.state3);
}
}
|
using System;
using System.Collections.Generic;
using TomKlonowski.Api.Data.Repository;
using TomKlonowski.Model;
namespace TomKlonowski.DB
{
public class SqlRepository : IBlogRepository, INoteRepository
{
#region Notes
public IEnumerable<Note> GetNotes()
{
throw new NotImplementedException();
}
public Note GetNote(int noteId)
{
return new TomKlonowskiDbContext().Notes.Find(noteId);
}
public Note CreateNote(Note newNote)
{
using (var db = new TomKlonowskiDbContext())
{
db.Notes.Add(newNote);
db.SaveChanges();
return newNote;
}
}
public Note UpdateNote(Note updatedNote)
{
throw new NotImplementedException();
}
public void DelteNote(int noteId)
{
throw new NotImplementedException();
}
#endregion
#region Blogs
public IEnumerable<Blog> GetBlogs()
{
return new TomKlonowskiDbContext().Blogs;
}
public Blog GetBlog(int blogId)
{
return new TomKlonowskiDbContext().Blogs.Find(blogId);
}
public Blog CreateBlog(Blog newBlog)
{
using (var db = new TomKlonowskiDbContext())
{
db.Blogs.Add(newBlog);
db.SaveChanges();
return newBlog;
}
}
public Blog UpdateBlog(Blog updatedBlog)
{
using (var db = new TomKlonowskiDbContext())
{
var blog = db.Blogs.Find(updatedBlog.Id);
blog.Title = updatedBlog.Title;
blog.Body = updatedBlog.Body;
blog.Description = updatedBlog.Description;
blog.Tags = updatedBlog.Tags;
blog.UpdateDate = DateTime.UtcNow;
db.SaveChanges();
return this.GetBlog(blog.Id);
}
}
public void DelteBlog(int blogId)
{
using (var db = new TomKlonowskiDbContext())
{
var blog = db.Blogs.Find(blogId);
db.Blogs.Remove(blog);
db.SaveChanges();
}
}
#endregion
}
}
|
using System;
using AutoMapper;
using XH.Infrastructure.Mapper;
namespace XH.Domain.Services
{
public class AutoMapperConfig : IAutoMapperRegistrar
{
public void Register(IMapperConfigurationExpression cfg)
{
throw new NotImplementedException();
}
}
}
|
using Alabo.App.Share.OpenTasks.Base;
using Alabo.Framework.Core.Enums.Enum;
using System;
namespace Alabo.App.Share.Rewards.ViewModels
{
public class ViewShareModuleList
{
public long Id { get; set; }
public Guid ModuleId { get; set; }
/// <summary>
/// 配置名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 维度名称
/// </summary>
public string ConfigName { get; set; }
public string DistriRatio { get; set; }
public DateTime CreateTime { get; set; }
public DateTime UpdateTime { get; set; }
public bool IsEnable { get; set; }
public TriggerType TriggerType { get; set; }
/// <summary>
/// 商品范围说明
/// </summary>
public string ProductRangIntro { get; set; }
/// <summary>
/// 用户类型说明
/// </summary>
public string ShareUserIntro { get; set; }
/// <summary>
/// 用户类型说明
/// </summary>
public string OrderUserIntro { get; set; }
/// <summary>
/// 资产分配说明
/// </summary>
public string RuleItemsIntro { get; set; }
/// <summary>
/// 最小触发金额
/// </summary>
public decimal MinimumAmount { get; set; }
/// <summary>
/// 短信通知
/// </summary>
public bool SmsNotification { get; set; }
public bool IsLock { get; set; } = false;
}
public class ShareBaseConfigList : ShareBaseConfig
{
}
} |
using NHibernate.Envers.Configuration.Attributes;
using SharpArch.Domain.DomainModel;
namespace Profiling2.Domain.Prf.Persons
{
/// <summary>
/// Person text that is only visible to Profiling Internationals and Profiling Nationals.
/// </summary>
public class PersonRestrictedNote : Entity
{
[Audited]
public virtual Person Person { get; set; }
[Audited]
public virtual string Note { get; set; }
public override string ToString()
{
return this.Note;
}
}
}
|
using fileCrawlerWPF.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace fileCrawlerWPF.Events
{
public class FilterToggledEventArgs
: RoutedEventArgs
{
public FilterContext Context { get; }
public bool IsEnabled { get; }
public FilterToggledEventArgs(FilterContext ctx, bool val)
{
Context = ctx;
IsEnabled = val;
}
}
}
|
using System;
using System.Collections.Generic;
using Musical_WebStore_BlazorApp.Server.Data.Models;
namespace Admin.Models
{
public class Order: Entity
{
public DateTime Date {get;set;}
public int ServiceId {get;set;}
public virtual Service Service {get;set;}
//user that ordered service
public string UserId {get;set;}
public virtual User User {get;set;}
public string Text {get;set;}
public virtual OrderType OrderType {get;set;}
public int OrderTypeId {get;set;}
public int DeviceId {get;set;}
public virtual Device Device {get;set;}
public int OrderStatusId {get;set;}
public virtual OrderStatus OrderStatus {get;set;}
public virtual IEnumerable<OrderWorker> OrderWorkers {get;set;}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CrowdFundingCore.Database
{
public class SD
{
public const string AdminEndUser = "Administrator";
public const string BackerEndUser = "Backer";
public const string ProjectCreatorEndUser = "Project Creator";
}
}
|
using System.Globalization;
using System.Text.RegularExpressions;
namespace EmberMemoryReader.Abstract.Data
{
public static class StringPatternHelper
{
public static byte[] ToBytes(this string s)
{
byte[] buffer = new byte[s.Length];
for (int i = 0; i < s.Length; i++)
{
buffer[i] = (byte)s[i];
}
return buffer;
}
public static double ToComparableVersion(this string stringVersion)
{
if (double.TryParse(Regex.Match(stringVersion, @"\d+(\.\d*)?").Value.ToString(), NumberStyles.Float, CultureInfo.InvariantCulture, out var ver))
{
return ver;
}
return -1;
}
}
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace MVC5HW.Models
{
public class 客戶資料ListVM : BaseListVM
{
public List<客戶資料VM> 客戶資料 { get; set; }
public 客戶資料ListVM()
{
客戶資料 = new List<客戶資料VM>();
}
}
/// <summary>
/// 客戶資料VM類別。
/// </summary>
public class 客戶資料VM
{
public int Id { get; set; }
[Display(Name = "客戶名稱"), Required(ErrorMessage = "{0}欄位必填")]
[StringLength(50, ErrorMessage = "{0}長度不可超過50。")]
public string 客戶名稱 { get; set; }
[Display(Name = "統一編號"), Required(ErrorMessage = "{0}欄位必填")]
[StringLength(8, ErrorMessage = "{0}長度不可超過8。")]
public string 統一編號 { get; set; }
[驗證電話(ErrorMessage = "電話格式錯誤(xxxx-xxxxxx)")]
[Display(Name = "電話"), Required(ErrorMessage = "{0}欄位必填")]
[StringLength(50, ErrorMessage = "{0}長度不可超過50。")]
public string 電話 { get; set; }
[Display(Name = "傳真"), StringLength(50, ErrorMessage = "{0}長度不可超過50。")]
public string 傳真 { get; set; }
[Display(Name = "地址"), StringLength(100, ErrorMessage = "{0}長度不可超過100。")]
public string 地址 { get; set; }
[EmailAddress]
[Display(Name = "Email"), StringLength(250, ErrorMessage = "{0}長度不可超過250。")]
public string Email { get; set; }
}
} |
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Coldairarrow.Entity.Sto_ProManage
{
/// <summary>
/// Pro_MaterialRequisitionItem
/// </summary>
[Table("Pro_MaterialRequisitionItem")]
public class Pro_MaterialRequisitionItem
{
/// <summary>
/// Id
/// </summary>
[Key]
public String Id { get; set; }
/// <summary>
/// ProCode
/// </summary>
public String ProCode { get; set; }
/// <summary>
/// PMR_No
/// </summary>
public String MR_Id { get; set; }
/// <summary>
/// MatNo
/// </summary>
public String MatNo { get; set; }
/// <summary>
/// MatName
/// </summary>
public String MatName { get; set; }
/// <summary>
/// GuiGe
/// </summary>
public String GuiGe { get; set; }
/// <summary>
/// UnitNo
/// </summary>
public String UnitNo { get; set; }
/// <summary>
/// Quantity
/// </summary>
public Decimal Quantity { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.Sconit.Entity.ORD;
namespace com.Sconit.Service
{
public interface IReceiptMgr
{
ReceiptMaster TransferOrder2Receipt(OrderMaster orderMaster);
//ReceiptMaster TransferOrder2Receipt(IList<OrderMaster> orderMasterList);
ReceiptMaster TransferIp2Receipt(IpMaster ipMaster);
ReceiptMaster TransferIpGap2Receipt(IpMaster ipMaster, CodeMaster.IpGapAdjustOption ipGapAdjustOption);
void CreateReceipt(ReceiptMaster receiptMaster);
void CreateReceipt(ReceiptMaster receiptMaster, DateTime effectiveDate);
void CreateReceipt(ReceiptMaster receiptMaster, bool isKit, DateTime effectiveDate);
void CancelReceipt(string receiptNo);
void CancelReceipt(string receiptNo, DateTime effectiveDate);
void CancelReceipt(ReceiptMaster receiptMaster);
void CancelReceipt(ReceiptMaster receiptMaster, DateTime effectiveDate);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KartObjects;
using KartLib;
using KartObjects.Entities;
namespace KartSystem
{
public partial class StoreEditor : XBaseDictionaryEditor
{
public StoreEditor()
{
InitializeComponent();
InitView();
}
public StoreEditor(Store editableStore, bool canChangeParentStore)
{
InitializeComponent();
_editableStore = editableStore;
//storeBindingSource.DataSource = KartDataDictionary.sStores;
goodGroupBindingSource.DataSource = KartLib.KartDataDictionary.sGoodGroups;
supplierBindingSource.DataSource = KartLib.KartDataDictionary.sSuppliers;
if (_editableStore.GeneratePlu)
goodDepartBindingSource.DataSource = _goodsInStore = (Loader.DbLoad<ScaleGoodDepart>("IdStore=" + _editableStore.Id) ?? new List<ScaleGoodDepart>());//.ConvertAll(q => (GoodDepart)q);// KartHelper.GetGoodsInStore(_editableStore.Id, out goodIds);
comboTreeList1.Enabled = canChangeParentStore;
comboTreeList1.DataSource = KartDataDictionary.sStores.Except(new Store[] { editableStore });
if (_editableStore.IdParent.HasValue)
comboTreeList1.SelectedItemId = _editableStore.IdParent;
InitView();
}
public StoreEditor(Store editableStore, List<Good> goods)
{
InitializeComponent();
_editableStore = editableStore;
InitView();
}
List<ScaleGoodDepart> _goodsInStore;
List<CashierByStore> _CashierByStore
{
get
{
return cashierByStoreBindingSource.DataSource as List<CashierByStore>;
}
}
List<GoodDepart> _deletedGoods = new List<GoodDepart>();
Dictionary<Warehouse, bool> _warehouses = new Dictionary<Warehouse, bool>();
Store _editableStore;
public override void InitView()
{
base.InitView();
storeBindingSource.DataSource = KartDataDictionary.sStores;
_warehouses.Clear();
if (!_editableStore.IdParent.HasValue)
{
gcGoodInDepart.Enabled = false;
cbCheckParentStore.Enabled = false;
}
ucSelectedPriceList1.SelectedIdPriceList = _editableStore.IdPriceList;
teName.Text = _editableStore.Name;
teCode.Text = _editableStore.Code;
teInfo.Text = _editableStore.Info;
cheGeneratePLU.Checked = _editableStore.GeneratePlu;
cashierByStoreBindingSource.DataSource = Loader.DbLoad<CashierByStore>("IdStore = " + _editableStore.Id) ?? new List<CashierByStore>();
cashierBindingSource.DataSource = Loader.DbLoad<Cashier>("") ?? new List<Cashier>();
}
protected override bool CheckForValidation()
{
bool result = true;
if (string.IsNullOrWhiteSpace(teName.Text))
{
NotValidDataMessage = "Не задано наименование. ";
return false;
}
return result;
}
protected override void SaveData()
{
_editableStore.Name = teName.Text;
_editableStore.Code = teCode.Text;
_editableStore.Info = teInfo.Text;
_editableStore.GeneratePlu = cheGeneratePLU.Checked;
_editableStore.IdPriceList = ucSelectedPriceList1.SelectedIdPriceList;
Store comboTr = comboTreeList1.SelectedItem as Store;
if (comboTr != null)
_editableStore.IdParent = comboTr.Id;
Saver.SaveToDb<Store>(_editableStore);
if (_goodsInStore != null)
foreach (ScaleGoodDepart newG in _goodsInStore)
Saver.SaveToDb<ScaleGoodDepart>(newG);
if (_CashierByStore != null)
foreach (CashierByStore c in _CashierByStore)
{
if (c.IdCashier != 0)
{
c.IdStore = _editableStore.Id;
Saver.SaveToDb<CashierByStore>(c);
}
}
}
public static List<Good> FindGoods(string goodIds)
{
List<Good> foundGoods = new List<Good>();
using (FindGoodForm form = new FindGoodForm(goodIds))
{
if (form.ShowDialog() == DialogResult.OK)
{
if (form.selectedGood != null && (string.IsNullOrWhiteSpace(goodIds) || !goodIds.Split(',').Contains(form.selectedGood.Id.ToString().Trim())))
foundGoods.Add(form.selectedGood);
if (form.selectedGroup != null)
foundGoods.AddRange(form.selectedGoods);
}
}
return foundGoods;
}
private void gridControl1_EmbeddedNavigator_ButtonClick(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e)
{
if (e.Button.ButtonType == DevExpress.XtraEditors.NavigatorButtonType.Append)
{
List<Good> foundGoods = FindGoods(string.Join(",", _goodsInStore.Select(gd => { return gd.Id.ToString(); }).Distinct()).Trim(','));//goodIds.Trim(','));
foreach (Good cg in foundGoods)
{
//если бы _editableStore.IdParent=null то сам обработчик был бы не доступен! (см InitView)
ScaleGoodDepart parentStoreGd = Loader.DbLoadSingle<ScaleGoodDepart>("Id=" + cg.Id + " and IdStore=" + _editableStore.IdParent);
//берём цену по которой этот товар в родительском отделе (если его там нет то цена =0)
ScaleGoodDepart newGd = new ScaleGoodDepart() { Id = cg.Id, Name = cg.Name, IdStore = _editableStore.Id, Price = parentStoreGd != null ? parentStoreGd.Price : 0 };
if (cbCheckParentStore.Checked)//если стоит галка "Выбирать товар только из главного офиса"
{
if (parentStoreGd != null)
_goodsInStore.Add(newGd);
}
else
{
_goodsInStore.Add(newGd);
}
}
gcGoodInDepart.RefreshDataSource();
e.Handled = true;
}
if (e.Button.ButtonType == DevExpress.XtraEditors.NavigatorButtonType.Remove)
{
GoodDepart deletedGood = goodDepartBindingSource.Current as GoodDepart;
if (deletedGood != null)
{
Saver.DeleteFromDb<GoodDepart>(deletedGood);
// товар из дочерних отделов надо удалять в хранимой процедуре!
}
}
}
private void ucSelectedPriceList1_MouseMove_1(object sender, MouseEventArgs e)
{
_editableStore.Name = teName.Text;
_editableStore.Code = teCode.Text;
_editableStore.Info = teInfo.Text;
_editableStore.GeneratePlu = cheGeneratePLU.Checked;
ucSelectedPriceList1._Store = _editableStore;
}
private void gridControl1_EmbeddedNavigator_ButtonClick_1(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e)
{
if (e.Button.ButtonType == DevExpress.XtraEditors.NavigatorButtonType.Remove)
{
CashierByStore deletedCashierByStore = cashierByStoreBindingSource.Current as CashierByStore;
if (deletedCashierByStore != null)
{
Saver.DeleteFromDb<CashierByStore>(deletedCashierByStore);
}
}
}
private void gvCashierByStore_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
{
List<CashierByStore> CashierByStore = cashierByStoreBindingSource.DataSource as List<CashierByStore>;
if (CashierByStore.Where(q => { return q.IdCashier == (long)e.Value && q.IdStore != 0; }).Count() > 0)
{
e.ErrorText = "Такой кассир уже задан";
e.Valid = false;
}
}
private void repositoryItemLookUpEdit3_EditValueChanged(object sender, EventArgs e)
{
gvCashierByStore.CloseEditor();
gvCashierByStore.UpdateCurrentRow();
}
}
} |
using System;
namespace Common.Entities
{
public interface IAppEntity : ICloneable
{
long Id { get; }
}
}
|
using System;
namespace BlazorShared.Models.Appointment
{
public class CreateAppointmentResponse : BaseResponse
{
public AppointmentDto Appointment { get; set; } = new AppointmentDto();
public CreateAppointmentResponse(Guid correlationId) : base(correlationId)
{
}
public CreateAppointmentResponse()
{
}
}
} |
namespace Sky
{
public static class ScreenParameters
{
public const int screenWidth = 1920;
public const int screenHeight = 1080;
public const double screenWidthInKm = 0.0004;
public const double screenHeightInKm = 0.0003;
public const double kmInPixel = screenWidthInKm / screenWidth;
public const double projectionCoef = 0.001;
public static double PixelsToKm(int pixels)
{
return pixels * kmInPixel;
}
public static int KmToPixels(double km)
{
return (int)(km / kmInPixel);
}
}
}
|
using StarlightRiver.Abilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Terraria;
namespace StarlightRiver.Items.Infusions
{
public class WispHomingItem : InfusionItem
{
public WispHomingItem() : base(3) { }
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Feral Wisp");
Tooltip.SetDefault("Faeflame Infusion\nRelease homing bolts that lower enemie's damage");
}
public override void UpdateEquip(Player player)
{
AbilityHandler mp = player.GetModPlayer<AbilityHandler>();
if (!(mp.wisp is WispHoming) && !(mp.wisp is WispCombo))
{
if (mp.wisp is WispWIP)
{
mp.wisp = new WispCombo(player);
mp.wisp.Locked = false;
}
else
{
mp.wisp = new WispHoming(player);
mp.wisp.Locked = false;
}
}
}
public override bool CanEquipAccessory(Player player, int slot)
{
AbilityHandler mp = player.GetModPlayer<AbilityHandler>();
return !mp.wisp.Locked;
}
public override void Unequip(Player player)
{
player.GetModPlayer<AbilityHandler>().wisp = new Abilities.Wisp(player);
player.GetModPlayer<AbilityHandler>().wisp.Locked = false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace PL.Integritas.CrossCutting.ExtensionMethods
{
public static class StringExtension
{
/// <summary>
/// Removes non numeric characters
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string RemovesNonNumeric(this string text)
{
if (text != null)
{
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"[^0-9]");
string returnValue = reg.Replace(text, string.Empty);
return returnValue;
}
return string.Empty;
}
/// <summary>
/// Returns a byte array from string
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static byte[] GetBytes(this string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
/// <summary>
/// A TryParse from string to int
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static int ParseInt(this string value)
{
int returnValue;
if (string.IsNullOrEmpty(value) || !int.TryParse(value, out returnValue))
{
return 0;
}
return returnValue;
}
public static string Crypt(this string text)
{
return Convert.ToBase64String(ProtectedData.Protect(Encoding.Unicode.GetBytes(text), null, DataProtectionScope.CurrentUser));
}
public static string Derypt(this string text)
{
return Encoding.Unicode.GetString(ProtectedData.Unprotect(Convert.FromBase64String(text), null, DataProtectionScope.CurrentUser));
}
}
}
|
using System;
using System.Collections.Generic;
namespace DAL.Models
{
public partial class Menu
{
public Menu()
{
CategoriesToMenu = new HashSet<CategoriesToMenu>();
}
public int MenuCode { get; set; }
public string MenuName { get; set; }
public string Discription { get; set; }
public int? UserCode { get; set; }
public DateTime? DateCreated { get; set; }
public DateTime? DateUpdated { get; set; }
public string Links { get; set; }
public int? ViewsNumber { get; set; }
public virtual Users User { get; set; }
public virtual ICollection<CategoriesToMenu> CategoriesToMenu { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AttractionComponentAggregator : ComponentAggregator<AttractionComponent>
{
protected void Awake()
{
AggregatorName = "AttractionComponentAggregator";
}
}
|
namespace KRFTemplateApi.App.Injection
{
using KRFCommon.CQRS.Query;
using KRFTemplateApi.App.CQRS.Sample.Query;
using KRFTemplateApi.Domain.CQRS.Sample.Query;
using Microsoft.Extensions.DependencyInjection;
public static class AppQueryInjection
{
public static void InjectAppQueries( this IServiceCollection services )
{
services.AddTransient<IQuery<SampleInput, SampleOutput>, GetSampleData>();
services.AddTransient<IQuery<ListSampleInput, ListSampleOutput>, ListaAllSample>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using ModelLibrary;
namespace HotelRestAPI.DBUtil
{
/// <summary>
/// En klasse der er forbundet til ens database, som man kan udnytte til fx at lave metoder
/// </summary>
public class ManagerGuest
{
/// <summary>
/// Fobindelse til ens lokale side.
/// </summary>
private const string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=HotelDbtest2;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
/// <summary>
/// SQL tekst, der selecter alle gæster
/// </summary>
private const string GET_ALL = "Select * from guest";
/// <summary>
/// SQL tekst der selecter en gæst
/// </summary>
private const string GET_ONE = "Select * from guest Where Guest_No = @Id";
/// <summary>
/// SQL tekst der indsætter en gæst
/// </summary>
private const string INSERT = "Insert into guest values(@Id, @Name, @Address)";
/// <summary>
/// SQL tekst der opdatere en gæsts indformationer
/// </summary>
private const string UPDATE = "Update guest set Guest_No = @Guestid, Name = @Name, Address = @Address where Guest_No = @Id";
/// <summary>
/// SQL tekst der sletter en gæst
/// </summary>
private const string DELETE = "Delete from guest where Guest_No =@Id";
/// <summary>
/// Metode der retunere listen alle gæster
/// </summary>
/// <returns>alle gæster</returns>
public IEnumerable<Guest> Get()
{
List<Guest> liste = new List<Guest>();
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand(GET_ALL, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Guest guest = readGuest(reader);
liste.Add(guest);
}
conn.Close();
return liste;
}
/// <summary>
/// Metode der læser en gæsts indformationer
/// </summary>
/// <param name="reader"></param>
/// <returns>gæsts information</returns>
private Guest readGuest(SqlDataReader reader)
{
Guest guest = new Guest();
guest.Id = reader.GetInt32(0);
guest.Name = reader.GetString(1);
guest.Address = reader.GetString(2);
return guest;
}
/// <summary>
/// Metode der retunere en enkel gæst
/// </summary>
/// <param name="id"></param>
/// <returns>en gæst</returns>
public Guest Get(int id)
{
Guest guest = null;
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand(GET_ONE, conn);
cmd.Parameters.AddWithValue("@Id", id);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
guest = readGuest(reader);
}
conn.Close();
return guest;
}
/// <summary>
/// Metode der skaber en ny gæst
/// </summary>
/// <param name="guest"></param>
/// <returns>ny gæst</returns>
public bool Post(Guest guest)
{
bool ok = false;
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand(INSERT, conn);
cmd.Parameters.AddWithValue("@Id", guest.Id);
cmd.Parameters.AddWithValue("@Name", guest.Name);
cmd.Parameters.AddWithValue("@Address", guest.Address);
try
{
int noOfRowsAffected = cmd.ExecuteNonQuery();
ok = noOfRowsAffected == 1 ? true : false;
}
catch (SqlException sqlException)
{
ok = false;
}
finally
{
conn.Close();
}
return ok;
}
/// <summary>
/// Metode der redigerer en gæsts information
/// </summary>
/// <param name="id">gæsts Nr</param>
/// <param name="guest">gæsts navn</param>
/// <returns>ny information</returns>
public bool Put(int id, Guest guest)
{
bool ok = false;
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand(UPDATE, conn);
cmd.Parameters.AddWithValue("@GuestId", guest.Id);
cmd.Parameters.AddWithValue("@Name", guest.Name);
cmd.Parameters.AddWithValue("@Address", guest.Address);
cmd.Parameters.AddWithValue("@Id", id);
int noOfRowsAffected = cmd.ExecuteNonQuery();
ok = noOfRowsAffected == 1 ? true : false;
conn.Close();
return ok;
}
/// <summary>
/// Metode der sletter en gæsts
/// </summary>
/// <param name="id">gæst nr</param>
/// <returns>gæst slettet</returns>
public bool Delete(int id)
{
bool ok = false;
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand(DELETE, conn);
cmd.Parameters.AddWithValue("@Id", id);
int noOfRowsAffected = cmd.ExecuteNonQuery();
ok = noOfRowsAffected == 1 ? true : false;
conn.Close();
return ok;
}
}
} |
using ArquiteturaLimpaMVC.Aplicacao.Produtos.Queries;
using ArquiteturaLimpaMVC.Dominio.Entidades;
using ArquiteturaLimpaMVC.Dominio.Interfaces;
using MediatR;
using System.Threading;
using System.Threading.Tasks;
namespace ArquiteturaLimpaMVC.Aplicacao.Produtos.Handlers
{
public class ProdutoPorIdQueryHandler : IRequestHandler<ProdutoPorIdQuery, Produto>
{
private readonly IProdutoRepository _produtoRepository;
public ProdutoPorIdQueryHandler(IProdutoRepository produtoRepository)
{
_produtoRepository = produtoRepository;
}
public async Task<Produto> Handle(ProdutoPorIdQuery request, CancellationToken cancellationToken)
{
return await _produtoRepository.ProdutoPorIdAsync(request.Id);
}
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuanLyNhaHang.Helper
{
public class MenuDAO
{
private static MenuDAO instance;
public static MenuDAO Instance
{
get { if (instance == null) instance = new MenuDAO(); return MenuDAO.instance; }
private set { MenuDAO.instance = value; }
}
private MenuDAO() { }
public List<Menu> GetListMenu(string id)
{
List<Menu> listMenu = new List<Menu>();
string query = "SELECT bi.MaPYC, f.TenMA, bi.SoLuongMA, f.GiaBan, f.GiaBan*bi.SoLuongMA AS totalPrice FROM dbo.ChiTietYeuCau AS bi, dbo.PhieuYeuCau AS b, dbo.MonAn AS f WHERE bi.MaPYC = b.MaPYC AND bi.MaMA = f.MaMA AND b.TrangThai=0 AND b.MaBan = '" + id + "'";
DataTable data = Define.Instance.ExecuteQuery(query);
foreach (DataRow item in data.Rows)
{
Menu menu = new Menu(item);
listMenu.Add(menu);
}
return listMenu;
}
}
}
|
using System;
namespace ServiceQuotes.Domain.Entities
{
public class EmployeeSpecialization
{
public Guid EmployeeId { get; set; }
public virtual Employee Employee { get; set; }
public Guid SpecializationId { get; set; }
public virtual Specialization Specialization { get; set; }
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using CyberSoldierServer.Data;
using CyberSoldierServer.Dtos.EjectDtos;
using CyberSoldierServer.Dtos.InsertDtos;
using CyberSoldierServer.Models.BaseModels;
using CyberSoldierServer.Models.PlayerModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace CyberSoldierServer.Controllers {
[Route("api/[controller]")]
public class AttackItemController : AuthApiController {
private readonly IMapper _mapper;
private readonly CyberSoldierContext _db;
public AttackItemController(IMapper mapper, CyberSoldierContext db) {
_mapper = mapper;
_db = db;
}
[HttpPost("SetWeapon")]
public async Task<IActionResult> SetWeapon([FromBody] WeaponInsertDto weaponDto) {
var player = await _db.Players.FirstOrDefaultAsync(p=>p.UserId==UserId);
var weapon = _mapper.Map<PlayerWeapon>(weaponDto);
if (await _db.PlayerWeapons.Where(w => w.PlayerId == player.Id).AnyAsync(w => w.WeaponId == weapon.Id)) {
return BadRequest("You already have this weapon!");
}
weapon.PlayerId = player.Id;
await _db.PlayerWeapons.AddAsync(weapon);
await _db.SaveChangesAsync();
return Ok();
}
[HttpGet("GetWeapons")]
public async Task<ActionResult<ICollection<PlayerWeaponDto>>> GetWeapons() {
var player = await _db.Players.Where(p => p.UserId == UserId).Include(p => p.Weapons).FirstOrDefaultAsync();
if (player.Weapons.Count==0) {
return NotFound("This player has no weapon");
}
var weapons = _mapper.Map<ICollection<PlayerWeaponDto>>(player.Weapons);
return Ok(weapons);
}
[HttpPost("SetShield")]
public async Task<IActionResult> SetShield([FromBody] ShieldInsertDto shieldDto) {
var player = await _db.Players.FirstOrDefaultAsync(p=>p.UserId==UserId);
var shield = _mapper.Map<PlayerShield>(shieldDto);
if (await _db.PlayerShields.Where(s => s.PlayerId == player.Id).AnyAsync(s => s.ShieldId == shield.Id)) {
return BadRequest("You already have this Shield!");
}
shield.PlayerId = player.Id;
await _db.PlayerShields.AddAsync(shield);
await _db.SaveChangesAsync();
return Ok();
}
[HttpGet("GetShields")]
public async Task<ActionResult<ICollection<PlayerShieldDto>>> GetShields() {
var player = await _db.Players.Where(p => p.UserId == UserId).Include(p => p.Shields).FirstOrDefaultAsync();
if (player.Shields.Count==0) {
return NotFound("This player has no Shield");
}
var shields = _mapper.Map<ICollection<PlayerShieldDto>>(player.Shields);
return Ok(shields);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Epam.Shops.Entities.Enums
{
public enum Gender
{
NotSpecified,
Male,
Female
}
public static class GenderExtension
{
public static string ToStringRus(this Gender gender)
{
switch (gender)
{
case Gender.NotSpecified:
return "Не указан";
case Gender.Male:
return "Мужской";
case Gender.Female:
return "Женский";
default:
return "))00)))";
}
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Waterskibaan;
using System;
namespace Tests
{
[TestClass]
public class KabelTests
{
[TestMethod]
public void TestIsStartPositieLeeg()
{
Kabel kabel = new Kabel();
Assert.AreEqual(kabel.IsStartPositieLeeg(), true);
kabel.NeemLijnInGebruik(new Lijn());
Assert.AreEqual(kabel.IsStartPositieLeeg(), false);
}
[TestMethod]
public void TestVerschuifLijnen()
{
Kabel kabel = new Kabel();
Lijn lijn = new Lijn();
Sporter sporter = new Sporter(MoveCollection.GetWillekeurigeMoves());
sporter.AantalRondenNogTeGaan = new Random().Next(1, 3);
lijn.Sporter = sporter;
kabel.NeemLijnInGebruik(lijn);
kabel.VerschuifLijnen();
Assert.AreEqual(kabel.IsStartPositieLeeg(), true);
}
[TestMethod]
public void TestVerwijderLijnVanKabel()
{
Kabel kabel = new Kabel();
Lijn lijn = new Lijn();
Sporter sporter = new Sporter(MoveCollection.GetWillekeurigeMoves())
{
Skies = new Skies(),
Zwemvest = new Zwemvest()
};
lijn.Sporter = sporter;
lijn.Sporter.AantalRondenNogTeGaan = 1;
kabel.NeemLijnInGebruik(lijn);
kabel.VerschuifLijnen();
kabel.VerschuifLijnen();
kabel.VerschuifLijnen();
kabel.VerschuifLijnen();
kabel.VerschuifLijnen();
kabel.VerschuifLijnen();
kabel.VerschuifLijnen();
kabel.VerschuifLijnen();
kabel.VerschuifLijnen();
Lijn testLine = kabel.VerwijderLijnVanKabel();
Assert.AreEqual(lijn, testLine);
}
}
}
|
using RestaurantAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace RestaurantAPI.Services.Contracts
{
public interface IDishCollection
{
public string InsertDish(Dish dish);
public string UpdateDish(Dish dish);
public string DeleteDish(string id);
public JsonResult GetAllDishes();
public JsonResult GetDishById(string id);
}
}
|
using System.Collections.Generic;
namespace Visitor
{
public class UserProfile
{
private List<INotification> notifications = new List<INotification>();
public void AddNotificationPreference(INotification notification)
{
notifications.Add(notification);
}
public void NotifyCommand(IOperation operation)
{
foreach (var notification in notifications)
{
notification.Execute(operation);
}
}
}
} |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using LoneWolf.Migration.Common;
namespace LoneWolf.Migration.Files
{
public class ImageMigration : IMigration
{
protected string input;
protected string output;
public ImageMigration(string input, string output)
{
this.input = input;
this.output = output;
}
public virtual void Execute()
{
var files = GetFiles();
foreach (var path in files)
{
var file = new FileInfo(path);
Write(file);
}
}
protected virtual IEnumerable<string> GetFiles()
{
var files = Directory.GetFiles(input, "ill*.png").AsEnumerable();
files = files.Union(Directory.GetFiles(input, "small*.png").AsEnumerable());
files = files.Union(Directory.GetFiles(input, "*.png").Where(s => Include(s)));
return files;
}
protected virtual void Write(FileInfo file)
{
file.CopyTo(output + file.Name);
}
private static bool Include(string file)
{
var inclusion = new List<string>()
{
"axe.png",
"bsword.png",
"dagger.png",
"food.png",
"helmet.png",
"mace.png",
"mail.png",
"map.png",
"potion.png",
"pouch.png",
"qstaff.png",
"spear.png",
"ssword.png",
"sword.png",
"warhammr.png",
"weapons.png"
};
return inclusion.Any(f => file.EndsWith(f));
}
}
}
|
using FluentNHibernate.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Common.Models.Mapping
{
public class KurskategorieMap : ClassMap<Kurskategorie>
{
public KurskategorieMap()
{
Id(x => x.KurskategorieID).GeneratedBy.HiLo("10");
Map(x => x.Bezeichnung).Not.Nullable();
}
}
}
|
namespace DelftTools.Units
{
/// <summary>
/// Transformed unit constructed using base unit with the next formula:
///
/// TransformedUnit = Multiplier . BaseUnit ^ Power + Offset
///
/// u1 - "m"
/// tu1 - "km"
///
/// tu1.BaseUnit.Symbol = "m"
/// tu1.Symbol = "km"
///
/// </summary>
public interface ITransformedUnit : IUnit
{
IUnit BaseUnit { get; }
double Power { get; }
double Multiplier { get; }
double Offset { get;}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Tools
{
public class LongInteger : IComparable<LongInteger>
{
public static readonly LongInteger Zero = new LongInteger(0);
public static readonly LongInteger One = new LongInteger(1);
private const int Positive = 1;
private const int Negative = -1;
private const int BASE = 10000;
private const int DIGITS_IN_PART = 4;
private List<int> _parts;
private int _sign;
private int _maxRadix;
public int LastDigit
{
get
{
return _parts[0] % 10;
}
}
public LongInteger(int num, int capacity = 3)
{
_sign = num < 0 ? Negative : Positive;
num *= _sign;
_parts = new List<int>(new int[capacity + 3]);
int i = 0;
while (num > 0)
{
_parts[i++] = num % BASE;
num /= BASE;
}
TrailZeroes();
}
public LongInteger(LongInteger longInteger)
{
_sign = longInteger._sign;
_parts = new List<int>();
_parts.AddRange(longInteger._parts);
_maxRadix = longInteger._maxRadix;
}
public static LongInteger Pow(LongInteger n, int exp)
{
LongInteger res = 1;
while (exp > 0)
{
if ((exp & 1) == 1)
{
exp--;
res *= n;
}
n *= n;
exp >>= 1;
}
return res;
}
public static LongInteger operator -(LongInteger a)
{
var res = new LongInteger(a) {_sign = Negative * a._sign};
return res;
}
public static LongInteger operator +(LongInteger a, LongInteger b)
{
if (a._sign == b._sign)
{
var res = Add(a, b);
res._sign = a._sign;
return res;
}
else if (a._sign == Negative)
{
return b - (-a);
}
else
{
return a - (-b);
}
}
public static LongInteger operator -(LongInteger a, LongInteger b)
{
if (a._sign != b._sign)
{
var res = Add(a, b);
res._sign = a._sign;
return res;
}
else if (a._sign == Negative)
{
return (-b) - (-a);
}
else if (CompareParts(a, b) >= 0)
{
return Subtract(a, b);
}
else
{
var res = Subtract(b, a);
res._sign = Negative;
return res;
}
}
private static int CompareParts(LongInteger a, LongInteger b)
{
if (a._parts.Count.CompareTo(b._parts.Count) != 0)
{
return a._parts.Count.CompareTo(b._parts.Count);
}
for (int i = a._parts.Count - 1; i >= 0; i--)
{
if (a._parts[i].CompareTo(b._parts[i]) != 0)
{
return a._parts[i].CompareTo(b._parts[i]);
}
}
return 0;
}
public static LongInteger operator /(LongInteger a, LongInteger b)
{
throw new NotImplementedException();
}
public static LongInteger operator *(LongInteger a, LongInteger b)
{
if (a._sign == b._sign)
{
return Multiply(a, b);
}
var res = Multiply(a, b);
res._sign = -1;
return res;
}
public static LongInteger operator *(LongInteger a, int b)
{
if (b >= BASE)
{
return a * new LongInteger(b);
}
var res = MultiplySmall(a, b);
if (b < 0)
{
res._sign = -1;
}
if (res._sign == a._sign)
{
res._sign = 1;
}
return res;
}
private static LongInteger Add(LongInteger a, LongInteger b)
{
int radix = Math.Max(a._maxRadix, b._maxRadix);
var res = new LongInteger(0) { _parts = new List<int>() };
int i, carry = 0;
for (i = 0; i <= radix || carry > 0; i++)
{
int current = carry +
(i < a._parts.Count ? a._parts[i] : 0) +
(i < b._parts.Count ? b._parts[i] : 0);
carry = current / BASE;
res._parts.Add(current - carry * BASE);
}
res.TrailZeroes();
return res;
}
private static LongInteger Subtract(LongInteger a, LongInteger b)
{
int radix = Math.Max(a._maxRadix, b._maxRadix);
var res = new LongInteger(0, 1);
int i, carry = 0;
for (i = 0; i <= radix || carry != 0; i++)
{
int current = - carry +
(i < a._parts.Count ? a._parts[i] : 0) -
(i < b._parts.Count ? b._parts[i] : 0);
carry = current < 0 ? 1 : 0;
res._parts.Add(current + carry * BASE);
}
res.TrailZeroes();
return res;
}
private static LongInteger Multiply(LongInteger a, LongInteger b)
{
var res = new LongInteger(0);
res._parts = new List<int>(new int[a._maxRadix + b._maxRadix + 2]);
for (int i = 0; i <= a._maxRadix; i++)
{
for (int j = 0, carry = 0; j <= b._maxRadix || carry > 0; j++)
{
int current = res._parts[i + j] +
a._parts[i] * (j < b._parts.Count ? b._parts[j] : 0) + carry;
carry = current / BASE;
res._parts[i + j] = current - carry * BASE;
}
}
res.TrailZeroes();
return res;
}
private static LongInteger MultiplySmall(LongInteger a, int b)
{
var res = new LongInteger(0) { _parts = new List<int>(new int[a._maxRadix + 2]) };
int i, carry = 0;
for (i = 0; i <= a._maxRadix || carry > 0; i++)
{
int current = carry + (i < a._parts.Count ? a._parts[i] * b : 0);
carry = current / BASE;
res._parts[i] = current - carry * BASE;
}
res.TrailZeroes();
return res;
}
public static implicit operator LongInteger(int i)
{
return new LongInteger(i);
}
private static int CompareTo(LongInteger a, LongInteger b)
{
if (a._sign == Negative && b._sign == Positive)
return -1;
else if (a._sign == Positive && b._sign == Negative)
return 1;
else if (a._sign == Positive)
return CompareParts(a, b);
else
return Invert(CompareParts(a, b));
}
private static int Invert(int x)
{
if (x == 0)
return 0;
else if (x < 0)
return 1;
else
return -1;
}
public int CompareTo(LongInteger other)
{
return CompareTo(this, other);
}
public bool Equals(LongInteger x) { return CompareTo(this, x) == 0; }
public static bool operator <(LongInteger x, LongInteger y) { return CompareTo(x, y) < 0; }
public static bool operator >(LongInteger x, LongInteger y) { return CompareTo(x, y) > 0; }
public static bool operator <=(LongInteger x, LongInteger y) { return CompareTo(x, y) <= 0; }
public static bool operator >=(LongInteger x, LongInteger y) { return CompareTo(x, y) >= 0; }
public static bool operator ==(LongInteger x, LongInteger y) { return CompareTo(x, y) == 0; }
public static bool operator !=(LongInteger x, LongInteger y) { return CompareTo(x, y) != 0; }
public override bool Equals(object obj)
{
return (obj is LongInteger) && (CompareTo(this, (LongInteger)obj) == 0);
}
public override string ToString()
{
string s = (_sign < 0 ? "-" : "") + _parts[_maxRadix];
for (int i = 1; i <= _maxRadix; i++)
{
s += _parts[_maxRadix - i].ToString().PadLeft(DIGITS_IN_PART, '0');
}
return s;
}
private void TrailZeroes()
{
for (int i = _parts.Count - 1; i >= 0; i--)
{
if (_parts[i] == 0 && i != 0)
{
_parts.RemoveAt(i);
}
else
{
_maxRadix = i;
return;
}
}
}
public override int GetHashCode()
{
return _parts.Aggregate(0, (current, part) => current ^ (part.GetHashCode() ^ 0xBADF00D));
}
}
}
|
using System.Collections;
using UnityEngine;
public enum PlayerListEventType {
PlayerJoined, //A player registered and joined the lobby
PlayerLeft, //A registered player left the Lobby
PlayerUpdatedPlayerList, //The playerList on a specific player is now up-to-date and synchronised
PlayerChangedCharacter //A player changed its character
};
public interface I_PlayerListObserver {
void OnPlayerListChanged(PlayerListEventType eventType, Player player);
}
|
using DrivingSchool_Api;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Repository.Interfaces
{
public interface IBookingTypeRepository
{
void Add(BookingType bookingType);
void Delete(int? bookingTypeId);
void Update(BookingType bookingType);
IQueryable<BookingType> GetAll();
BookingType GetSingleRecord(int? bookingTypeId);
BookingType Find(int? bookingTypeId);
}
}
|
namespace DFC.ServiceTaxonomy.GraphSync.Enums
{
public enum EnabledStatus
{
Enabled,
AlreadyEnabled
}
}
|
using AutoTests.Framework.Web.Attributes;
namespace AutoTests.Framework.Tests.Web.Elements
{
public class MultipleLocatorElement : DemoElement
{
[FromLocator]
public string Name { get; set; }
public string Value { get; set; }
public MultipleLocatorElement(Application application) : base(application)
{
}
}
} |
namespace SAAS.FrameWork.Mq.Mng
{
public interface IClientMqBuilder
{
IClientMq BuildMq();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IRAPShared
{
public class KeyValueEntity
{
public string Key { get; set; }
public object Value { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace ASPNETCOREJSON.Models
{
public class Mercury
{
[Key]
public int Mercury_Id { get; set; }
public DateTime DateTimeStart { get; set; }
public double? Hg { get; set; }
public string Unit { get; set; }
}
}
|
using System;
using System.Threading;
namespace Conversor_de_minutos
{
class Program
{
static void Main(string[] args)
{
int ciclos=1, total, min=0, seg=0;
Console.Write("Escolha o tempo em minutos: ");
total = Convert.ToInt32(Console.ReadLine());
min = total;
string fmt = "00"; //to string servido pra dar o alinhamento usando 2 caracteres "00"
total = total * 60;
Console.Clear();
while (ciclos <= total)
{
Console.WriteLine("{0}:{1}\n", min.ToString(fmt), seg.ToString(fmt));
seg--;
if(seg <= 0)
{
seg = 60;
min--;
}
Thread.Sleep(1000); //da o delay a cada mensagem (esta em milisegundos)
Console.Clear(); //limpa
}
}
}
}
|
namespace MySurveys.Models
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Data.Common;
public class Question : DeletableEntity
{
private ICollection<PossibleAnswer> possibleAnswers;
private ICollection<Answer> answers;
public Question()
{
this.possibleAnswers = new HashSet<PossibleAnswer>();
this.answers = new HashSet<Answer>();
}
[Key]
[Index]
public int Id { get; set; }
[Required]
[StringLength(200), MinLength(2)]
public string Content { get; set; }
public int SurveyId { get; set; }
public virtual Survey Survey { get; set; }
public string ParentContent { get; set; }
public bool IsDependsOn { get; set; }
public virtual ICollection<PossibleAnswer> PossibleAnswers
{
get { return this.possibleAnswers; }
set { this.possibleAnswers = value; }
}
public virtual ICollection<Answer> Answers
{
get { return this.answers; }
set { this.answers = value; }
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(BoundingBox)), CanEditMultipleObjects]
public class BoundingBoxEditor : Editor
{
BoundingBox BoundingBox;
void OnSceneGUI()
{
BoundingBox = (BoundingBox)target;
Vector3 bottomLeft = BoundingBox.transform.position + new Vector3(BoundingBox.X, BoundingBox.Y);
Vector3 bottomRight = BoundingBox.transform.position + new Vector3(BoundingBox.X + BoundingBox.Width, BoundingBox.Y);
Vector3 topRight = BoundingBox.transform.position + new Vector3(BoundingBox.X + BoundingBox.Width, BoundingBox.Y + BoundingBox.Height);
Vector3 topleft = BoundingBox.transform.position + new Vector3(BoundingBox.X, BoundingBox.Y + BoundingBox.Height);
Vector3[] verts = {
bottomLeft,
topleft,
topRight,
bottomRight,
};
Handles.DrawSolidRectangleWithOutline(verts, new Color(0.5f, 0.5f, 0.5f, 0.1f), new Color(0.7f, 0.1f, 0.1f, 1));
EditorGUI.BeginChangeCheck();
Handles.color = Handles.xAxisColor;
Vector3 newBottomLeft = Handles.Slider2D(bottomLeft, Vector3.forward, Vector3.up, Vector3.right, HandleUtility.GetHandleSize(bottomLeft) / 10, Handles.DotHandleCap, new Vector2(1, 1)) - BoundingBox.transform.position;
Handles.color = Handles.zAxisColor;
Vector3 newTopRight = Handles.Slider2D(topRight, Vector3.forward, Vector3.up, Vector3.right, HandleUtility.GetHandleSize(topRight) / 10, Handles.DotHandleCap, new Vector2(1, 1)) - BoundingBox.transform.position;
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed Bounding Box");
BoundingBox.X = Mathf.RoundToInt(newBottomLeft.x);
BoundingBox.Y = Mathf.RoundToInt(newBottomLeft.y);
Vector3 sizeDelta = newTopRight - newBottomLeft;
BoundingBox.Width = Mathf.Max(Mathf.RoundToInt(sizeDelta.x), 0);
BoundingBox.Height = Mathf.Max(Mathf.RoundToInt(sizeDelta.y), 0);
}
if (BoundingBox.transform.hasChanged)
{
BoundingBox.transform.position = new Vector3((int)BoundingBox.transform.position.x, (int)BoundingBox.transform.position.y, BoundingBox.transform.position.z);
BoundingBox.transform.hasChanged = false;
}
}
public override void OnInspectorGUI()
{
DrawDefaultInspector();
if (GUILayout.Button("Normalize"))
{
BoundingBox boundingBox = (BoundingBox)target;
boundingBox.transform.position = new Vector3((int)(boundingBox.transform.position.x + boundingBox.X), (int)(boundingBox.transform.position.y + boundingBox.Y), boundingBox.transform.position.z);
boundingBox.X = 0;
boundingBox.Y = 0;
Debug.Log("Normalize");
}
}
}
|
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ACT.DFAssist
{
public partial class OverlayForm : Form
{
private static class NativeMethods
{
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
}
private const int WS_EX_LAYERED = 0x80000;
private const int WS_EX_TOOLWINDOW = 0x80;
private const int WM_NCLBUTTONDOWN = 0xA1;
private const int HT_CAPTION = 0x2;
//
private const int BlinkTime = 300;
private const int BlinkCount = 20;
private static readonly Color ColorFate = Color.DarkOrange;
private static readonly Color ColorMatch = Color.Red;
//
private readonly Timer _timer;
private int _blink;
private Color _accent_color;
//
public OverlayForm()
{
InitializeComponent();
Location = Settings.OverlayLocation;
_timer = new Timer
{
Interval = BlinkTime
};
_timer.Tick += Timer_Tick;
}
private void Timer_Tick(object sender, EventArgs e)
{
if (++_blink > BlinkCount)
StopBlink();
else
{
if (BackColor == Color.Black)
BackColor = _accent_color;
else
BackColor = Color.Black;
}
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= WS_EX_LAYERED | WS_EX_TOOLWINDOW;
return cp;
}
}
private void OverlayForm_Load(object sender, EventArgs e)
{
}
private void DoMoveDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
NativeMethods.ReleaseCapture();
NativeMethods.SendMessage(Handle, WM_NCLBUTTONDOWN, new IntPtr(HT_CAPTION), IntPtr.Zero);
}
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
DoMoveDown(e);
}
protected override void OnLocationChanged(EventArgs e)
{
base.OnLocationChanged(e);
Settings.OverlayLocation = Location;
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
}
private void LblInfo_MouseDown(object sender, MouseEventArgs e)
{
DoMoveDown(e);
}
public void SetInfoText(string localtext)
{
lblInfo.Text = Mesg.GetText(localtext);
}
internal void StartBlink()
{
_blink = 0;
_timer.Start();
}
internal void StopBlink()
{
_timer.Stop();
BackColor = Color.Black;
if (_accent_color == ColorFate) // FATE였다면
{
_accent_color = Color.Black;
lblInfo.Text = string.Empty;
}
}
// 모든 이벤트 없앰
internal void EventNone()
{
this.Invoke((MethodInvoker)(() =>
{
_accent_color = Color.Black;
lblInfo.Text = string.Empty;
StopBlink();
}));
}
// 페이트 알림
internal void EventFate(GameData.Fate fate)
{
this.Invoke((MethodInvoker)(() =>
{
lblInfo.Text = fate.Name;
_accent_color = ColorFate;
StartBlink();
}));
}
// 듀티 큐 상태
internal void EventStatus(int queue)
{
string msg = queue < 0 ? string.Empty : $"#{queue}";
this.Invoke((MethodInvoker)(() =>
{
lblInfo.Text = Mesg.GetText("ov-duties-wait", msg); ;
}));
}
// 듀티 큐(루렛)
internal void EventQueue(string name)
{
this.Invoke((MethodInvoker)(() =>
{
_accent_color = Color.Black;
lblInfo.Text = name;
}));
}
// 매치 이름(인스턴스/루렛) 표시
internal void EventMatch(string name, bool blink = true)
{
this.Invoke((MethodInvoker)(() =>
{
lblInfo.Text = name;
_accent_color = ColorMatch;
if (blink)
StartBlink();
}));
}
}
}
|
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SocialWorkout.Models
{
public class DBcontext
{
//For Best practice, Please put this in the web.config. This is only for demo purpose.
//====================================================
public String connectionString = "mongodb://ProjectSport:Ss123123@ds036617.mlab.com:36617/socialworkout";
public String DataBaseName = "socialworkout";
//====================================================
public MongoDatabase Database;
public DBcontext()
{
var client = new MongoClient(connectionString);
var server = client.GetServer();
Database = server.GetDatabase(DataBaseName);
}
public MongoCollection<Country> Countries
{
get
{
var Countries = Database.GetCollection<Country>("Countries");
return Countries;
}
}
public MongoCollection<User> Users
{
get
{
var Users = Database.GetCollection<User>("Users");
return Users;
}
}
public MongoCollection<Data> Data
{
get
{
var DATA = Database.GetCollection<Data>("Data");
return DATA;
}
}
public MongoCollection<Trainer> Trainers
{
get
{
var Trainers = Database.GetCollection<Trainer>("Trainer");
return Trainers;
}
}
public MongoCollection<EventLine> Events
{
get
{
var events = Database.GetCollection<EventLine>("EventLine");
return events;
}
}
public MongoCollection<ContactUs> ContactUs
{
get
{
var ContactUs = Database.GetCollection<ContactUs>("ContactUs");
return ContactUs;
}
}
public MongoCollection<Survey> Survey
{
get
{
var Survey = Database.GetCollection<Survey>("Survey");
return Survey;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Choice.Cenium.HotelImportJob
{
public class ReadFile<T> where T : new()
{
public delegate void GetLine(string[] a, T newPos);
protected static List<T> ReadStream(Stream stream, GetLine getLine)
{
{
var retList = new List<T>();
TextReader tr = new StreamReader(stream, new UTF8Encoding(true), true);
// Leave the first line
tr.ReadLine();
string readLine;
while ((readLine = tr.ReadLine()) != null)
{
var a = readLine.Split(new[] { ';' });
// Find
var line = new T();
try
{
getLine(a, line);
retList.Add(line);
}
catch (Exception)
{
Console.WriteLine("Unreadable line:" + readLine);
}
}
tr.Close();
return retList;
}
}
}
}
|
using Newtonsoft.Json;
namespace BlazorFullCalendar.Data
{
public class CalendarHeader : JsonSerializable
{
[JsonProperty("left")]
public string Left { get; set; } = "title";
[JsonProperty("center")]
public string Center { get; set; } = "";
[JsonProperty("right")]
public string Right { get; set; } = "today prev,next";
}
}
|
using System;
namespace Class
{
class Rectangle
{
public double width;
public double height;
public Rectangle(double width, double height)
{
this.width = width;
this.height = height;
}
public double Area()
{
return width * height;
}
public void Print()
{
Console.WriteLine($"Width: {width} Height: {height} Area: {Area()}");
}
}
class Program
{
static void Main(string[] args)
{
Rectangle rect1 = new Rectangle(10, 5);
rect1.Print();
Rectangle rect2 = new Rectangle(20, 20);
rect2.Print();
}
}
}
|
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Entities.Core;
namespace Alabo.Datas.Stores.Random.Mongo {
public abstract class RandomMongoStore<TEntity, TKey> : RandomAsyncMongoStore<TEntity, TKey>,
IRandomStore<TEntity, TKey>
where TEntity : class, IKey<TKey>, IVersion, IEntity {
protected RandomMongoStore(IUnitOfWork unitOfWork) : base(unitOfWork) {
}
public TEntity GetRandom() {
//var find = Collection.AsQueryable().Where(x => true).OrderBy(a => Guid.NewGuid()).Take(1).FirstOrDefault();
var find = FirstOrDefault();
return find;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//This is an example of a quest, where the player has to pick up 3 wood
public class collectWoodQuest : Quest {
private void Start()
{
//Simple way to make a quest, just fill out all properties and add to objective list
questName = "Collect 3 wood";
questDescription = "Help the village with cutting wood";
itemReward = "DebugPotion";
experienceAward = 10;
int currentAmount = 0;
objectives.Add(new CollectObjective(this, "Wood", questDescription, false, currentAmount, 3));
objectives.ForEach(g => g.initialization()); //Loop through all objectives for quest and initialize them
}
private void addToUI()
{
Inventory.instance.addSword();
Inventory.instance.addQuest(this);
}
} |
using System.Diagnostics;
using Breeze.Screens;
using Breeze.Helpers;
using Breeze.Services.InputService;
using Breeze.AssetTypes.DataBoundTypes;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Breeze.AssetTypes
{
public class CentredImageAsset : DataboundAsset
{
private string loadedTexture = "";
private Texture2D texture;
private float aspectRatio;
public DataboundValue<ScaleMode> ScalingMode { get; set; }
public CentredImageAsset() { }
public CentredImageAsset(string txture, FloatRectangle position, ScaleMode scalemode = ScaleMode.Fill, float rotation = 0f)
{
texture = Solids.Instance.AssetLibrary.GetTexture(txture, true);
//texture = txture;
Position.Value = position;
ScalingMode.Value = scalemode;
aspectRatio = texture.Width / (float)texture.Height;
Rotation.Value = rotation;
}
public DataboundValue<float> Rotation { get; set; } = new DataboundValue<float>();
public DataboundValue<Color?> Colorize { get; set; } = new DataboundValue<Color?>();
public DataboundValue<string> Texture { get; set; } = new DataboundValue<string>();
//public DataboundValue<Texture2D> Texture2D { get; set; } = new DataboundValue<Texture2D>();
public DataboundValue<float> Scale { get; set; } = new DataboundValue<float>(1);
public override void Draw(BaseScreen.Resources screenResources, SmartSpriteBatch spriteBatch, ScreenAbstractor screen, float opacity, FloatRectangle? clip = null, Texture2D bgTexture = null, Vector2? scrollOffset = null)
{
if (texture != null)
{
if (aspectRatio == 0)
{
aspectRatio = texture.Width / (float)texture.Height;
}
}
if (Texture.HasValue() && (texture == null || loadedTexture != Texture.Value()))
{
loadedTexture = Texture.Value();
texture = Solids.Instance.AssetLibrary.GetTexture(loadedTexture, true);
}
Rectangle rect = screen.Translate(ActualPosition).ToRectangle(); //.Move(scrollOffset)
if (ScalingMode.Value == ScaleMode.BestFit)
{
float newWidth = rect.Width;
float newHeight = newWidth / aspectRatio;
if (newHeight > rect.Height)
{
newHeight = rect.Height;
newWidth = newHeight * aspectRatio;
}
float xOffset = (rect.Width - newWidth) / 2f;
float yOffset = (rect.Height - newHeight) / 2f;
rect = new Rectangle((int)(rect.X + xOffset), (int)(rect.Y + yOffset), (int)newWidth, (int)newHeight);
}
if (ScalingMode.Value == ScaleMode.Fill)
{
float newWidth = rect.Width;
float newHeight = newWidth / aspectRatio;
if (newHeight < rect.Height)
{
newHeight = rect.Height;
newWidth = newHeight * aspectRatio;
}
float xOffset = (rect.Width - newWidth) / 2f;
float yOffset = (rect.Height - newHeight) / 2f;
rect = new Rectangle((int)(rect.X + xOffset), (int)(rect.Y + yOffset), (int)newWidth, (int)newHeight);
}
if (ScalingMode.Value == ScaleMode.None)
{
rect.Width = texture.Width;
rect.Height = texture.Height;
}
if (texture != null)
{
Color c = Color.White;
if (Colorize.HasValue())
{
if (Colorize.Value() != null)
{
c = Colorize.Value().Value;
}
}
using (new SmartSpriteBatchManager(Solids.Instance.SpriteBatch))
{
if (clip == null)
{
rect = new Rectangle(rect.X + (int) (rect.Width / 2f), rect.Y + (int) (rect.Height / 2f), rect.Width, rect.Height);
spriteBatch.Draw(texture, rect, null, c* opacity, Rotation.Value, new Vector2(texture.Width / 2, texture.Height / 2), SpriteEffects.None, 1f);
}
else
{
FloatRectangle? tclip = screen.Translate(clip);
Rectangle source = new Rectangle(0, 0, texture.Width, texture.Height);
(Rectangle position, Rectangle? source) translator = TextureHelpers.GetAdjustedDestAndSourceAfterClip(new FloatRectangle(rect), source, tclip);
using (new SmartSpriteBatchManager(Solids.Instance.SpriteBatch))
{
spriteBatch.Draw(texture, translator.position, translator.source, c * opacity, Rotation.Value, new Vector2(translator.source.Value.Width / 2f, translator.source.Value.Height / 2f), SpriteEffects.None, 1f);
}
}
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMoveBehavior_Prototype : MonoBehaviour
{
public int playerSpeed = 10;
public int playerJump = 1250;
public float xMove;
public bool isAirborn;
public static char activeSide;
// Start is called before the first frame update
void Start()
{
activeSide = 't';
if (activeSide == 't')
{
Debug.Log("Active side set to Top");
}
}
// Update is called once per frame
void Update()
{
MovePlayer();
SetActiveSide();
}
void MovePlayer()
{
// controls
xMove = Input.GetAxis("Horizontal");
if(Input.GetKeyDown(KeyCode.UpArrow) && isAirborn == false)
{
Jump();
isAirborn = true;
}
// animation (maybe)
// active side (later)
// physics
gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(xMove * playerSpeed, gameObject.GetComponent<Rigidbody2D>().velocity.y);
}
void Jump()
{
GetComponent<Rigidbody2D>().AddForce(Vector2.up * playerJump);
}
void OnCollisionEnter2D (Collision2D col)
{
if(col.gameObject.tag == "Floor" || col.gameObject.tag == "Enemy")
{
isAirborn = false;
}
}
void SetActiveSide()
{
if(Input.GetKeyDown(KeyCode.W))
{
activeSide = 't';
Debug.Log("Active side set to Top");
}
else if(Input.GetKeyDown(KeyCode.A))
{
activeSide = 'l';
Debug.Log("Active side set to Left");
}
else if (Input.GetKeyDown(KeyCode.S))
{
activeSide = 'b';
Debug.Log("Active side set to Bottom");
}
else if (Input.GetKeyDown(KeyCode.D))
{
activeSide = 'r';
Debug.Log("Active side set to Right");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Web : AmbientThing
{
private void OnEnable()
{
health = 3;
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using com.Sconit.Entity.SYS;
using System.ComponentModel.DataAnnotations;
//TODO: Add other using statements here
namespace com.Sconit.Entity.MRP.MD
{
public partial class MrpFlowDetail
{
public double HaltTime { get; set; }
public double TrialTime { get; set; }
//public Double CalcStock
//{
// get
// {
// return this.MaxStock > this.SafeStock ? this.MaxStock : this.SafeStock;
// }
//}
[CodeDetailDescriptionAttribute(CodeMaster = com.Sconit.CodeMaster.CodeMaster.OrderType, ValueField = "Type")]
[Display(Name = "MrpFlowDetail_Type", ResourceType = typeof(Resources.MRP.MrpFlowDetail))]
public string TypeDescription { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab9
{
class Student
{
//Data members
private string stuName;
private string stuHmtwn;
private string stuFavfood;
private string stuFavcolor;
private DateTime stuDateofBirth;
#region Properties
//Properties
public string Name
{
set // give a value to the name
{ //Validation
stuName = value; // Value is always on the right side
}
get //retrieve the name
{ //Validation
return stuName;
}
}
public string Hmtwn
{
set // give a value to the name
{ //Validation
stuHmtwn = value; // Value is always on the right side
}
get //retrieve the name
{ //Validation
return stuHmtwn;
}
}
public string FavFood
{
set // give a value to the name
{ //Validation
stuFavfood = value; // Value is always on the right side
}
get //retrieve the name
{ //Validation
return stuFavfood;
}
}
public string FavColor
{
set // give a value to the name
{ //Validation
stuFavcolor = value; // Value is always on the right side
}
get //retrieve the name
{ //Validation
return stuFavcolor;
}
}
public DateTime DateOfBirth
{
set // give a value to the name
{ //Validation
stuDateofBirth = value; // Value is always on the right side
}
get //retrieve the name
{ //Validation
return stuDateofBirth;
}
}
public void PrintInfo() // Use Properties ie Name vs stuName
{
Console.WriteLine("Student Name: "+Name);
Console.WriteLine("Student Hometown: "+Hmtwn);
Console.WriteLine("Student Favorite Food: "+FavFood);
Console.WriteLine("Student Favorite Color: "+FavColor);
Console.WriteLine("Student Date of Birth: "+DateOfBirth);
}
}
#endregion
}
/* example of Main
static void Main(string[] args)
{
Student Mike = new Student();
Mike.Name = "Mike Valda"; //Set
Console.Writeline(Mike.Name); //Get
Mike.Hmtwn = "Troy";
Mike.FavFood = "Pizza";
Mike.DateofBirth = DateTime.Parse("01/15/1970");
Mike.PrintInfo();
*/ |
using System;
using System.Collections.Generic;
using System.Text;
using Linedata.Foundation.EventPublisher;
using Linedata.Foundation.Messaging;
namespace EventPublisher
{
public class TopicStreamNameMapper : ITopicStreamNameMapper
{
const string streamPrefix = "gateway";
public bool TryGetStreamName(Topic topic, out string stream)
{
var topicName = topic.ToString();
if (topicName.StartsWith("\\FixConnections"))
{
stream = $"$ce-{streamPrefix}.FixConnectionAggregate";
return true;
}
if (topicName.StartsWith("\\Accounts"))
{
stream = $"$ce-{streamPrefix}.Account";
return true;
}
stream = null;
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace ChefDishes.Models
{
public class Chef
{
[Key]
public int ChefId { get; set; }
[Required]
[MinLength(3, ErrorMessage = "First name must be at least 3 characters")]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[MinLength(3, ErrorMessage = "Last name must be at least 3 characters")]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
// Validate over 18
[Display(Name = "Date of Birth")]
public DateTime Dob { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.Now;
public DateTime UpdatedAt { get; set; } = DateTime.Now;
public List<Dish> CreatedDishes { get; set; }
}
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Utilities;
using UnityEngine;
namespace Microsoft.MRDL
{
/// <summary>
/// Controls the scale a set of transforms under a target transform.
/// Uses noise for variation.
/// </summary>
[ExecuteInEditMode]
public class Growbies : MonoBehaviour
{
const float minGrowthCutoff = 0.001f;
public enum CorkscrewAxisEnum
{
X,
Y,
Z,
}
public bool IsDirty { get; set; }
[Range(0,1)]
[Header("Animated Parameters")]
public float Growth = 0f;
[Header("Static Parameters")]
[SerializeField]
[Tooltip("Random values determined by seed")]
[Range(0, 1)]
public float growthRandomness = 0.5f;
[Range(0, 1)]
public float growthJitter = 0;
[SerializeField]
[Tooltip("Multiplier for scale of transforms in heirarchy from first to last")]
private AnimationCurve growthScaleMultiplier = AnimationCurve.EaseInOut(0f, 1f, 1f, 1f);
[Range(0, 1)]
[Tooltip("How much the growbies rotate on their Y axis as they grow")]
public float corkScrewAmount = 0;
[Range(1, 20)]
[Tooltip("How jittery to make the corkscrew effect")]
public float corkscrewJitter = 5;
[SerializeField]
CorkscrewAxisEnum corkscrewAxis = CorkscrewAxisEnum.Y;
[SerializeField]
private int seed = 1234;
[Header("Non-uniform scaling (set to linear for uniform scaling)")]
[SerializeField]
private AnimationCurve xAxisScale = AnimationCurve.Linear(0f, 0f, 1f, 1f);
[SerializeField]
private AnimationCurve yAxisScale = AnimationCurve.Linear(0f, 0f, 1f, 1f);
[SerializeField]
private AnimationCurve zAxisScale = AnimationCurve.Linear(0f, 0f, 1f, 1f);
private Vector3 finalScale;
private System.Random random;
private FastSimplexNoise noise;
private float growbieSizeLastFrame = 0;
private int numTransformLastFrame = 0;
private float[] randomGrowthValues;
private void OnEnable()
{
// This will ensure we update at least once
growbieSizeLastFrame = 1f - Growth;
GenerateRandomGrowthValues();
}
private void Update()
{
Growth = Mathf.Clamp01(Growth);
if (Application.isPlaying && Growth == growbieSizeLastFrame && !IsDirty)
{
// Nothing to do!
return;
}
IsDirty = false;
int numTransforms = transform.childCount;
if (numTransformLastFrame != numTransforms)
{
GenerateRandomGrowthValues();
}
for (int i = 0; i < numTransforms; i++)
{
Transform growbie = transform.GetChild(i);
if (Growth < minGrowthCutoff)
{
growbie.gameObject.SetActive(false);
continue;
}
float scale = Growth * (growthScaleMultiplier.Evaluate((float)i / numTransforms));
if (growthRandomness > 0)
{
scale = scale * (1f - (growthRandomness * randomGrowthValues[i]));
}
if (corkScrewAmount > 0)
{
float corkscrew = (float)noise.Evaluate(Growth, (scale + i) * corkscrewJitter);
Vector3 eulerAngles = growbie.localEulerAngles;
switch (corkscrewAxis)
{
case CorkscrewAxisEnum.X:
eulerAngles.x = corkscrew * 360 * corkScrewAmount;
break;
case CorkscrewAxisEnum.Y:
eulerAngles.y = corkscrew * 360 * corkScrewAmount;
break;
case CorkscrewAxisEnum.Z:
eulerAngles.z = corkscrew * 360 * corkScrewAmount;
break;
}
growbie.localEulerAngles = eulerAngles;
}
if (growthJitter > 0)
{
float growthJitterMultiplier = (1 + growthJitter);
float jitter = (float)noise.Evaluate(Growth * 15 * growthJitterMultiplier, (i * 15 * growthJitterMultiplier));
scale += (jitter * (growthJitter * 0.1f));
}
if (scale < 0.001f)
{
growbie.gameObject.SetActive(false);
}
else
{
growbie.gameObject.SetActive(true);
finalScale = Vector3.one * scale;
// Apply non-uniform scaling
finalScale.x = xAxisScale.Evaluate(scale);
finalScale.y = yAxisScale.Evaluate(scale);
finalScale.z = zAxisScale.Evaluate(scale);
// Apply final scale
growbie.localScale = finalScale;
}
}
growbieSizeLastFrame = Growth;
numTransformLastFrame = numTransforms;
}
private void GenerateRandomGrowthValues()
{
random = new System.Random(seed);
randomGrowthValues = new float[transform.childCount];
for (int i = 0; i < randomGrowthValues.Length; i++)
{
randomGrowthValues[i] = (float)random.NextDouble();
}
if (noise == null)
{
noise = new FastSimplexNoise(seed);
}
}
}
} |
using UnityEngine;
namespace UnityGPShockwaves
{
/// <summary>A generic interface for shock wave objects. Provides virtual methods to be overridden by subclass.</summary>
/// <author>Michael Jones</author>
public class Shockwave : ScriptableObject
{
/// <summary>The initial wave speed. (m/s)</summary>
[Tooltip("The initial wave speed. (m/s)")]
public float initialSpeed = 500F;
/// <summary>The medium of the shock wave.</summary>
[Tooltip("The properties of the shock wave medium, used for calculating shock wave effects. Uses default ShockWaveMedium if none given.")]
public ShockwaveMedium waveMedium;
/// <summary>The color used for low pressure particles.</summary>
[Tooltip("The color used for low pressure particles.")]
public Color color1 = Color.green;
/// <summary>The color used for high pressure particles.</summary>
[Tooltip("The color used for high pressure particles.")]
public Color color2 = Color.red;
/// <summary>Render a visualisation of the shock wave.</summary>
[Tooltip("Note: Enabling visualisation may hinder performance.")]
public bool visualisation = false;
/// <summary>The accuracy of the simulation. Higher accuracy means higher performance cost.</summary>
[Tooltip("Higher accuracy will result in a better simulation but may hinder performance. Defaults to 1.")]
public float accuracy = 1F;
/// <summary>Print debug statements.</summary>
[Tooltip("Print debug statements.")]
public bool debugMode = false;
/// <summary>Disabled instance will have no effect.</summary>
[HideInInspector]
public bool enabled = true;
/// <summary>Has the Setup function been called?</summary>
protected bool setup = false;
/// <summary>Setup message must be called by handler.</summary>
public virtual void Setup()
{
if (!enabled) return;
// TODO: fields bounds checks
if (!waveMedium)
{
Debug.LogError("Missing wave medium!");
return;
}
// warn if wave is too slow
if (initialSpeed < waveMedium.speedOfSound) Debug.LogWarning("initialSpeed (" + initialSpeed + ") is less than shockWaveMedium.speedOfSound (" + waveMedium.speedOfSound + "). The shock wave will have no effect below the speed of sound.");
setup = true;
}
/// <summary>Reset this instance.</summary>
public virtual void Reset()
{
setup = false;
}
/// <summary>Spawns a shock wave at the given origin position.</summary>
/// <param name="origin">The origin position in world space.</param>
public virtual void Spawn(Vector3 origin)
{
if (!enabled) return;
if (!setup)
{
Debug.LogError("Can't spawn shock wave. Call Shockwave.Setup first!");
return;
}
}
/// <summary>FixedUpdate message must be called by handler every fixed update.</summary>
public virtual void FixedUpdate()
{
if (!enabled) return;
}
/// <summary>OnRenderObject message must be called by handler.</summary>
public virtual void OnRenderObject()
{
if (!enabled || !visualisation) return;
}
}
}
|
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System;
namespace PatientWebAppE2ETests.Pages
{
public class AddFeedbackPage
{
private readonly IWebDriver driver;
private readonly string URI;
private IWebElement CommentElement => driver.FindElement(By.Id("text_area_id"));
private IWebElement IsAnonymousElement => driver.FindElement(By.XPath("//input[@id = 'no_anonymous']"));
private IWebElement IsAllowedElement => driver.FindElement(By.XPath(".//div[contains(.,'I don't want my feedback to be published')]/input"));
private IWebElement SubmitButtonElement => driver.FindElement(By.Id("submit_button"));
private IWebElement AlertElement => driver.FindElement(By.Id("alert"));
public const string ValidCommentMessage = "You have successfuly left a feedback";
public const string InvalidCommentMessage = "Feedback cannot be empty";
public AddFeedbackPage(IWebDriver driver, string uri)
{
this.driver = driver;
URI = uri;
}
public void InsertComment(string comment)
{
CommentElement.SendKeys(comment);
}
public void InsertIsAnonymous(string isAnonymous)
{
if (isAnonymous.Equals("no"))
{
IsAnonymousElement.Click();
}
}
public void InsertIsAllowed(string isAllowed)
{
if (isAllowed.Equals("no"))
{
IsAllowedElement.Click();
}
}
public void SubmitForm()
{
SubmitButtonElement.Click();
}
public string GetDialogMessage()
{
return AlertElement.Text;
}
public void WaitForFormSubmit()
{
var wait = new WebDriverWait(driver, new TimeSpan(0, 0, 40));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.UrlToBe(URI));
}
public void Navigate() => driver.Navigate().GoToUrl(URI);
}
}
|
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
using DMS;
using DMS.BusinessObject;
using System.IO;
using DMS.Utils;
namespace DMS.Presentation
{
/// <summary>
/// Summary description for SCM_Parameter.
/// </summary>
public class frmParameter : System.Windows.Forms.Form
{
#region ".NET Code"
private System.ComponentModel.IContainer components = null;
private System.Windows.Forms.DataGridTableStyle dataGridTableStyle1;
private System.Windows.Forms.DataGridTextBoxColumn dataGridTextBoxColumn1;
private System.Windows.Forms.DataGridTextBoxColumn dataGridTextBoxColumn2;
private System.Windows.Forms.DataGridTextBoxColumn dataGridTextBoxColumn3;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.Panel panel4;
private System.Windows.Forms.DataGrid grdParam;
private System.Windows.Forms.LinkLabel lnkBrowse;
private System.Windows.Forms.TextBox txtParamValue;
private System.Windows.Forms.TextBox txtDescription;
private System.Windows.Forms.TextBox txtParamName;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Label label9;
private DotNetSkin.SkinControls.SkinButton btnClose;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.ComboBox cboParamGroup;
private System.Windows.Forms.Label label1;
private DotNetSkin.SkinControls.SkinButton btnView;
private Label lblParameter;
private TextBox txtParameter;
private DotNetSkin.SkinControls.SkinButton btnUpdate;
public frmParameter()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
InitializeCombo();
FixPosition();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
///
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#endregion
#region "Variable"
private DataTable m_dt = null;
private CurrencyManager m_manager = null;
private clsParameterBO bo = new clsParameterBO();
private static log4net.ILog log = log4net.LogManager.GetLogger(typeof(frmParameter));
public DataTable DataSource
{
get{return m_dt;}
}
#endregion
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmParameter));
this.grdParam = new System.Windows.Forms.DataGrid();
this.dataGridTableStyle1 = new System.Windows.Forms.DataGridTableStyle();
this.dataGridTextBoxColumn1 = new System.Windows.Forms.DataGridTextBoxColumn();
this.dataGridTextBoxColumn2 = new System.Windows.Forms.DataGridTextBoxColumn();
this.dataGridTextBoxColumn3 = new System.Windows.Forms.DataGridTextBoxColumn();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.label9 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.panel3 = new System.Windows.Forms.Panel();
this.panel2 = new System.Windows.Forms.Panel();
this.panel1 = new System.Windows.Forms.Panel();
this.panel4 = new System.Windows.Forms.Panel();
this.lnkBrowse = new System.Windows.Forms.LinkLabel();
this.btnUpdate = new DotNetSkin.SkinControls.SkinButton();
this.txtParamValue = new System.Windows.Forms.TextBox();
this.txtDescription = new System.Windows.Forms.TextBox();
this.txtParamName = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.btnClose = new DotNetSkin.SkinControls.SkinButton();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.lblParameter = new System.Windows.Forms.Label();
this.txtParameter = new System.Windows.Forms.TextBox();
this.btnView = new DotNetSkin.SkinControls.SkinButton();
this.cboParamGroup = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.grdParam)).BeginInit();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
this.SuspendLayout();
//
// grdParam
//
this.grdParam.AllowSorting = false;
this.grdParam.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.grdParam.CaptionVisible = false;
this.grdParam.DataMember = "";
this.grdParam.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.grdParam.Location = new System.Drawing.Point(5, 237);
this.grdParam.Name = "grdParam";
this.grdParam.ReadOnly = true;
this.grdParam.Size = new System.Drawing.Size(839, 250);
this.grdParam.TabIndex = 3;
this.grdParam.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] {
this.dataGridTableStyle1});
this.grdParam.CurrentCellChanged += new System.EventHandler(this.grdParam_CurrentCellChanged);
//
// dataGridTableStyle1
//
this.dataGridTableStyle1.AllowSorting = false;
this.dataGridTableStyle1.AlternatingBackColor = System.Drawing.Color.AliceBlue;
this.dataGridTableStyle1.DataGrid = this.grdParam;
this.dataGridTableStyle1.GridColumnStyles.AddRange(new System.Windows.Forms.DataGridColumnStyle[] {
this.dataGridTextBoxColumn1,
this.dataGridTextBoxColumn2,
this.dataGridTextBoxColumn3});
this.dataGridTableStyle1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
//
// dataGridTextBoxColumn1
//
this.dataGridTextBoxColumn1.Format = "";
this.dataGridTextBoxColumn1.FormatInfo = null;
this.dataGridTextBoxColumn1.HeaderText = "Parameter Name";
this.dataGridTextBoxColumn1.MappingName = "Param_Name";
this.dataGridTextBoxColumn1.Width = 190;
//
// dataGridTextBoxColumn2
//
this.dataGridTextBoxColumn2.Format = "";
this.dataGridTextBoxColumn2.FormatInfo = null;
this.dataGridTextBoxColumn2.HeaderText = "Parameter Value";
this.dataGridTextBoxColumn2.MappingName = "Param_Value";
this.dataGridTextBoxColumn2.Width = 135;
//
// dataGridTextBoxColumn3
//
this.dataGridTextBoxColumn3.Format = "";
this.dataGridTextBoxColumn3.FormatInfo = null;
this.dataGridTextBoxColumn3.HeaderText = "Description";
this.dataGridTextBoxColumn3.MappingName = "Description";
this.dataGridTextBoxColumn3.Width = 400;
//
// groupBox1
//
this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox1.Controls.Add(this.label9);
this.groupBox1.Controls.Add(this.label8);
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Controls.Add(this.label7);
this.groupBox1.Controls.Add(this.panel3);
this.groupBox1.Controls.Add(this.panel2);
this.groupBox1.Controls.Add(this.panel1);
this.groupBox1.Controls.Add(this.panel4);
this.groupBox1.Location = new System.Drawing.Point(8, 60);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(839, 64);
this.groupBox1.TabIndex = 9;
this.groupBox1.TabStop = false;
//
// label9
//
this.label9.Location = new System.Drawing.Point(32, 39);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(328, 16);
this.label9.TabIndex = 21;
this.label9.Tag = "";
this.label9.Text = "WS: Parameters relate to Windows Service";
//
// label8
//
this.label8.Location = new System.Drawing.Point(400, 16);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(301, 16);
this.label8.TabIndex = 16;
this.label8.Tag = "";
this.label8.Text = "SP: Parameters relate to Stock Policy";
//
// label5
//
this.label5.Location = new System.Drawing.Point(32, 16);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(328, 23);
this.label5.TabIndex = 14;
this.label5.Text = "PPO: Parameters relate to Proposal purchase Order";
//
// label7
//
this.label7.Location = new System.Drawing.Point(400, 39);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(311, 23);
this.label7.TabIndex = 14;
this.label7.Text = "OTHER: Other parameters";
//
// panel3
//
this.panel3.BackColor = System.Drawing.Color.MediumBlue;
this.panel3.Location = new System.Drawing.Point(385, 20);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(8, 8);
this.panel3.TabIndex = 16;
//
// panel2
//
this.panel2.BackColor = System.Drawing.Color.MediumBlue;
this.panel2.Location = new System.Drawing.Point(385, 43);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(8, 8);
this.panel2.TabIndex = 15;
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.MediumBlue;
this.panel1.ForeColor = System.Drawing.SystemColors.Desktop;
this.panel1.Location = new System.Drawing.Point(16, 20);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(8, 8);
this.panel1.TabIndex = 14;
//
// panel4
//
this.panel4.BackColor = System.Drawing.Color.MediumBlue;
this.panel4.Location = new System.Drawing.Point(16, 43);
this.panel4.Name = "panel4";
this.panel4.Size = new System.Drawing.Size(8, 8);
this.panel4.TabIndex = 17;
//
// lnkBrowse
//
this.lnkBrowse.Location = new System.Drawing.Point(418, 79);
this.lnkBrowse.Name = "lnkBrowse";
this.lnkBrowse.Size = new System.Drawing.Size(24, 16);
this.lnkBrowse.TabIndex = 7;
this.lnkBrowse.TabStop = true;
this.lnkBrowse.Text = "[...]";
this.lnkBrowse.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkBrowse_LinkClicked);
//
// btnUpdate
//
this.btnUpdate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnUpdate.Image = ((System.Drawing.Image)(resources.GetObject("btnUpdate.Image")));
this.btnUpdate.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnUpdate.Location = new System.Drawing.Point(681, 70);
this.btnUpdate.Name = "btnUpdate";
this.btnUpdate.Size = new System.Drawing.Size(69, 23);
this.btnUpdate.TabIndex = 8;
this.btnUpdate.Text = " Save";
this.btnUpdate.Click += new System.EventHandler(this.cmdUpdate_Click);
//
// txtParamValue
//
this.txtParamValue.Location = new System.Drawing.Point(157, 80);
this.txtParamValue.Name = "txtParamValue";
this.txtParamValue.Size = new System.Drawing.Size(256, 20);
this.txtParamValue.TabIndex = 6;
this.txtParamValue.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtParamValue_KeyPress);
//
// txtDescription
//
this.txtDescription.Enabled = false;
this.txtDescription.Location = new System.Drawing.Point(157, 48);
this.txtDescription.Name = "txtDescription";
this.txtDescription.Size = new System.Drawing.Size(256, 20);
this.txtDescription.TabIndex = 5;
//
// txtParamName
//
this.txtParamName.Enabled = false;
this.txtParamName.Location = new System.Drawing.Point(157, 16);
this.txtParamName.Name = "txtParamName";
this.txtParamName.Size = new System.Drawing.Size(256, 20);
this.txtParamName.TabIndex = 4;
//
// label4
//
this.label4.Location = new System.Drawing.Point(24, 48);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(127, 23);
this.label4.TabIndex = 6;
this.label4.Text = "Description";
//
// label3
//
this.label3.Location = new System.Drawing.Point(24, 80);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(127, 23);
this.label3.TabIndex = 5;
this.label3.Text = "ParameterValue";
//
// label2
//
this.label2.Location = new System.Drawing.Point(24, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(127, 23);
this.label2.TabIndex = 4;
this.label2.Text = "Parameter Name";
//
// groupBox2
//
this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox2.Controls.Add(this.btnClose);
this.groupBox2.Controls.Add(this.txtParamName);
this.groupBox2.Controls.Add(this.label2);
this.groupBox2.Controls.Add(this.txtParamValue);
this.groupBox2.Controls.Add(this.lnkBrowse);
this.groupBox2.Controls.Add(this.label4);
this.groupBox2.Controls.Add(this.label3);
this.groupBox2.Controls.Add(this.txtDescription);
this.groupBox2.Controls.Add(this.btnUpdate);
this.groupBox2.Location = new System.Drawing.Point(8, 125);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(839, 105);
this.groupBox2.TabIndex = 12;
this.groupBox2.TabStop = false;
//
// btnClose
//
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnClose.Image = ((System.Drawing.Image)(resources.GetObject("btnClose.Image")));
this.btnClose.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnClose.Location = new System.Drawing.Point(759, 69);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(69, 23);
this.btnClose.TabIndex = 9;
this.btnClose.Text = " Close";
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// groupBox3
//
this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox3.Controls.Add(this.lblParameter);
this.groupBox3.Controls.Add(this.txtParameter);
this.groupBox3.Controls.Add(this.btnView);
this.groupBox3.Controls.Add(this.cboParamGroup);
this.groupBox3.Controls.Add(this.label1);
this.groupBox3.Location = new System.Drawing.Point(8, 8);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(841, 50);
this.groupBox3.TabIndex = 13;
this.groupBox3.TabStop = false;
//
// lblParameter
//
this.lblParameter.Location = new System.Drawing.Point(471, 17);
this.lblParameter.Name = "lblParameter";
this.lblParameter.Size = new System.Drawing.Size(57, 17);
this.lblParameter.TabIndex = 14;
this.lblParameter.Text = "Param";
this.lblParameter.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// txtParameter
//
this.txtParameter.Location = new System.Drawing.Point(547, 14);
this.txtParameter.MaxLength = 20;
this.txtParameter.Name = "txtParameter";
this.txtParameter.Size = new System.Drawing.Size(113, 20);
this.txtParameter.TabIndex = 15;
//
// btnView
//
this.btnView.Image = ((System.Drawing.Image)(resources.GetObject("btnView.Image")));
this.btnView.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnView.Location = new System.Drawing.Point(681, 12);
this.btnView.Name = "btnView";
this.btnView.Size = new System.Drawing.Size(76, 23);
this.btnView.TabIndex = 6;
this.btnView.Text = " Search";
this.btnView.Click += new System.EventHandler(this.btnView_Click);
//
// cboParamGroup
//
this.cboParamGroup.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboParamGroup.Location = new System.Drawing.Point(140, 14);
this.cboParamGroup.Name = "cboParamGroup";
this.cboParamGroup.Size = new System.Drawing.Size(326, 21);
this.cboParamGroup.TabIndex = 4;
//
// label1
//
this.label1.Location = new System.Drawing.Point(13, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(121, 23);
this.label1.TabIndex = 3;
this.label1.Text = "Parameter Group";
//
// frmParameter
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(856, 494);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.grdParam);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MinimumSize = new System.Drawing.Size(632, 432);
this.Name = "frmParameter";
this.Text = "SCM - Parameter Management";
((System.ComponentModel.ISupportInitialize)(this.grdParam)).EndInit();
this.groupBox1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.ResumeLayout(false);
}
#endregion
#region MainFunctions
/// <summary>
///fix position cho cac control
/// </summary>
/// <remarks>
/// Author: Nguyen Minh Khoa G3
/// Modified: 18-Apr-2011
/// </remarks>
public void FixPosition()
{
label1.Top = 10;
cboParamGroup.Top = 10;
label1.Left = 10;
cboParamGroup.Left = label1.Right + 5;
groupBox3.Height = cboParamGroup.Bottom + 12;
groupBox1.Top = groupBox3.Bottom + 8;
groupBox2.Top = groupBox1.Bottom + 5;
grdParam.Top = groupBox2.Bottom + 5;
btnView.Top = cboParamGroup.Top - 2;
label2.Top = 10;
txtParamName.Top = 10;
label4.Top = label2.Bottom+ 5;
label3.Top = label4.Bottom+5;
txtDescription.Top = label4.Top;
txtParamValue.Top = label3.Top;
label2.Left = 10;
label3.Left = 10;
label4.Left = 10;
txtParamName.Left = label2.Right + 5;
txtDescription.Left = txtParamName.Left;
txtParamValue.Left = txtParamName.Left;
lnkBrowse.Top = txtParamValue.Top +7;
btnUpdate.Top = txtParamValue.Top - 3;
btnClose.Top = btnUpdate.Top;
}
/// <summary>
/// bind du lieu tu datatable vao cac textbox
/// </summary>
/// <remarks>
/// Author: Nguyen Minh Khoa G3
/// Modified: 18-Apr-2011
/// </remarks>
public void BindDataToControl()
{
if (m_dt.Rows.Count > 0)
{
txtParamName.Text = m_dt.Rows[m_manager.Position]["PARAM_NAME"].ToString();
txtDescription.Text = m_dt.Rows[m_manager.Position]["DESCRIPTION"].ToString();
txtParamValue.Text = m_dt.Rows[m_manager.Position]["PARAM_VALUE"].ToString();
btnUpdate.Enabled = true;
}
else
{
btnUpdate.Enabled = false;
}
}
/// <summary>
/// Nhan mot datable tu ham LoadAll, sau do gan vao datasource cua combobox
/// </summary>
/// <remarks>
/// Author: Nguyen Minh Khoa G3
/// Modified: 18-Apr-2011
/// </remarks>
private void InitializeCombo()
{
try
{
m_dt=bo.LoadAll();
DataRow dr = m_dt.NewRow();
dr["PARAM_GROUP"] = "[ALL]";
m_dt.Rows.InsertAt(dr, 0);
cboParamGroup.DataSource= DataSource;
cboParamGroup.DisplayMember= "PARAM_GROUP";
cboParamGroup.ValueMember= "PARAM_GROUP";
(cboParamGroup.DataSource as DataTable).DefaultView.Sort = "PARAM_GROUP";
cboParamGroup.SelectedIndex=0;
}
catch(Exception ex)
{
log.Error(ex.Message, ex);
MessageBox.Show(clsResources.GetMessage("errors.available"), clsResources.GetMessage("messages.general"), MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
#region Event
private void grdParam_CurrentCellChanged(object sender, System.EventArgs e)
{
BindDataToControl();
}
private void btnView_Click(object sender, System.EventArgs e)
{
if(cboParamGroup.Text=="Time")
{
lnkBrowse.Enabled=false;
}
else
{
lnkBrowse.Enabled=true;
}
string strgroup = cboParamGroup.Text == "[ALL]" ? "%%" : cboParamGroup.Text;
m_dt=bo.GetOne(strgroup, txtParameter.Text.Trim());
grdParam.DataSource=DataSource;
m_manager = (CurrencyManager)this.BindingContext[DataSource];
BindDataToControl();
}
private void lnkBrowse_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
FolderBrowserDialog fbrdlg = new FolderBrowserDialog();
fbrdlg.ShowNewFolderButton = true;
if (fbrdlg.ShowDialog() == DialogResult.OK)
{
this.txtParamValue.Text=fbrdlg.SelectedPath;
}
}
private void txtParamValue_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if(cboParamGroup.Text=="Time")
{
char chr = e.KeyChar;
if(!(chr >= '1' && chr <= '9' || chr == 8 || chr == 13))
e.Handled = true;
}
}
private void btnClose_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void cmdUpdate_Click(object sender, System.EventArgs e)
{
string strValue, strName, strType;
strValue=txtParamValue.Text;
strName=txtParamName.Text;
strType=m_dt.Rows[m_manager.Position]["PARAM_TYPE"].ToString();
System.Windows.Forms.DialogResult i = MessageBox.Show(clsResources.GetMessage("messages.save"), clsResources.GetMessage("messages.general"), MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (i.ToString() == "No")
return;
if (strValue=="")
{
MessageBox.Show(clsResources.GetMessage("errors.fill", txtParamValue.Text), clsResources.GetMessage("messages.general"), MessageBoxButtons.OK, MessageBoxIcon.Error);
txtParamValue.Focus();
txtParamValue.SelectAll();
return;
}
// if(strType =="s" && m_dt.Rows[m_manager.Position]["PARAM_NAME"].ToString() != "WS_RURAL_SKU_REMINDER_PERIOD") //nghiahbt added 28-May-07
// {
// strDes = m_dt.Rows[m_manager.Position]["DESCRIPTION"].ToString();
// if(strDes.IndexOf("day")!= -1)
// {
// strValue = strValue.ToUpper();
// if(strValue!= "MON" && strValue!= "TUE" && strValue!= "WED"
// && strValue!= "THU" && strValue!= "FRI" && strValue!= "SAT" && strValue!= "SUN")
// {
// MessageBox.Show(strDes,clsResources.GetMessage("messages.general"),MessageBoxButtons.OK, MessageBoxIcon.Error);
// txtParamValue.Focus();
// txtParamValue.SelectAll();
// return;
//
// }
// }
// }
if( bo.Validate(strType, strValue) == false)
{
// if(strType=="s")
// MessageBox.Show(clsResources.GetMessage("errors.exist", txtParamValue.Text), clsResources.GetMessage("messages.general"), MessageBoxButtons.OK, MessageBoxIcon.Error);
// else
if(strType=="t"||strType=="n")
MessageBox.Show(clsResources.GetMessage("errors.number", "Time"), clsResources.GetMessage("messages.general"), MessageBoxButtons.OK, MessageBoxIcon.Error);
else if(strType=="d")
MessageBox.Show(clsResources.GetMessage("errors.date"), clsResources.GetMessage("messages.general"), MessageBoxButtons.OK, MessageBoxIcon.Error);
else if(strType=="b")
MessageBox.Show(clsResources.GetMessage("errors.bool"), clsResources.GetMessage("messages.general"), MessageBoxButtons.OK, MessageBoxIcon.Error);
m_dt.RejectChanges();
txtParamValue.Focus();
txtParamValue.SelectAll();
return;
}
if (bo.Update(strValue, strName))
{
m_dt.Rows[m_manager.Position]["PARAM_VALUE"] = txtParamValue.Text;
m_dt.AcceptChanges();
MessageBox.Show(clsResources.GetMessage("messages.success"), clsResources.GetMessage("messages.general"), MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
#endregion
}
}
|
using Contoso.Extensions.Services;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KFrame.Sources
{
/// <summary>
/// Class DbSourceAbstract.
/// </summary>
public abstract class DbSourceAbstract : SourceAbstract
{
/// <summary>
/// Gets or sets the name of the connection.
/// </summary>
/// <value>The name of the connection.</value>
public string ConnectionName { get; set; }
/// <summary>
/// Gets or sets the schema.
/// </summary>
/// <value>The schema.</value>
public string Schema { get; set; } = "dbo";
/// <summary>
/// Gets or sets the database service.
/// </summary>
/// <value>The database service.</value>
public IDbService DbService { get; set; } = new DbService();
/// <summary>
/// Gets or sets a value indicating whether [use variant].
/// </summary>
/// <value><c>true</c> if [use variant]; otherwise, <c>false</c>.</value>
public bool UseVariant { get; set; } = false;
/// <summary>
/// execute as an asynchronous operation.
/// </summary>
/// <param name="b">The b.</param>
/// <param name="ctx">The CTX.</param>
/// <param name="sql">The SQL.</param>
/// <returns>Task.</returns>
protected static async Task ExecuteAsync(StringBuilder b, IDbConnection ctx, string sql)
{
b.AppendLine(sql);
try
{
foreach (var x in sql.Split(new[] { "GO" }, StringSplitOptions.RemoveEmptyEntries))
await ctx.ExecuteAsync(x);
}
catch (Exception e) { b.AppendLine("\nERROR"); b.Append(e); }
}
/// <summary>
/// Gets the i frame procedure.
/// </summary>
/// <param name="chapter">The chapter.</param>
/// <returns>System.String.</returns>
/// <value>The i frame procedure.</value>
protected abstract string GetIFrameProcedure(string chapter);
/// <summary>
/// get i frame as an asynchronous operation.
/// </summary>
/// <param name="chapter">The chapter.</param>
/// <param name="sources">The sources.</param>
/// <returns>Task<dynamic>.</returns>
/// <exception cref="ArgumentNullException">DbService</exception>
/// <exception cref="ArgumentNullException">Schema</exception>
public override async Task<dynamic> GetIFrameAsync(string chapter, IEnumerable<IKFrameSource> sources)
{
if (DbService == null)
throw new ArgumentNullException(nameof(DbService));
if (string.IsNullOrEmpty(Schema))
throw new ArgumentNullException(nameof(Schema));
using (var ctx = DbService.GetConnection(ConnectionName))
{
var s = await ctx.QueryMultipleAsync(GetIFrameProcedure(chapter), null, commandType: CommandType.StoredProcedure);
var f = s.Read().Single(); var frame = (DateTime)f.Frame; var frameId = (int?)f.FrameId;
var result = (IDictionary<string, object>)new ExpandoObject();
result.Add("frame", frame.Ticks);
foreach (var source in sources.Cast<IKFrameDbSource>())
result.Add(source.Param.key, source.Read(s));
return (dynamic)result;
}
}
/// <summary>
/// Gets the p frame procedure.
/// </summary>
/// <param name="chapter">The chapter.</param>
/// <returns>System.String.</returns>
/// <value>The p frame procedure.</value>
protected abstract string GetPFrameProcedure(string chapter);
class DelData
{
public object Id { get; set; }
public int Id0 { get; set; }
public string Id1 { get; set; }
public Guid Id2 { get; set; }
public string Param { get; set; }
}
/// <summary>
/// get p frame as an asynchronous operation.
/// </summary>
/// <param name="chapter">The chapter.</param>
/// <param name="sources">The sources.</param>
/// <param name="frame">The iframe.</param>
/// <param name="expand">if set to <c>true</c> [expand].</param>
/// <returns>Task<System.ValueTuple<dynamic, KFrameRepository.Check, System.String>>.</returns>
/// <exception cref="ArgumentNullException">DbService</exception>
/// <exception cref="ArgumentNullException">Schema</exception>
public override async Task<(dynamic data, KFrameRepository.FrameCheck check, string etag)> GetPFrameAsync(string chapter, IEnumerable<IKFrameSource> sources, DateTime frame, bool expand)
{
if (DbService == null)
throw new ArgumentNullException(nameof(DbService));
if (string.IsNullOrEmpty(Schema))
throw new ArgumentNullException(nameof(Schema));
var frameL = frame.ToLocalTime();
using (var ctx = DbService.GetConnection(ConnectionName))
{
var s = await ctx.QueryMultipleAsync(GetPFrameProcedure(chapter), new { iframe = frame, iframeL = frameL, expand }, commandType: CommandType.StoredProcedure);
var f = s.Read().Single(); var frameId = (int?)f.FrameId;
var etag = Convert.ToBase64String(BitConverter.GetBytes(((DateTime)f.Frame).Ticks));
if (frameId == null)
return (null, null, etag);
var ddel = s.Read<int>().Single();
var del = expand ? s.Read<DelData>().Select(x => new KFrameRepository._del_
{
id = UseVariant ? $"{x.Id}" : $"{(x.Id0 != -1 ? x.Id0.ToString() : string.Empty)}{x.Id1}{(x.Id2 != Guid.Empty ? x.Id2.ToString() : string.Empty)}",
t = x.Param
}).ToList() : null;
var maxDate = DateTime.MinValue;
var result = (IDictionary<string, object>)(expand ? new ExpandoObject() : null);
result?.Add("del", del);
foreach (var source in sources.Cast<IKFrameDbSource>())
{
var date = s.Read<DateTime?>().Single();
if (date != null && date.Value > maxDate)
maxDate = date.Value;
result?.Add(source.Param.key, source.Read(s));
}
return ((dynamic)result, new KFrameRepository.FrameCheck { Frame = frame, Keys = new[] { frameId.Value, ddel }, MaxDate = maxDate }, etag);
}
}
/// <summary>
/// Clears the asynchronous.
/// </summary>
/// <param name="b">The b.</param>
/// <param name="ctx">The CTX.</param>
/// <param name="chapter">The chapter.</param>
/// <param name="sources">The sources.</param>
/// <returns>Task.</returns>
protected abstract Task ClearAsync(StringBuilder b, IDbConnection ctx, string chapter, IEnumerable<IKFrameDbSource> sources);
/// <summary>
/// clear as an asynchronous operation.
/// </summary>
/// <param name="chapter">The chapter.</param>
/// <param name="sources">The sources.</param>
/// <returns>Task<System.String>.</returns>
/// <exception cref="ArgumentNullException">DbService</exception>
/// <exception cref="ArgumentNullException">Schema</exception>
public override async Task<string> ClearAsync(string chapter, IEnumerable<IKFrameSource> sources)
{
if (DbService == null)
throw new ArgumentNullException(nameof(DbService));
if (string.IsNullOrEmpty(Schema))
throw new ArgumentNullException(nameof(Schema));
var b = new StringBuilder();
using (var ctx = DbService.GetConnection(ConnectionName))
await ClearAsync(b, ctx, chapter, sources.Cast<IKFrameDbSource>());
b.AppendLine("DONE");
return b.ToString();
}
/// <summary>
/// Databases the install asynchronous.
/// </summary>
/// <param name="b">The b.</param>
/// <param name="ctx">The CTX.</param>
/// <param name="chapter">The chapter.</param>
/// <param name="sources">The sources.</param>
/// <returns>Task.</returns>
protected abstract Task InstallAsync(StringBuilder b, IDbConnection ctx, string chapter, IEnumerable<IKFrameDbSource> sources);
/// <summary>
/// database install as an asynchronous operation.
/// </summary>
/// <param name="chapter">The chapter.</param>
/// <param name="sources">The sources.</param>
/// <returns>Task<System.String>.</returns>
/// <exception cref="ArgumentNullException">DbService</exception>
/// <exception cref="ArgumentNullException">Schema</exception>
public override async Task<string> InstallAsync(string chapter, IEnumerable<IKFrameSource> sources)
{
if (DbService == null)
throw new ArgumentNullException(nameof(DbService));
if (string.IsNullOrEmpty(Schema))
throw new ArgumentNullException(nameof(Schema));
var b = new StringBuilder();
using (var ctx = DbService.GetConnection(ConnectionName))
await InstallAsync(b, ctx, chapter, sources.Cast<IKFrameDbSource>());
b.AppendLine("DONE");
return b.ToString();
}
/// <summary>
/// Databases the uninstall asynchronous.
/// </summary>
/// <param name="b">The b.</param>
/// <param name="ctx">The CTX.</param>
/// <param name="chapter">The chapter.</param>
/// <param name="sources">The sources.</param>
/// <returns>Task.</returns>
protected abstract Task UninstallAsync(StringBuilder b, IDbConnection ctx, string chapter, IEnumerable<IKFrameDbSource> sources);
/// <summary>
/// database uninstall as an asynchronous operation.
/// </summary>
/// <param name="chapter">The chapter.</param>
/// <param name="sources">The sources.</param>
/// <returns>Task<System.String>.</returns>
/// <exception cref="ArgumentNullException">DbService</exception>
/// <exception cref="ArgumentNullException">Schema</exception>
/// <exception cref="ArgumentNullException">DbService</exception>
public override async Task<string> UninstallAsync(string chapter, IEnumerable<IKFrameSource> sources)
{
if (DbService == null)
throw new ArgumentNullException(nameof(DbService));
if (string.IsNullOrEmpty(Schema))
throw new ArgumentNullException(nameof(Schema));
var b = new StringBuilder();
using (var ctx = DbService.GetConnection(ConnectionName))
await UninstallAsync(b, ctx, chapter, sources.Cast<IKFrameDbSource>());
b.AppendLine("DONE");
return b.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ContactUs
{
public partial class ThankYou : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string sSiteName = ConfigurationManager.AppSettings["SiteName"];
string sSiteTitle = ConfigurationManager.AppSettings["SiteTitle"];
Page.Title = sSiteTitle;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class InputManager
{
#region template
public static bool get()
{
return false;
}
public static bool getUp()
{
return false;
}
public static bool getDown()
{
return false;
}
#endregion
#region movement
#region foward
static KeyCode _forward = KeyCode.W;
public static bool getMoveForward()
{
return Input.GetKey(_forward);
}
public static bool getMoveForwardUp()
{
return Input.GetKeyUp(_forward);
}
public static bool getMoveForwardDown()
{
return Input.GetKeyDown(_forward);
}
#endregion
#region Back
static KeyCode _back = KeyCode.S;
public static bool getMoveBack()
{
return Input.GetKey(_back);
}
public static bool getMoveBackUp()
{
return Input.GetKeyUp(_back); ;
}
public static bool getMoveBackDown()
{
return Input.GetKeyDown(_back); ;
}
#endregion
#region Left
static KeyCode _left = KeyCode.A;
public static bool getMoveLeft()
{
return Input.GetKey(_left);
}
public static bool getMoveLeftUp()
{
return Input.GetKeyUp(_left);
}
public static bool getMoveLeftDown()
{
return Input.GetKeyDown(_left);
}
#endregion
#region Right
static KeyCode _right = KeyCode.D;
public static bool getMoveRight()
{
return Input.GetKey(_right);
}
public static bool getMoveRightUp()
{
return Input.GetKeyUp(_right);
}
public static bool getMoveRightDown()
{
return Input.GetKeyDown(_right);
}
#endregion
#region Dash
static KeyCode _dash = KeyCode.LeftShift;
public static bool getDash()
{
return Input.GetKey(_dash);
}
public static bool getDashUp()
{
return Input.GetKeyUp(_dash);
}
public static bool getDashDown()
{
return Input.GetKeyDown(_dash);
}
#endregion
#region Jump
static KeyCode _jump = KeyCode.Space;
public static bool getJump()
{
return Input.GetKey(_jump);
}
public static bool getJumpUp()
{
return Input.GetKeyUp(_jump);
}
public static bool getJumpDown()
{
return Input.GetKeyDown(_jump);
}
#endregion
#endregion
#region camera
public static Vector2 getMouse()
{
return new Vector2(Input.GetAxis("MouseHorizontal"), Input.GetAxis("MouseVertical"));
}
#endregion
}
|
namespace rm.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Ridge")]
public partial class Ridge
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Ridge()
{
ActionJournals = new HashSet<ActionJournal>();
Lapms = new HashSet<Lapm>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int idRidge { get; set; }
public int? Humidity { get; set; }
public int? Luminescence { get; set; }
public int Owner_idUser { get; set; }
public int GroundType { get; set; }
public int FetuseType { get; set; }
public int idScenario { get; set; }
public byte? Auto { get; set; }
public int? Temperature { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ActionJournal> ActionJournals { get; set; }
public virtual Fetuse Fetuse { get; set; }
public virtual Ground Ground { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Lapm> Lapms { get; set; }
public virtual Scenario Scenario { get; set; }
public virtual User User { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using BezierMasterNS.MeshesCreating;
namespace MileCode {
public enum Using{
Object,
Mesh,
None
}
public class BeizerMastersLearn : MonoBehaviour {
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IRAP.Global;
namespace BatchSystemMNGNT_Asimco.Entities
{
public class TEntityXMLPORV01 : IXMLNodeObject
{
public string AgencyLeaf { get; set; }
public string SysLogID { get; set; }
public string StationID { get; set; }
public string RoleLeaf { get; set; }
public string CommunityID { get; set; }
public string UserCode { get; set; }
public string ExCode { get; set; }
public string UserID { get; set; }
public string PassWord { get; set; }
public string PONumber { get; set; }
public string POLineNumber { get; set; }
public string POReceiptActionType { get; set; }
public string POLineUM { get; set; }
public string ReceiptQuantityMove1 { get; set; }
public string Stockroom1 { get; set; }
public string Bin1 { get; set; }
public string InventoryCategory1 { get; set; }
public string POLineType { get; set; }
public string ItemNumber { get; set; }
public string NewLot { get; set; }
public string LotNumberAssignmentPolicy { get; set; }
public string LotNumberDefault { get; set; }
public string VendorLotNumber { get; set; }
public string FirstReceiptDate { get; set; }
public string PromisedDate { get; set; }
public string POReceiptDate { get; set; }
public string GetXMLString()
{
return IRAPXMLUtils.ObjectToXMLString(this, "Parameters", "Param");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EX_6C_Inheritance_Weapons
{
class Weapon
{
public void StartFiring(string firingNoise)
{
Console.WriteLine($"Firing weapon: {firingNoise}");
}
public virtual void Fire()
{
Console.WriteLine("Default: Firing weapon");
}
}
class SmallCaliberWeapon : Weapon
{
public void Handgunload()
{
Console.WriteLine("Loading Colt 45");
}
public override void Fire()
{
Console.WriteLine("Firing small weapons");
}
}
class DirectFireMethod : Weapon
{
public void Hellfireload()
{
Console.WriteLine("loading Hellfire");
}
public override void Fire()
{
Console.WriteLine("Firing Hellfire Missiles");
}
}
class InDirectFireMethod : Weapon
{
public void Howitzerload()
{
Console.WriteLine("loading Howitzer");
}
public override void Fire()
{
Console.WriteLine("Firing Artillery Weapons");
}
}
}
|
using Source.Code.Utils;
using TMPro;
using UnityEngine;
namespace Source.Code.UI
{
public class TeamVsTeamScore : MonoBehaviour
{
[SerializeField] private TextMeshProUGUI leftScoreTMP;
[SerializeField] private TextMeshProUGUI rightScoreTMP;
[SerializeField] private TextMeshProUGUI whoWinsTitleTMP;
private SessionSettings sessionSettings;
private void Start()
{
sessionSettings = SessionSettings.Instance;
sessionSettings.Factions[0].ScoresChanged += OnLeftTeamScoreChanged;
sessionSettings.Factions[1].ScoresChanged += OnRightTeamScoreChanged;
leftScoreTMP.text = "0";
rightScoreTMP.text = "0";
sessionSettings.GlobalState.GlobalStateChanged += OnGlobalStateChanged;
}
private void OnGlobalStateChanged(GlobalState.States state)
{
switch (state)
{
case GlobalState.States.WaitingForOtherPlayers:
break;
case GlobalState.States.Game:
break;
case GlobalState.States.GameEnded:
{
if (sessionSettings.Factions[0].Scores == sessionSettings.Factions[1].Scores)
{
whoWinsTitleTMP.color = Color.black;
whoWinsTitleTMP.text = "Draw!";
whoWinsTitleTMP.gameObject.SetActive(true);
Debug.Log("Draw");
return;
}
bool isBlueWins = sessionSettings.Factions[0].Scores > sessionSettings.Factions[1].Scores;
string winnerSideName = isBlueWins ? "Blue" : "Red";
whoWinsTitleTMP.color = isBlueWins ? Color.blue : Color.red;
whoWinsTitleTMP.text = winnerSideName + " Team won!";
whoWinsTitleTMP.gameObject.SetActive(true);
Debug.Log("Winner is " + sessionSettings.GlobalState.FactionsSortedByScore[0].ID + " with score " + sessionSettings.GlobalState.FactionsSortedByScore[0].Scores);
Debug.Log("Loser is " + sessionSettings.GlobalState.FactionsSortedByScore[1].ID + " with score " + sessionSettings.GlobalState.FactionsSortedByScore[1].Scores);
}
break;
default:
break;
}
}
private void OnLeftTeamScoreChanged(int score)
{
leftScoreTMP.text = score.ToString();
}
private void OnRightTeamScoreChanged(int score)
{
rightScoreTMP.text = score.ToString();
}
}
} |
using UnityEngine;
public class Collectible : Interactable {
public Item item;
public override void ProcessDefaultInteraction()
{
base.ProcessDefaultInteraction();
PickUp();
}
public override void ProcessAltInteraction()
{
base.ProcessAltInteraction();
Examine();
}
void PickUp()
{
print("Picked up " + item.name);
Destroy(gameObject);
}
void Examine()
{
print(item.description);
}
}
|
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace skyConverter.ModelStructure
{
class Model : ISerializer
{
private String _name = "";
private List<Mesh> _meshes;
private Material _material;
private bool isMultipart = false;
private int numberOfParts = 0;
private int numberOfPart = 0;
public Model(String _name)
{
this._name = _name;
this._meshes = new List<Mesh>();
this._material = new Material("Materials/Phong.mat", "PHONG");
this._material.specular = new double[] { 1.0, 1.0, 1.0, 1.0 };
this._material.specularIntensity = 0.0;
}
public void setIsMultipart(bool isMultiPart)
{
this.isMultipart = isMultiPart;
}
public void setNumberOfParts(int parts)
{
this.numberOfParts = parts;
}
public void setNumberOfPart(int part)
{
this.numberOfPart = part;
}
public int GetNumberOfPart()
{
return this.numberOfPart;
}
public void addMesh(Mesh mesh)
{
_meshes.Add(mesh);
}
public JObject serializeObject()
{
JObject obj = new JObject();
obj.Add("Name", _name);
obj.Add("Material", this._material.serializeObject());
JObject multipartObj = new JObject();
multipartObj.Add("UseMultipart", isMultipart);
multipartObj.Add("Part", numberOfPart);
multipartObj.Add("TotalParts", numberOfParts);
obj.Add("Multipart", multipartObj);
if(_meshes.Count != 0){
JArray meshesNode = new JArray();
for (int i = 0; i < _meshes.Count; i++)
{
Mesh m = _meshes[i];
meshesNode.Add(m.serializeObject());
}
obj.Add("Meshes", meshesNode);
return obj;
}
return null;
}
public JArray serializeArray()
{
return null;
}
}
}
|
using System.Reflection;
using AutoTests.Framework.Models;
namespace AutoTests.Framework.Web.Binding
{
public class HandlerArgs
{
private readonly MethodInfo methodInfo;
private readonly PageObject pageObject;
public PropertyLink PropertyLink { get; }
public HandlerArgs(PageObject pageObject, MethodInfo methodInfo, PropertyLink propertyLink)
{
this.pageObject = pageObject;
this.methodInfo = methodInfo;
PropertyLink = propertyLink;
}
public object Invoke(params object[] args)
{
return methodInfo.Invoke(pageObject, args);
}
}
} |
namespace LiveCode.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Ozone")]
public partial class Ozone
{
[Key]
public int Ozone_Id { get; set; }
[Column(TypeName = "date")]
public DateTime DateTimeStart { get; set; }
[Column("Ozone")]
public double? Ozone1 { get; set; }
[Required]
[StringLength(10)]
public string Unit { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace VEE.Util
{
public static class ImageUtil
{
public enum ImageType
{
Png,
Xpng,
Gif,
Jpg,
Jpeg,
None,
}
public static Dictionary<string, ImageType> ImageTypes = new Dictionary<string, ImageType>
{
{".jpg", ImageType.Jpg},
{".jpeg",ImageType.Jpeg},
{".png",ImageType.Png},
{".x-png",ImageType.Xpng},
{".gif",ImageType.Gif}
};
public static Dictionary<ImageType, ImageFormat> ImageFormats = new Dictionary<ImageType, ImageFormat>
{
{ImageType.Jpg, ImageFormat.Jpeg},
{ImageType.Jpeg, ImageFormat.Jpeg},
{ImageType.Png, ImageFormat.Png},
{ImageType.Xpng, ImageFormat.Png},
{ImageType.Gif, ImageFormat.Gif}
};
public static byte[] ToByteArray(this Image image, ImageType type)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, ImageFormats[type]);
return ms.ToArray();
}
public static Image ToImage(this byte[] byteArrayIn)
{
if (byteArrayIn == null || byteArrayIn.Length == 0)
{
return null;
}
ImageConverter converter = new ImageConverter();
return (Image)converter.ConvertFrom(byteArrayIn);
}
public static Image ScaleImage(this Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var graphics = Graphics.FromImage(newImage))
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
}
} |
using System;
using Newtonsoft.Json;
namespace FiroozehGameService.Models.GSLive.RT
{
[Serializable]
internal class Leave
{
[JsonProperty("1")] public string MemberLeaveId;
[JsonProperty("2")] public string RoomId;
public Leave(string memberLeaveId, string roomId)
{
MemberLeaveId = memberLeaveId;
RoomId = roomId;
}
public override string ToString()
{
return "Leave{" +
"MemberLeaveID='" + MemberLeaveId + '\'' +
", RoomID='" + RoomId + '\'' +
'}';
}
}
} |
namespace Rhino.Mocks.Tests
{
using System.IO;
using Xunit;
using Rhino.Mocks.Impl;
public class TraceWriterWithStackTraceExpectationWriterFixture
{
[Fact]
public void WillPrintLogInfoWithStackTrace()
{
TraceWriterWithStackTraceExpectationWriter expectationWriter = new TraceWriterWithStackTraceExpectationWriter();
StringWriter writer = new StringWriter();
expectationWriter.AlternativeWriter = writer;
RhinoMocks.Logger = expectationWriter;
IDemo mock = MockRepository.GenerateStrictMock<IDemo>();
mock.Expect(x => x.VoidNoArgs());
mock.VoidNoArgs();
mock.VerifyAllExpectations();
Assert.Contains("WillPrintLogInfoWithStackTrace", writer.GetStringBuilder().ToString());
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Framework.Core.Common;
namespace Tests.Pages.Van.SocialOrg.DifferentTasks
{
public class Fundraise : GeneralTask
{
public Fundraise(Driver driver) : base(driver) { }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner3 : MonoBehaviour
{
public GameObject Jeep3;
public Semaforo3 semaforo3;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("GenerarCarro3", 1, 2);
}
// Update is called once per frame
void Update()
{
}
void GenerarCarro3()
{
if (semaforo3.Semaforo3verde)
{
Instantiate(Jeep3, transform.position, Quaternion.identity);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SAAS.FrameWork
{
public class SysRequesModel<TModel>
{
public RequestHeader Header { get; set; }
/// <summary>
/// 对象
/// </summary>
public TModel Body { get; set; }
public SysRequesModel()
{
Header = new RequestHeader();
}
}
public class RequestHeader
{
public string RequestType { get; set; }
/// <summary>
/// 运用程序ID
/// </summary>
public int AppID { get; set; }
/// <summary>
/// 每次访问 生成的GUID,查日记的时候,可以按照GUID去查询
/// </summary>
public string GUID { get; set; }
}
public class SysResponseModel
{
public ResponseHeader Header { get; set; }
public SysResponseModel()
{
Header = new ResponseHeader();
}
}
public class SysResponseModel<TModel> : SysResponseModel
{
public TModel Body { get; set; }
}
public class ResponseHeader
{
/// <summary>
/// 返回错误码,0无错,-1 客户端错误
/// </summary>
public int ReturnCode { get; set; }
/// <summary>
/// 页面属性的名字
/// </summary>
public string PropertyName { get; set; }
/// <summary>
/// 错误信息
/// </summary>
public string Message { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InstanceCreation
{
static class ClassC
{
static ClassC()
{
Console.WriteLine("Static class Initialized");
}
public static void Print()
{
Console.WriteLine("Static class print");
}
}
}
|
using Explayer.Services;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using Unosquare.Labs.EmbedIO;
using Unosquare.Labs.EmbedIO.Modules;
namespace Explayer.Server
{
interface ILocalServer
{
Task<string> Start();
}
class LocalServer : ILocalServer
{
private readonly IHandleStaticFilesService _staticFilesService;
public LocalServer(IHandleStaticFilesService staticFilesService)
{
_staticFilesService = staticFilesService;
}
public static string Url => "http://" + GetLocalIpAddress() + ":8787";
public async Task<string> Start()
{
await _staticFilesService.InitializeStaticFiles();
var filePath = _staticFilesService.DirectoryPath;
// Start the web server
await Task.Factory.StartNew(async () =>
{
using (var server = new WebServer(Url))
{
// Register static files service
server.RegisterModule(new LocalSessionModule());
server.RegisterModule(new StaticFilesModule(filePath));
server.Module<StaticFilesModule>().UseRamCache = false;
server.Module<StaticFilesModule>().DefaultExtension = ".html";
server.Module<StaticFilesModule>().DefaultDocument = "index.html";
server.Module<StaticFilesModule>().UseGzip = false;
// Register socket service
server.RegisterModule(new WebSocketsModule());
server.Module<WebSocketsModule>().RegisterWebSocketsServer<SocketServer>("/socket");
// Run server
await server.RunAsync();
}
});
return Url;
}
private static string GetLocalIpAddress()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
try
{
listener.Start();
return ((IPEndPoint)listener.LocalEndpoint).Address.ToString();
}
finally
{
listener.Stop();
}
}
}
}
|
using GoogleARCore;
using System.Collections.Generic;
using UnityEngine;
namespace ARConfigurator
{
/// <summary>
/// Controls the behaviour of a single placed element at runtime, such as applying/resetting colors and textures.
/// Also constructs a mesh collider upon instantiation.
/// </summary>
public class ElementController : MonoBehaviour
{
// These have to be public because they need to be serialized.
// Only used internally to reconstruct the collider mesh on instantiation.
[HideInInspector] public Vector2[] ColliderMeshUV;
[HideInInspector] public Vector3[] ColliderMeshVertices;
[HideInInspector] public int[] ColliderMeshTriangles;
private ElementMetadata ElementMetadata;
public long CurrentLeftFeatureId = -1;
public long CurrentRightFeatureId = -1;
public long CurrentUpperFeatureId = -1;
private Stack<Color> ColorHistory;
private Renderer[] ElementRenderers;
private Dictionary<int, Color> OriginalColors;
private Dictionary<int, Texture> OriginalTextures;
private bool IsColliding = false;
// Note: initialization logic HAS to happen inside Awake instead of Start
// Otherwise, the collider won't have enough time to instantiate when element is placed.
void Awake()
{
ElementMetadata = GetComponent<ElementMetadata>();
ElementRenderers = GetComponentsInChildren<Renderer>();
ColorHistory = new Stack<Color>();
OriginalColors = new Dictionary<int, Color>();
OriginalTextures = new Dictionary<int, Texture>();
foreach (Renderer renderer in ElementRenderers)
{
foreach (Material material in renderer.materials)
{
OriginalColors.Add(material.GetInstanceID(), material.color);
OriginalTextures.Add(material.GetInstanceID(), material.mainTexture);
}
}
// Rebuild the collider mesh.
var colliderMesh = new Mesh();
colliderMesh.vertices = ColliderMeshVertices;
colliderMesh.triangles = ColliderMeshTriangles;
colliderMesh.uv = ColliderMeshUV;
colliderMesh.RecalculateNormals();
colliderMesh.RecalculateBounds();
// Add a mesh collider to the prefab.
var collider = gameObject.AddComponent<MeshCollider>();
collider.sharedMesh = colliderMesh;
collider.convex = true;
collider.isTrigger = true;
// Add physics to the element
var rb = gameObject.AddComponent<Rigidbody>();
rb.isKinematic = true;
}
public long GetFeatureId()
{
return ElementMetadata.FeatureId;
}
public void Colorize(Color color)
{
foreach (Renderer renderer in ElementRenderers)
{
foreach (Material material in renderer.materials)
{
material.color = color;
}
}
ColorHistory.Push(color);
}
public void RestorePreviousColor()
{
if (ColorHistory.Count > 1)
{
ColorHistory.Pop();
Color lastColor = ColorHistory.Peek();
foreach (Renderer renderer in ElementRenderers)
{
foreach (Material material in renderer.materials)
{
material.color = lastColor;
}
}
}
else
{
if (ColorHistory.Count == 1) ColorHistory.Pop();
foreach (Renderer renderer in ElementRenderers)
{
foreach (Material material in renderer.materials)
{
material.color = OriginalColors[material.GetInstanceID()];
}
}
}
}
public void SetTexture(Texture2D texture)
{
foreach (Renderer renderer in ElementRenderers)
{
foreach (Material material in renderer.materials)
{
material.mainTexture = texture;
}
}
}
public void RestoreTextures()
{
foreach (Renderer renderer in ElementRenderers)
{
foreach (Material material in renderer.materials)
{
material.mainTexture = OriginalTextures[material.GetInstanceID()];
}
}
}
public void MarkAsInvalid()
{
Colorize(Color.red);
}
public bool IsLeftSlotOccupied()
{
return CurrentLeftFeatureId > -1;
}
public bool IsRightSlotOccupied()
{
return CurrentRightFeatureId > -1;
}
public bool IsUpperSlotOccupied()
{
return CurrentUpperFeatureId > -1;
}
private void OnTriggerEnter(Collider otherCollider)
{
var visualizer = otherCollider.gameObject.GetComponent<SolidPlaneVisualizer>();
if (!IsColliding && visualizer != null && visualizer.GetPlaneType() == DetectedPlaneType.Vertical)
{
Colorize(Color.yellow);
IsColliding = true;
}
}
private void OnTriggerExit(Collider otherCollider)
{
var visualizer = otherCollider.gameObject.GetComponent<SolidPlaneVisualizer>();
if (IsColliding && visualizer != null && visualizer.GetPlaneType() == DetectedPlaneType.Vertical)
{
RestorePreviousColor();
IsColliding = false;
}
}
#if UNITY_EDITOR
// This method is only used during database import.
public void SaveColliderMesh(Mesh colliderMesh)
{
ColliderMeshVertices = colliderMesh.vertices;
ColliderMeshTriangles = colliderMesh.triangles;
ColliderMeshUV = colliderMesh.uv;
}
#endif
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LunchBuddies
{
class Restaurant
{
public string RestaurantName;
readonly List<string> _restaurants = new List<string> { "Dinos", "Dinos 1", "Dinos 2", "Dinos 3" };
public Restaurant()
{
Random randomRestaurant = new();
int index = randomRestaurant.Next(_restaurants.Count);
RestaurantName = _restaurants[index];
}
}
}
|
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using FiiiCoin.Business;
using FiiiCoin.Models;
using FiiiCoin.Utility.Api;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace FiiiCoin.Wallet.Test.Bussiness
{
[TestClass]
public class UtxoApiTest
{
[TestMethod]
public async Task TestGetTxOutSetInfo()
{
//Server Test
ApiResponse response = await UtxoApi.GetTxOutSetInfo();
//Client Use
Assert.IsFalse(response.HasError);
TxOutSet result = response.GetResult<TxOutSet>();
Assert.IsNotNull(result);
}
[TestMethod]
public async Task TestGetListUnspent()
{
ApiResponse response = await UtxoApi.ListUnspent(2, 99999, null);
Assert.IsFalse(response.HasError);
List<UnspentUtxo> result = response.GetResult<List<UnspentUtxo>>();
Assert.IsNotNull(result);
}
[TestMethod]
public async Task TestGetUnconfirmedBalance()
{
ApiResponse response = await UtxoApi.GetUnconfirmedBalance();
Assert.IsFalse(response.HasError);
long result = response.GetResult<long>();
Assert.IsNotNull(result);
}
[TestMethod]
public async Task TestGetTxOut()
{
ApiResponse response = await UtxoApi.GetTxOut("474DF906F3A53285EC40566D0BA1AFBD4828BDD3789C9599F6EA0489C4333381", 0, false);
Assert.IsFalse(response.HasError);
TxOutModel result = response.GetResult<TxOutModel>();
Assert.IsNotNull(result);
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Plarium9__10
{
class Program
{
static async Task Main(string[] args)
{
Catalog catalog;
string str, firstName, secondName, groupParam, ch;
BD db = new("catalog.xml");
if (File.Exists("temp\\tempData.xml"))
{
do
{
Console.WriteLine("Обнаружен файл экстренного сохранения ?\nЖелаете его выгрузить : yes/not");
ch = Console.ReadLine();
} while (ch != "yes" && ch != "not");
if (ch == "yes")
{
db.Path = "temp\\tempData.xml";
}
}
catalog = await db.ReadAsync();
Console.WriteLine("Введите название продукта перечень параметров которого вы хотите увидеть");
str = Console.ReadLine();
if(catalog[str] != null) catalog[str].ProductGroup.ShowParamsGroups();
Console.WriteLine("Введите с каким параметром товар вас не интересует");
str = Console.ReadLine();
catalog.ShowWithoutParameter(str);
Console.WriteLine("Введите какую группу вы хотите вывести");
str = Console.ReadLine();
catalog.ShowWithParameter(str);
Console.ReadKey();
catalog.Show();
Console.WriteLine("Введите продукты c каким параметром удалять");
str = Console.ReadLine();
catalog.Remove(str);
catalog.Show();
Console.WriteLine("Введите в какой товар вы хотите переместить группу пораметров");
firstName = Console.ReadLine();
Console.WriteLine("Введите из какого товара вы хотите переместить группу пораметров");
secondName = Console.ReadLine();
Console.WriteLine("Введите название группы пораметров, которую перемещаем");
groupParam = Console.ReadLine();
catalog.MoveParameterGroup(firstName, secondName, groupParam);
Console.WriteLine("\n\nПроизошла замена\n\n");
catalog.Show();
do
{
Console.WriteLine("Желаете сохранить результат работы с каталогом ?\nВведите : yes/not");
ch = Console.ReadLine();
} while (ch != "yes" && ch != "not");
if (ch == "yes"){
db.Path = "catalog.xml";
Thread saveThread = new(new ParameterizedThreadStart(db.SaveCatalog));
saveThread.Start(catalog);
}
do
{
Console.WriteLine("Желаете увидеть выборку ?\nВведите : yes/not");
ch = Console.ReadLine();
} while (ch != "yes" && ch != "not");
if (ch == "yes"){
Thread myThread = new(new ParameterizedThreadStart(BD.ShowFile));
myThread.Start("data.txt");
}
}
}
} |
using Mojang.Minecraft.Protocol.Providers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mojang.Minecraft
{
/// <summary>
/// UTF-8编码的字符串,首位是字符串长度,长于2,短于240
/// </summary>
public class PString : IPackageField
{
protected string _InnerString;
public PString()
{
}
public PString(string str)
{
_InnerString = str ?? string.Empty;
}
public override string ToString() => _InnerString;
internal virtual void AppendIntoField(FieldMaker fieldMaker)
{
var bytes = Encoding.UTF8.GetBytes(_InnerString);
var length = new VarInt((uint)bytes.Length);
fieldMaker.AppendPackageField(length);
fieldMaker.AppendBytes(bytes);
//fieldMaker.AppendVarintLengthPrefixedBytes(Encoding.UTF8.GetBytes(_InnerString));
}
void IPackageField.AppendIntoField(FieldMaker fieldMaker)
{
AppendIntoField(fieldMaker);
}
void IPackageField.FromField(FieldMatcher fieldMatcher)
{
FromField(fieldMatcher);
}
internal virtual void FromField(FieldMatcher fieldMatcher)
{
var stringLength = fieldMatcher.MatchPackageField<VarInt>();
var stringData = fieldMatcher.ReadBytes(stringLength);
if (stringData.Length != stringLength)
throw new ArgumentException("字符串长度错误");
_InnerString = Encoding.UTF8.GetString(stringData);
}
public static implicit operator string (PString str)
=> str.ToString();
public static implicit operator PString (string str)
=> new PString(str);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using BO;
namespace DAL_
{
public class Program
{
public static void Main(string[] args)
{
}
}
}
|
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace FifthBot.Migrations
{
public partial class cleanMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Attacks",
columns: table => new
{
MessageID = table.Column<ulong>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
AttackerId = table.Column<ulong>(nullable: false),
TargetId = table.Column<ulong>(nullable: false),
Name = table.Column<string>(nullable: true),
Category = table.Column<string>(nullable: true),
DateandTime = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Attacks", x => x.MessageID);
});
migrationBuilder.CreateTable(
name: "Commands",
columns: table => new
{
CommandID = table.Column<ulong>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
MessageID = table.Column<ulong>(nullable: false),
ActorID = table.Column<ulong>(nullable: false),
TargetID = table.Column<ulong>(nullable: false),
ChannelID = table.Column<ulong>(nullable: false),
CommandName = table.Column<string>(nullable: true),
CommandData = table.Column<string>(nullable: true),
CommandStep = table.Column<int>(nullable: false),
DateTime = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Commands", x => x.CommandID);
});
migrationBuilder.CreateTable(
name: "IntroChannels",
columns: table => new
{
ChannelID = table.Column<ulong>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
ServerID = table.Column<ulong>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_IntroChannels", x => x.ChannelID);
});
migrationBuilder.CreateTable(
name: "KinkEmojis",
columns: table => new
{
JoinID = table.Column<ulong>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
KinkID = table.Column<ulong>(nullable: false),
ServerID = table.Column<ulong>(nullable: false),
EmojiName = table.Column<string>(nullable: true),
KinkGroupID = table.Column<ulong>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_KinkEmojis", x => x.JoinID);
});
migrationBuilder.CreateTable(
name: "KinkGroupMenus",
columns: table => new
{
JoinID = table.Column<ulong>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
KinkGroupID = table.Column<ulong>(nullable: false),
ServerID = table.Column<ulong>(nullable: false),
KinkMsgID = table.Column<ulong>(nullable: false),
KinkChannelID = table.Column<ulong>(nullable: false),
LimitMsgID = table.Column<ulong>(nullable: false),
LimitChannelID = table.Column<ulong>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_KinkGroupMenus", x => x.JoinID);
});
migrationBuilder.CreateTable(
name: "KinkGroups",
columns: table => new
{
KinkGroupID = table.Column<ulong>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
KinkGroupName = table.Column<string>(nullable: true),
KinkGroupDescrip = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_KinkGroups", x => x.KinkGroupID);
});
migrationBuilder.CreateTable(
name: "Kinks",
columns: table => new
{
KinkID = table.Column<ulong>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
KinkName = table.Column<string>(nullable: true),
KinkDesc = table.Column<string>(nullable: true),
KinkGroupID = table.Column<ulong>(nullable: false),
AliasFor = table.Column<ulong>(nullable: false),
GroupOrder = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Kinks", x => x.KinkID);
});
migrationBuilder.CreateTable(
name: "ServerSettings",
columns: table => new
{
ServerID = table.Column<ulong>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
ServerName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ServerSettings", x => x.ServerID);
});
migrationBuilder.CreateTable(
name: "Stones",
columns: table => new
{
UserId = table.Column<ulong>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Amount = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Stones", x => x.UserId);
});
migrationBuilder.CreateTable(
name: "UserKinks",
columns: table => new
{
JoinID = table.Column<ulong>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
KinkID = table.Column<ulong>(nullable: false),
UserID = table.Column<ulong>(nullable: false),
IsLimit = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserKinks", x => x.JoinID);
});
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
UserID = table.Column<ulong>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
ServerID = table.Column<ulong>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.UserID);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Attacks");
migrationBuilder.DropTable(
name: "Commands");
migrationBuilder.DropTable(
name: "IntroChannels");
migrationBuilder.DropTable(
name: "KinkEmojis");
migrationBuilder.DropTable(
name: "KinkGroupMenus");
migrationBuilder.DropTable(
name: "KinkGroups");
migrationBuilder.DropTable(
name: "Kinks");
migrationBuilder.DropTable(
name: "ServerSettings");
migrationBuilder.DropTable(
name: "Stones");
migrationBuilder.DropTable(
name: "UserKinks");
migrationBuilder.DropTable(
name: "Users");
}
}
}
|
using ApartmentApps.Data;
namespace ApartmentApps.Api
{
///// <summary>
///// Handles the syncronization of data between yardi and apartment apps.
///// </summary>
//public class YardiIntegration : PropertyIntegrationAddon, IMaintenanceRequestCheckinEvent, IMaintenanceSubmissionEvent
//{
// public override bool Filter()
// {
// return UserContext.CurrentUser.Property.YardiInfo != null;
// }
// public void MaintenanceRequestSubmited( MaitenanceRequest maitenanceRequest)
// {
// // Sync with entrata on work order
// }
// public void MaintenanceRequestCheckin( MaintenanceRequestCheckin maitenanceRequest, MaitenanceRequest request)
// {
// }
// public YardiIntegration(IUserContext userContext) : base(TODO, userContext)
// {
// }
//}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Focuswin.SP.Base.Utility;
using Microsoft.SharePoint;
using YFVIC.DMS.Model.Models.Settings;
using YFVIC.DMS.Model.Models.Common;
using YFVIC.DMS.Model.Models.HR;
using YFVIC.DMS.Model.Models.FileInfo;
using YFVIC.DMS.Model.Models.WorkFlow;
using YFVIC.DMS.Model.Models.ExtenalCompany;
using YFVIC.DMS.Model.Models.Project;
namespace YFVIC.DMS.Model.Models.Distribute
{
public class BorrowMgr
{
FileInfoMgr filemgr = new FileInfoMgr();
BorrowFileMgr borrowfilemgr = new BorrowFileMgr();
SPUser user = SPContext.Current.Web.CurrentUser;
SysOrgMgr orgmgr = new SysOrgMgr();
SysUserMgr usermgr = new SysUserMgr();
/// <summary>
/// 添加借阅信息
/// </summary>
/// <param name="obj">借阅信息实体</param>
/// <returns></returns>
public bool InsertBorrow(BorrowEntity obj)
{
SPUser spuser = SPContext.Current.Web.CurrentUser;
string loginname = DMSComm.resolveLogon(spuser.LoginName);
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (DistributeDataContext db = new DistributeDataContext(setting.DefaultValue))
{
Borrow item = new Borrow();
item.AcceptDepartment = obj.AcceptDepartment;
item.FileId = obj.FileId;
item.BorrowType = obj.BorrowType;
item.DisId = obj.DisId;
item.Recipient = obj.Recipient;
item.RecipientMail = obj.RecipientMail;
item.Remark = obj.Remark;
item.FileId = obj.FileId;
item.RecipientType = obj.RecipientType;
item.StartTime = obj.StartTime;
item.EndTime = obj.EndTime;
item.Publish = obj.Publish;
item.ShareDepartment = obj.ShareDepartment;
item.BFId = obj.BFId;
item.Creater = loginname;
item.FileLevel = obj.FileLevel;
item.ShareDepartManager = obj.ShareDepartManager;
item.ShareDepartSM = obj.ShareDeparSM;
item.CreatTime = DateTime.Now.ToString();
item.IsDelete = "false";
db.Borrows.InsertOnSubmit(item);
db.SubmitChanges();
if (obj.BorrowType == "借阅")
{
List<BorrowFileEntity> files = borrowfilemgr.GetBorrowFilesByIds(new PagingEntity { Id = item.BFId });
string filename="";
foreach(BorrowFileEntity file in files)
{
if (string.IsNullOrEmpty(filename))
{
filename = file.FileName;
}
else
{
filename = filename+","+file.FileName;
}
borrowfilemgr.UpdataBFile(file.Id.ToString(), item.Id.ToString());
}
WFCommEntity wfcomm = new WFCommEntity();
WFCommMgr wfcommmgr = new WFCommMgr();
wfcomm.ApplicantAD = loginname;
wfcomm.BorrowId = item.Id.ToString();
wfcomm.WFType = ((int)DMSEnum.WFType.Boorow).ToString();
wfcomm.FileName = filename;
wfcomm.AcceptDepartment = obj.AcceptDepartment;
wfcommmgr.StartBorrowWorkFlow(wfcomm);
}
return true;
}
}
/// <summary>
/// 添加借阅信息
/// </summary>
/// <param name="obj">借阅信息实体</param>
/// <returns></returns>
public bool AddBorrow(BorrowEntity obj)
{
SPUser spuser = SPContext.Current.Web.CurrentUser;
string loginname = DMSComm.resolveLogon(spuser.LoginName);
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
string sendee = "";
using (DistributeDataContext db = new DistributeDataContext(setting.DefaultValue))
{
string[] recipients = obj.Recipient.Split(',');
if (obj.RecipientType == "外部")
{
foreach (string recipient in recipients)
{
Borrow item = new Borrow();
EXUserMgr usermgr = new EXUserMgr();
EXUserEntity user = usermgr.GetEXUserByAccount(new PagingEntity { Account = recipient });
item.AcceptDepartment = obj.AcceptDepartment;
item.FileId = obj.FileId;
item.BorrowType = "分发";
item.DisId = obj.DisId;
item.Recipient = recipient;
item.RecipientMail = user.Email;
item.Remark = obj.Remark;
item.FileId = obj.FileId;
item.RecipientType = "外部";
item.StartTime = obj.StartTime;
item.EndTime = obj.EndTime;
item.Publish = obj.Publish;
item.ShareDepartment = obj.ShareDepartment;
item.BFId = obj.BFId;
item.Creater = loginname;
item.CreatTime = DateTime.Now.ToString();
item.Publish = "Y";
item.IsDelete = "false";
item.FileLevel = obj.FileLevel;
item.ShareDepartManager = obj.ShareDepartManager;
item.ShareDepartSM = obj.ShareDeparSM;
db.Borrows.InsertOnSubmit(item);
db.SubmitChanges();
if (string.IsNullOrEmpty(sendee))
{
sendee = user.Name;
}
else
{
sendee =sendee+","+ user.Name;
}
}
}
else
{
foreach (string recipient in recipients)
{
Borrow item = new Borrow();
item.AcceptDepartment = obj.AcceptDepartment;
item.FileId = obj.FileId;
item.BorrowType = "分发";
item.DisId = obj.DisId;
item.Recipient = recipient;
item.RecipientMail = user.Email;
item.Remark = obj.Remark;
item.FileId = obj.FileId;
item.RecipientType = "部门";
item.StartTime = obj.StartTime;
item.EndTime = obj.EndTime;
item.Publish = obj.Publish;
item.ShareDepartment = obj.ShareDepartment;
item.BFId = obj.BFId;
item.Creater = loginname;
item.CreatTime = DateTime.Now.ToString();
item.Publish = "Y";
item.IsDelete = "false";
item.FileLevel = obj.FileLevel;
item.ShareDepartManager = obj.ShareDepartManager;
item.ShareDepartSM = obj.ShareDeparSM;
db.Borrows.InsertOnSubmit(item);
db.SubmitChanges();
SysOrgEntity oitem = orgmgr.GetSysOrgById(new PagingEntity { Id = recipient });
if (string.IsNullOrEmpty(sendee))
{
sendee = oitem.ChineseName;
}
else
{
sendee = sendee + "," + oitem.ChineseName;
}
}
}
FileInfoEntity file = filemgr.GetFileinfoByid(obj.FileId);
AuditMgr auditmgr = new AuditMgr();
ShareEntity shareaction = new ShareEntity();
shareaction.Sendee = sendee;
shareaction.ItemId = obj.FileId;
shareaction.Type = file.AssTag;
shareaction.Creater = obj.Creater;
shareaction.CreateTime = DateTime.Now.ToString();
shareaction.UserType = "系统";
auditmgr.InsertShareHistory(shareaction);
return true;
}
}
/// <summary>
/// 更新借阅信息
/// </summary>
/// <param name="obj">借阅信息实体</param>
/// <returns></returns>
public bool UpdataBorrow(BorrowEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (DistributeDataContext db = new DistributeDataContext(setting.DefaultValue))
{
Borrow item = db.Borrows.Where(p => p.Id == Convert.ToInt32(obj.Id)).FirstOrDefault();
item.AcceptDepartment = obj.AcceptDepartment;
item.FileId = obj.FileId;
item.BorrowType = obj.BorrowType;
item.DisId = obj.DisId;
item.Recipient = obj.Recipient;
item.RecipientMail = obj.RecipientMail;
item.RecipientType = obj.RecipientType;
item.Remark = obj.Remark;
item.StartTime = obj.StartTime;
item.EndTime = obj.EndTime;
item.Publish = obj.Publish;
item.ShareDepartment = obj.ShareDepartment;
item.UpdataTime = DateTime.Now.ToString();
item.BFId = obj.BFId;
item.FileLevel = obj.FileLevel;
item.ShareDepartManager = obj.ShareDepartManager;
item.ShareDepartSM = obj.ShareDeparSM;
item.IsDelete = obj.IsDelete;
db.SubmitChanges();
return true;
}
}
/// <summary>
/// 删除借阅信息
/// </summary>
/// <param name="id">借阅信息编号</param>
/// <returns></returns>
public bool DelBorrow(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (DistributeDataContext db = new DistributeDataContext(setting.DefaultValue))
{
Borrow item = db.Borrows.Where(p => p.Id == Convert.ToInt32(obj.Id)).FirstOrDefault();
db.Borrows.DeleteOnSubmit(item);
db.SubmitChanges();
return true;
}
}
/// <summary>
/// 获取借阅信息列表
/// </summary>
/// <param name="obj">页面参数</param>
/// <returns></returns>
public List<BorrowEntity> GetBorrows(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (DistributeDataContext db = new DistributeDataContext(setting.DefaultValue))
{
List<Borrow> items = db.Borrows.Where(p => p.BorrowType==obj.AreaType).Skip(obj.LimitRows * (obj.TakeCount - 1)).Take(obj.LimitRows).ToList();
List<BorrowEntity> listitems = new List<BorrowEntity>();
foreach (Borrow item in items)
{
BorrowEntity bitem = new BorrowEntity();
bitem.AcceptDepartment = item.AcceptDepartment;
bitem.FileId = item.FileId;
bitem.BorrowType = item.BorrowType;
bitem.DisId = item.DisId;
bitem.Recipient = item.Recipient;
bitem.RecipientMail = item.RecipientMail;
bitem.Remark = item.Remark;
bitem.RecipientType = item.RecipientType;
bitem.StartTime = item.StartTime;
bitem.EndTime = item.EndTime;
bitem.Publish = item.Publish;
bitem.BFId = item.BFId;
bitem.FileLevel = item.FileLevel;
bitem.ShareDepartment = item.ShareDepartment;
bitem.ShareDepartManager = item.ShareDepartManager;
bitem.ShareDeparSM = item.ShareDepartSM;
bitem.IsDelete = item.IsDelete;
FileInfoEntity file = filemgr.GetFileinfoByid(item.FileId);
bitem.FileName = file.FileName;
bitem.FilePath = file.Path;
listitems.Add(bitem);
}
return listitems;
}
}
/// <summary>
/// 获取公司借阅信息总数
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public int GetBorrowsCount(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (DistributeDataContext db = new DistributeDataContext(setting.DefaultValue))
{
List<Borrow> items = db.Borrows.Where(p => p.BorrowType == obj.AreaType).ToList();
return items.Count;
}
}
/// <summary>
/// 根据借阅信息id获取借阅信息信息
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public BorrowEntity GetBorrowById(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
SysOrgMgr orgmgr = new SysOrgMgr();
SysUserMgr usermgr = new SysUserMgr();
using (DistributeDataContext db = new DistributeDataContext(setting.DefaultValue))
{
Borrow item = db.Borrows.Where(p => p.Id == Convert.ToInt32(obj.Id)).FirstOrDefault();
BorrowEntity bitem = new BorrowEntity();
SysOrgEntity org = new SysOrgEntity();
SysUserEntity user = usermgr.GetSysUserBySid(item.Recipient);
org = orgmgr.GetSysOrgById(new PagingEntity { Id = item.AcceptDepartment });
bitem.Id = item.Id.ToString();
bitem.AcceptDepartment = item.AcceptDepartment;
bitem.AcceptDepartmentName =org.ChineseName;
bitem.FileId = item.FileId;
bitem.BorrowType = item.BorrowType;
bitem.DisId = item.DisId;
bitem.Recipient = item.Recipient;
bitem.RecipientName = user.ChineseName;
bitem.CreateTime = item.CreatTime;
bitem.RecipientMail = item.RecipientMail;
bitem.Remark = item.Remark;
bitem.RecipientType = item.RecipientType;
bitem.StartTime = item.StartTime;
bitem.EndTime = item.EndTime;
bitem.Publish = item.Publish;
bitem.BFId = item.BFId;
bitem.FileLevel = item.FileLevel;
bitem.ShareDepartManager = item.ShareDepartManager;
bitem.ShareDeparSM = item.ShareDepartSM;
bitem.IsDelete = item.IsDelete;
org = orgmgr.GetSysOrgById(new PagingEntity { Id = item.ShareDepartment });
bitem.ShareDepartment = item.ShareDepartment;
bitem.ShareDepartmentName = org.ChineseName;
if (string.IsNullOrEmpty(item.BFId))
{
FileInfoEntity file = filemgr.GetActiveFileinfoByid(item.FileId);
bitem.FileName = file.FileName;
bitem.FilePath = file.Path;
}
else
{
string[] ids = item.BFId.Split(',');
foreach (string id in ids)
{
BorrowFileEntity file = borrowfilemgr.GetBorrowFileById(new PagingEntity { Id = id });
if (string.IsNullOrEmpty(bitem.FileName))
{
bitem.FileName = file.FileName;
bitem.FilePath = file.FilePath;
}
else
{
bitem.FileName =bitem.FileName+","+ file.FileName;
bitem.FilePath = bitem.FilePath + "," + file.FilePath;
}
}
}
return bitem;
}
}
/// <summary>
/// 根据分发Id删除借阅信息
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public bool DelBorrowByDisId(string id)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (DistributeDataContext db = new DistributeDataContext(setting.DefaultValue))
{
List<Borrow> items = db.Borrows.Where(p => p.DisId==id).ToList();
List<BorrowEntity> listitems = new List<BorrowEntity>();
foreach (Borrow item in items)
{
db.Borrows.DeleteOnSubmit(item);
db.SubmitChanges();
}
return true;
}
}
/// <summary>
/// 根据用户获取列表
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public List<BorrowEntity> GetBorrrowByUser(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (DistributeDataContext db = new DistributeDataContext(setting.DefaultValue))
{
List<Borrow> items = db.Borrows.Where(p => p.Recipient == obj.Applicant && p.RecipientType == obj.UserType && DateTime.Now >= DateTime.Parse(p.StartTime) && DateTime.Now <= DateTime.Parse(p.EndTime)).Skip(obj.LimitRows * (obj.TakeCount - 1)).Take(obj.LimitRows).ToList();
List<BorrowEntity> listitems = new List<BorrowEntity>();
foreach (Borrow item in items)
{
BorrowEntity bitem = new BorrowEntity();
bitem.AcceptDepartment = item.AcceptDepartment;
bitem.FileId = item.FileId;
bitem.BorrowType = item.BorrowType;
bitem.DisId = item.DisId;
bitem.Recipient = item.Recipient;
bitem.RecipientMail = item.RecipientMail;
bitem.Remark = item.Remark;
bitem.RecipientType = item.RecipientType;
bitem.StartTime = item.StartTime;
bitem.EndTime = item.EndTime;
bitem.BFId = item.BFId;
bitem.FileLevel = item.FileLevel;
bitem.ShareDepartment = item.ShareDepartment;
bitem.ShareDepartManager = item.ShareDepartManager;
bitem.ShareDeparSM = item.ShareDepartSM;
bitem.IsDelete = item.IsDelete;
FileInfoEntity file = filemgr.GetActiveFileinfoByid(item.FileId);
bitem.FileName = file.FileName;
bitem.FilePath = file.Path;
listitems.Add(bitem);
}
return listitems;
}
}
/// <summary>
/// 根据用户获取列表数量
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public int GetBorrrowByUserCount(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
using (DistributeDataContext db = new DistributeDataContext(setting.DefaultValue))
{
List<Borrow> items = db.Borrows.Where(p => p.Recipient == obj.Applicant && p.RecipientType == obj.UserType && DateTime.Now >= DateTime.Parse(p.StartTime) && DateTime.Now <= DateTime.Parse(p.EndTime)).ToList();
return items.Count;
}
}
/// <summary>
/// 根据分发id获取用户信息
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public List<BorrowEntity> GetBorrowByDisId(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
SysUserMgr usermgr = new SysUserMgr();
using (DistributeDataContext db = new DistributeDataContext(setting.DefaultValue))
{
List<Borrow> items = db.Borrows.Where(p => p.DisId==obj.Id).ToList();
List<BorrowEntity> listitems = new List<BorrowEntity>();
foreach (Borrow item in items)
{
BorrowEntity bitem = new BorrowEntity();
bitem.AcceptDepartment = item.AcceptDepartment;
bitem.FileId = item.FileId;
bitem.BorrowType = item.BorrowType;
bitem.DisId = item.DisId;
SysUserEntity user = usermgr.GetSysUserBySid(item.Recipient);
if (obj.Language == "2052")
{
bitem.Recipient = user.ChineseName;
}
else
{
bitem.Recipient = user.EnglishName;
}
bitem.RecipientMail = item.RecipientMail;
bitem.Remark = item.Remark;
bitem.RecipientType = item.RecipientType;
bitem.StartTime = item.StartTime;
bitem.EndTime = item.EndTime;
bitem.BFId = item.BFId;
bitem.FileLevel = item.FileLevel;
bitem.ShareDepartment = item.ShareDepartment;
bitem.ShareDepartManager = item.ShareDepartManager;
bitem.ShareDeparSM = item.ShareDepartSM;
bitem.IsDelete = item.IsDelete;
FileInfoEntity file = filemgr.GetActiveFileinfoByid(item.FileId);
bitem.FileName = file.FileName;
bitem.FilePath = file.Path;
listitems.Add(bitem);
}
return listitems;
}
}
/// <summary>
/// 获取草稿
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public List<BorrowEntity> GetDrafts(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
SPUser spuser = SPContext.Current.Web.CurrentUser;
string loginname = DMSComm.resolveLogon(spuser.LoginName);
using (DistributeDataContext db = new DistributeDataContext(setting.DefaultValue))
{
List<Borrow> items = db.Borrows.Where(p => p.Creater == loginname && p.IsDraft == "true").OrderByDescending(o => o.Id).ToList();
List<BorrowEntity> listitems = new List<BorrowEntity>();
foreach (Borrow item in items)
{
BorrowEntity bitem = new BorrowEntity();
bitem.Id = item.Id.ToString();
bitem.AcceptDepartment = item.AcceptDepartment;
bitem.FileId = item.FileId;
bitem.BorrowType = item.BorrowType;
bitem.DisId = item.DisId;
bitem.Recipient = item.Recipient;
bitem.RecipientMail = item.RecipientMail;
bitem.Remark = item.Remark;
bitem.RecipientType = item.RecipientType;
bitem.StartTime = item.StartTime;
bitem.EndTime = item.EndTime;
bitem.Publish = item.Publish;
bitem.BFId = item.BFId;
bitem.CreateTime = item.CreatTime;
bitem.ShareDepartment = item.ShareDepartment;
bitem.ShareDepartManager = item.ShareDepartManager;
bitem.ShareDeparSM = item.ShareDepartSM;
bitem.FileLevel = item.FileLevel;
if (!string.IsNullOrEmpty(item.FileId))
{
FileInfoEntity file = filemgr.GetActiveFileinfoByid(item.FileId);
bitem.FileName = file.FileName;
bitem.FilePath = file.Path;
}
else
{
string[] ids = item.BFId.Split(',');
foreach (string id in ids)
{
BorrowFileEntity file = borrowfilemgr.GetBorrowFileById(new PagingEntity { Id = id });
if (string.IsNullOrEmpty(bitem.FileName))
{
bitem.FileName = file.FileName;
bitem.FilePath = file.FilePath;
}
else
{
bitem.FileName = bitem.FileName + "," + file.FileName;
bitem.FilePath = bitem.FilePath + "," + file.FilePath;
}
}
}
listitems.Add(bitem);
}
return listitems;
}
}
/// <summary>
/// 获取分发给我的文件
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public List<FileInfoEntity> GetDistome(PagingEntity obj)
{
List<FileInfoEntity> items = GetAllDistome(obj);
items=items.Skip(obj.LimitRows * (obj.TakeCount - 1)).Take(obj.LimitRows).ToList();
return items;
}
/// <summary>
/// 获取分发给我的文件数量
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public int GetDistomeCount(PagingEntity obj)
{
List<FileInfoEntity> items = GetAllDistome(obj);
return items.Count();
}
/// <summary>
/// 获取所有分发给我的文件
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public List<FileInfoEntity> GetAllDistome(PagingEntity obj)
{
SettingsMgr mgr = new SettingsMgr();
SettingsEntity setting = mgr.GetSystemSetting(SPContext.Current.Site.Url, "DBConnection");
string loginname = DMSComm.resolveLogon(user.LoginName);
List<string> orgs = orgmgr.GetOrgsByuser(loginname);
string company = usermgr.GetUserOrgCompany(loginname);
ProjectUserMgr projectusermgr = new ProjectUserMgr();
using (DistributeDataContext db = new DistributeDataContext(setting.DefaultValue))
{
List<string> projects = projectusermgr.GetProjectsByuserid(loginname);
List<BorrowFileView> disitems = db.BorrowFileViews.Where(p => orgs.Contains(p.Recipient) || projects.Contains(p.Recipient)).GroupBy(o => o.FileName).Select(c => c.OrderByDescending(s => s.CreateTime).First()).ToList();
List<BorrowView> borroweritems = db.BorrowViews.Where(p => orgs.Contains(p.Recipient) || projects.Contains(p.Recipient)).GroupBy(o => o.FileName).Select(c => c.OrderByDescending(s => s.CreateTime).First()).ToList();
List<FileInfoEntity> listitems = new List<FileInfoEntity>();
foreach (BorrowFileView item in disitems)
{
FileInfoEntity file = filemgr.GetFileinfoByid(item.Id.ToString());
file.FileName = item.FileName;
file.CreateTime = item.CreateTime;
SysUserEntity userinfo = usermgr.GetSysUserBySid(item.Creater);
file.Creater = item.Creater;
file.CreaterName = userinfo.ChineseName;
file.VersionNum = item.VersionNum;
file.DisId = item.DisId;
file.BorrowId = item.BorrowId;
file.FilePath = item.FilePath;
file.CreateType = item.CreateType;
listitems.Add(file);
}
foreach (BorrowView item in borroweritems)
{
FileInfoEntity file = filemgr.GetFileinfoByid(item.Id.ToString());
file.FileName = item.FileName;
file.CreateTime = item.CreateTime;
SysUserEntity userinfo = usermgr.GetSysUserBySid(item.Creater);
file.Creater = item.Creater;
file.CreaterName = userinfo.ChineseName;
file.VersionNum = item.VersionNum;
file.DisId = item.DisId;
file.BorrowId = item.BorrowId;
file.FilePath = item.FilePath;
file.CreateType = item.CreateType;
listitems.Add(file);
}
listitems=listitems.GroupBy(o => o.FileName).Select(c => c.OrderByDescending(s => s.CreateTime).First()).ToList();
return listitems;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GardenControlCore.Enums
{
public enum TaskActionId {
RelayOn = 1,
RelayOff,
RelayToggle,
DS18B20Reading,
FloatSensorStateReading
}
public enum TimeIntervalUnit
{
Seconds = 1,
Minutes,
Hours,
Days
}
public enum TriggerType
{
TimeOfDay = 1,
Interval,
Sunrise,
Sunset
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cracking
{
class RemoveDups
{
public static Node deleteDups(Node head) {
HashSet<int> set = new HashSet<int>();
Node previous = null;
Node n = head;
while (n != null) {
if (set.Contains(n.Value))
{
previous.Next = n.Next;// skip to the next node
}
else {
previous = n;
set.Add(n.Value);
}
n = n.Next;
}
return head;
}
}
}
|
using System.Web.Http;
using TfsMobile.Contracts;
namespace TfsMobileServices.Controllers
{
public class LoginController : ApiController
{
[HttpPost]
public bool Login(RequestLoginContract login)
{
var headers = HeradersUtil.FixHeaders(Request.Headers);
var handler = new AuthenticationHandler(headers);
var validated = handler.ValidateUser();
return validated;
}
}
} |
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;
namespace Wee.UI.Core.TagHelpers
{
[HtmlTargetElement("bootstrap-progress")]
public class ProgressTagHelper : TagHelper
{
[HtmlAttributeName("class")]
public string ProgressClass { get; set; }
public ProgressTagHelper()
{
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
(await output.GetChildContentAsync()).GetContent();
output.Attributes.SetAttribute("class", (object) ("progress " + this.ProgressClass));
// ISSUE: reference to a compiler-generated method
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.